repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
55,364
Fix crash with convert namespace
Oopsie.
CyrusNajmabadi
2021-08-03T02:29:24Z
2021-08-03T12:57:53Z
a80a5868188242800f4615dc51ab30ed5e9eaf76
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
Fix crash with convert namespace. Oopsie.
./src/Compilers/CSharp/Portable/Binder/Semantics/OverloadResolution/MethodTypeInference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; /* SPEC: Type inference occurs as part of the compile-time processing of a method invocation and takes place before the overload resolution step of the invocation. When a particular method group is specified in a method invocation, and no type arguments are specified as part of the method invocation, type inference is applied to each generic method in the method group. If type inference succeeds, then the inferred type arguments are used to determine the types of formal parameters for subsequent overload resolution. If overload resolution chooses a generic method as the one to invoke then the inferred type arguments are used as the actual type arguments for the invocation. If type inference for a particular method fails, that method does not participate in overload resolution. The failure of type inference, in and of itself, does not cause a compile-time error. However, it often leads to a compile-time error when overload resolution then fails to find any applicable methods. If the supplied number of arguments is different than the number of parameters in the method, then inference immediately fails. Otherwise, assume that the generic method has the following signature: Tr M<X1...Xn>(T1 x1 ... Tm xm) With a method call of the form M(E1...Em) the task of type inference is to find unique type arguments S1...Sn for each of the type parameters X1...Xn so that the call M<S1...Sn>(E1...Em)becomes valid. During the process of inference each type parameter Xi is either fixed to a particular type Si or unfixed with an associated set of bounds. Each of the bounds is some type T. Each bound is classified as an upper bound, lower bound or exact bound. Initially each type variable Xi is unfixed with an empty set of bounds. */ // This file contains the implementation for method type inference on calls (with // arguments, and method type inference on conversion of method groups to delegate // types (which will not have arguments.) namespace Microsoft.CodeAnalysis.CSharp { internal static class PooledDictionaryIgnoringNullableModifiersForReferenceTypes { private static readonly ObjectPool<PooledDictionary<NamedTypeSymbol, NamedTypeSymbol>> s_poolInstance = PooledDictionary<NamedTypeSymbol, NamedTypeSymbol>.CreatePool(Symbols.SymbolEqualityComparer.IgnoringNullable); internal static PooledDictionary<NamedTypeSymbol, NamedTypeSymbol> GetInstance() { var instance = s_poolInstance.Allocate(); Debug.Assert(instance.Count == 0); return instance; } } // Method type inference can fail, but we still might have some best guesses. internal struct MethodTypeInferenceResult { public readonly ImmutableArray<TypeWithAnnotations> InferredTypeArguments; public readonly bool Success; public MethodTypeInferenceResult( bool success, ImmutableArray<TypeWithAnnotations> inferredTypeArguments) { this.Success = success; this.InferredTypeArguments = inferredTypeArguments; } } internal sealed class MethodTypeInferrer { internal abstract class Extensions { internal static readonly Extensions Default = new DefaultExtensions(); internal abstract TypeWithAnnotations GetTypeWithAnnotations(BoundExpression expr); internal abstract TypeWithAnnotations GetMethodGroupResultType(BoundMethodGroup group, MethodSymbol method); private sealed class DefaultExtensions : Extensions { internal override TypeWithAnnotations GetTypeWithAnnotations(BoundExpression expr) { return TypeWithAnnotations.Create(expr.Type); } internal override TypeWithAnnotations GetMethodGroupResultType(BoundMethodGroup group, MethodSymbol method) { return method.ReturnTypeWithAnnotations; } } } private enum InferenceResult { InferenceFailed, MadeProgress, NoProgress, Success } private enum Dependency { Unknown = 0x00, NotDependent = 0x01, DependsMask = 0x10, Direct = 0x11, Indirect = 0x12 } private readonly ConversionsBase _conversions; private readonly ImmutableArray<TypeParameterSymbol> _methodTypeParameters; private readonly NamedTypeSymbol _constructedContainingTypeOfMethod; private readonly ImmutableArray<TypeWithAnnotations> _formalParameterTypes; private readonly ImmutableArray<RefKind> _formalParameterRefKinds; private readonly ImmutableArray<BoundExpression> _arguments; private readonly Extensions _extensions; private readonly TypeWithAnnotations[] _fixedResults; private readonly HashSet<TypeWithAnnotations>[] _exactBounds; private readonly HashSet<TypeWithAnnotations>[] _upperBounds; private readonly HashSet<TypeWithAnnotations>[] _lowerBounds; private Dependency[,] _dependencies; // Initialized lazily private bool _dependenciesDirty; /// <summary> /// For error recovery, we allow a mismatch between the number of arguments and parameters /// during type inference. This sometimes enables inferring the type for a lambda parameter. /// </summary> private int NumberArgumentsToProcess => System.Math.Min(_arguments.Length, _formalParameterTypes.Length); public static MethodTypeInferenceResult Infer( Binder binder, ConversionsBase conversions, ImmutableArray<TypeParameterSymbol> methodTypeParameters, // We are attempting to build a map from method type parameters // to inferred type arguments. NamedTypeSymbol constructedContainingTypeOfMethod, ImmutableArray<TypeWithAnnotations> formalParameterTypes, // We have some unusual requirements for the types that flow into the inference engine. // Consider the following inference problems: // // Scenario one: // // class C<T> // { // delegate Y FT<X, Y>(T t, X x); // static void M<U, V>(U u, FT<U, V> f); // ... // C<double>.M(123, (t,x)=>t+x); // // From the first argument we infer that U is int. How now must we make an inference on // the second argument? The *declared* type of the formal is C<T>.FT<U,V>. The // actual type at the time of inference is known to be C<double>.FT<int, something> // where "something" is to be determined by inferring the return type of the // lambda by determine the type of "double + int". // // Therefore when we do type inference, if a formal parameter type is a generic delegate // then *its* formal parameter types must be the formal parameter types of the // *constructed* generic delegate C<double>.FT<...>, not C<T>.FT<...>. // // One would therefore suppose that we'd expect the formal parameter types to here // be passed in with the types constructed with the information known from the // call site, not the declared types. // // Contrast that with this scenario: // // Scenario Two: // // interface I<T> // { // void M<U>(T t, U u); // } // ... // static void Goo<V>(V v, I<V> iv) // { // iv.M(v, ""); // } // // Obviously inference should succeed here; it should infer that U is string. // // But consider what happens during the inference process on the first argument. // The first thing we will do is say "what's the type of the argument? V. What's // the type of the corresponding formal parameter? The first formal parameter of // I<V>.M<whatever> is of type V. The inference engine will then say "V is a // method type parameter, and therefore we have an inference from V to V". // But *V* is not one of the method type parameters being inferred; the only // method type parameter being inferred here is *U*. // // This is perhaps some evidence that the formal parameters passed in should be // the formal parameters of the *declared* method; in this case, (T, U), not // the formal parameters of the *constructed* method, (V, U). // // However, one might make the argument that no, we could just add a check // to ensure that if we see a method type parameter as a formal parameter type, // then we only perform the inference if the method type parameter is a type // parameter of the method for which inference is being performed. // // Unfortunately, that does not work either: // // Scenario three: // // class C<T> // { // static void M<U>(T t, U u) // { // ... // C<U>.M(u, 123); // ... // } // } // // The *original* formal parameter types are (T, U); the *constructed* formal parameter types // are (U, U), but *those are logically two different U's*. The first U is from the outer caller; // the second U is the U of the recursive call. // // That is, suppose someone called C<string>.M<double>(string, double). The recursive call should be to // C<double>.M<int>(double, int). We should absolutely not make an inference on the first argument // from U to U just because C<U>.M<something>'s first formal parameter is of type U. If we did then // inference would fail, because we'd end up with two bounds on 'U' -- 'U' and 'int'. We only want // the latter bound. // // What these three scenarios show is that for a "normal" inference we need to have the // formal parameters of the *original* method definition, but when making an inference from a lambda // to a delegate, we need to have the *constructed* method signature in order that the formal // parameters *of the delegate* be correct. // // How to solve this problem? // // We solve it by passing in the formal parameters in their *original* form, but also getting // the *fully constructed* type that the method call is on. When constructing the fixed // delegate type for inference from a lambda, we do the appropriate type substitution on // the delegate. ImmutableArray<RefKind> formalParameterRefKinds, // Optional; assume all value if missing. ImmutableArray<BoundExpression> arguments,// Required; in scenarios like method group conversions where there are // no arguments per se we cons up some fake arguments. ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, Extensions extensions = null) { Debug.Assert(!methodTypeParameters.IsDefault); Debug.Assert(methodTypeParameters.Length > 0); Debug.Assert(!formalParameterTypes.IsDefault); Debug.Assert(formalParameterRefKinds.IsDefault || formalParameterRefKinds.Length == formalParameterTypes.Length); Debug.Assert(!arguments.IsDefault); // Early out: if the method has no formal parameters then we know that inference will fail. if (formalParameterTypes.Length == 0) { return new MethodTypeInferenceResult(false, default(ImmutableArray<TypeWithAnnotations>)); // UNDONE: OPTIMIZATION: We could check to see whether there is a type // UNDONE: parameter which is never used in any formal parameter; if // UNDONE: so then we know ahead of time that inference will fail. } var inferrer = new MethodTypeInferrer( conversions, methodTypeParameters, constructedContainingTypeOfMethod, formalParameterTypes, formalParameterRefKinds, arguments, extensions); return inferrer.InferTypeArgs(binder, ref useSiteInfo); } //////////////////////////////////////////////////////////////////////////////// // // Fixed, unfixed and bounded type parameters // // SPEC: During the process of inference each type parameter is either fixed to // SPEC: a particular type or unfixed with an associated set of bounds. Each of // SPEC: the bounds is of some type T. Initially each type parameter is unfixed // SPEC: with an empty set of bounds. private MethodTypeInferrer( ConversionsBase conversions, ImmutableArray<TypeParameterSymbol> methodTypeParameters, NamedTypeSymbol constructedContainingTypeOfMethod, ImmutableArray<TypeWithAnnotations> formalParameterTypes, ImmutableArray<RefKind> formalParameterRefKinds, ImmutableArray<BoundExpression> arguments, Extensions extensions) { _conversions = conversions; _methodTypeParameters = methodTypeParameters; _constructedContainingTypeOfMethod = constructedContainingTypeOfMethod; _formalParameterTypes = formalParameterTypes; _formalParameterRefKinds = formalParameterRefKinds; _arguments = arguments; _extensions = extensions ?? Extensions.Default; _fixedResults = new TypeWithAnnotations[methodTypeParameters.Length]; _exactBounds = new HashSet<TypeWithAnnotations>[methodTypeParameters.Length]; _upperBounds = new HashSet<TypeWithAnnotations>[methodTypeParameters.Length]; _lowerBounds = new HashSet<TypeWithAnnotations>[methodTypeParameters.Length]; _dependencies = null; _dependenciesDirty = false; } #if DEBUG internal string Dump() { var sb = new System.Text.StringBuilder(); sb.AppendLine("Method type inference internal state"); sb.AppendFormat("Inferring method type parameters <{0}>\n", string.Join(", ", _methodTypeParameters)); sb.Append("Formal parameter types ("); for (int i = 0; i < _formalParameterTypes.Length; ++i) { if (i != 0) { sb.Append(", "); } sb.Append(GetRefKind(i).ToParameterPrefix()); sb.Append(_formalParameterTypes[i]); } sb.Append("\n"); sb.AppendFormat("Argument types ({0})\n", string.Join(", ", from a in _arguments select a.Type)); if (_dependencies == null) { sb.AppendLine("Dependencies are not yet calculated"); } else { sb.AppendFormat("Dependencies are {0}\n", _dependenciesDirty ? "out of date" : "up to date"); sb.AppendLine("dependency matrix (Not dependent / Direct / Indirect / Unknown):"); for (int i = 0; i < _methodTypeParameters.Length; ++i) { for (int j = 0; j < _methodTypeParameters.Length; ++j) { switch (_dependencies[i, j]) { case Dependency.NotDependent: sb.Append("N"); break; case Dependency.Direct: sb.Append("D"); break; case Dependency.Indirect: sb.Append("I"); break; case Dependency.Unknown: sb.Append("U"); break; } } sb.AppendLine(); } } for (int i = 0; i < _methodTypeParameters.Length; ++i) { sb.AppendFormat("Method type parameter {0}: ", _methodTypeParameters[i].Name); var fixedType = _fixedResults[i]; if (!fixedType.HasType) { sb.Append("UNFIXED "); } else { sb.AppendFormat("FIXED to {0} ", fixedType); } sb.AppendFormat("upper bounds: ({0}) ", (_upperBounds[i] == null) ? "" : string.Join(", ", _upperBounds[i])); sb.AppendFormat("lower bounds: ({0}) ", (_lowerBounds[i] == null) ? "" : string.Join(", ", _lowerBounds[i])); sb.AppendFormat("exact bounds: ({0}) ", (_exactBounds[i] == null) ? "" : string.Join(", ", _exactBounds[i])); sb.AppendLine(); } return sb.ToString(); } #endif private RefKind GetRefKind(int index) { Debug.Assert(0 <= index && index < _formalParameterTypes.Length); return _formalParameterRefKinds.IsDefault ? RefKind.None : _formalParameterRefKinds[index]; } private ImmutableArray<TypeWithAnnotations> GetResults() { // Anything we didn't infer a type for, give the error type. // Note: the error type will have the same name as the name // of the type parameter we were trying to infer. This will give a // nice user experience where by we will show something like // the following: // // user types: customers.Select( // we show : IE<TResult> IE<Customer>.Select<Customer,TResult>(Func<Customer,TResult> selector) // // Initially we thought we'd just show ?. i.e.: // // IE<?> IE<Customer>.Select<Customer,?>(Func<Customer,?> selector) // // This is nice and concise. However, it falls down if there are multiple // type params that we have left. for (int i = 0; i < _methodTypeParameters.Length; i++) { if (_fixedResults[i].HasType) { if (!_fixedResults[i].Type.IsErrorType()) { continue; } var errorTypeName = _fixedResults[i].Type.Name; if (errorTypeName != null) { continue; } } _fixedResults[i] = TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol(_constructedContainingTypeOfMethod, _methodTypeParameters[i].Name, 0, null, false)); } return _fixedResults.AsImmutable(); } private bool ValidIndex(int index) { return 0 <= index && index < _methodTypeParameters.Length; } private bool IsUnfixed(int methodTypeParameterIndex) { Debug.Assert(ValidIndex(methodTypeParameterIndex)); return !_fixedResults[methodTypeParameterIndex].HasType; } private bool IsUnfixedTypeParameter(TypeWithAnnotations type) { Debug.Assert(type.HasType); if (type.TypeKind != TypeKind.TypeParameter) return false; TypeParameterSymbol typeParameter = (TypeParameterSymbol)type.Type; int ordinal = typeParameter.Ordinal; return ValidIndex(ordinal) && TypeSymbol.Equals(typeParameter, _methodTypeParameters[ordinal], TypeCompareKind.ConsiderEverything2) && IsUnfixed(ordinal); } private bool AllFixed() { for (int methodTypeParameterIndex = 0; methodTypeParameterIndex < _methodTypeParameters.Length; ++methodTypeParameterIndex) { if (IsUnfixed(methodTypeParameterIndex)) { return false; } } return true; } private void AddBound(TypeWithAnnotations addedBound, HashSet<TypeWithAnnotations>[] collectedBounds, TypeWithAnnotations methodTypeParameterWithAnnotations) { Debug.Assert(IsUnfixedTypeParameter(methodTypeParameterWithAnnotations)); var methodTypeParameter = (TypeParameterSymbol)methodTypeParameterWithAnnotations.Type; int methodTypeParameterIndex = methodTypeParameter.Ordinal; if (collectedBounds[methodTypeParameterIndex] == null) { collectedBounds[methodTypeParameterIndex] = new HashSet<TypeWithAnnotations>(TypeWithAnnotations.EqualsComparer.ConsiderEverythingComparer); } collectedBounds[methodTypeParameterIndex].Add(addedBound); } private bool HasBound(int methodTypeParameterIndex) { Debug.Assert(ValidIndex(methodTypeParameterIndex)); return _lowerBounds[methodTypeParameterIndex] != null || _upperBounds[methodTypeParameterIndex] != null || _exactBounds[methodTypeParameterIndex] != null; } private TypeSymbol GetFixedDelegateOrFunctionPointer(TypeSymbol delegateOrFunctionPointerType) { Debug.Assert((object)delegateOrFunctionPointerType != null); Debug.Assert(delegateOrFunctionPointerType.IsDelegateType() || delegateOrFunctionPointerType is FunctionPointerTypeSymbol); // We have a delegate where the input types use no unfixed parameters. Create // a substitution context; we can substitute unfixed parameters for themselves // since they don't actually occur in the inputs. (They may occur in the outputs, // or there may be input parameters fixed to _unfixed_ method type variables. // Both of those scenarios are legal.) var fixedArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(_methodTypeParameters.Length); for (int iParam = 0; iParam < _methodTypeParameters.Length; iParam++) { fixedArguments.Add(IsUnfixed(iParam) ? TypeWithAnnotations.Create(_methodTypeParameters[iParam]) : _fixedResults[iParam]); } TypeMap typeMap = new TypeMap(_constructedContainingTypeOfMethod, _methodTypeParameters, fixedArguments.ToImmutableAndFree()); return typeMap.SubstituteType(delegateOrFunctionPointerType).Type; } //////////////////////////////////////////////////////////////////////////////// // // Phases // private MethodTypeInferenceResult InferTypeArgs(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: Type inference takes place in phases. Each phase will try to infer type // SPEC: arguments for more type parameters based on the findings of the previous // SPEC: phase. The first phase makes some initial inferences of bounds, whereas // SPEC: the second phase fixes type parameters to specific types and infers further // SPEC: bounds. The second phase may have to be repeated a number of times. InferTypeArgsFirstPhase(ref useSiteInfo); bool success = InferTypeArgsSecondPhase(binder, ref useSiteInfo); return new MethodTypeInferenceResult(success, GetResults()); } //////////////////////////////////////////////////////////////////////////////// // // The first phase // private void InferTypeArgsFirstPhase(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(!_formalParameterTypes.IsDefault); Debug.Assert(!_arguments.IsDefault); // We expect that we have been handed a list of arguments and a list of the // formal parameter types they correspond to; all the details about named and // optional parameters have already been dealt with. // SPEC: For each of the method arguments Ei: for (int arg = 0, length = this.NumberArgumentsToProcess; arg < length; arg++) { BoundExpression argument = _arguments[arg]; TypeWithAnnotations target = _formalParameterTypes[arg]; ExactOrBoundsKind kind = GetRefKind(arg).IsManagedReference() || target.Type.IsPointerType() ? ExactOrBoundsKind.Exact : ExactOrBoundsKind.LowerBound; MakeExplicitParameterTypeInferences(argument, target, kind, ref useSiteInfo); } } private void MakeExplicitParameterTypeInferences(BoundExpression argument, TypeWithAnnotations target, ExactOrBoundsKind kind, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * If Ei is an anonymous function, an explicit type parameter // SPEC: inference is made from Ei to Ti. // (We cannot make an output type inference from a method group // at this time because we have no fixed types yet to use for // overload resolution.) // SPEC: * Otherwise, if Ei has a type U then a lower-bound inference // SPEC: or exact inference is made from U to Ti. // SPEC: * Otherwise, no inference is made for this argument if (argument.Kind == BoundKind.UnboundLambda) { ExplicitParameterTypeInference(argument, target, ref useSiteInfo); } else if (argument.Kind != BoundKind.TupleLiteral || !MakeExplicitParameterTypeInferences((BoundTupleLiteral)argument, target, kind, ref useSiteInfo)) { // Either the argument is not a tuple literal, or we were unable to do the inference from its elements, let's try to infer from argument type if (IsReallyAType(argument.Type)) { ExactOrBoundsInference(kind, _extensions.GetTypeWithAnnotations(argument), target, ref useSiteInfo); } } } private bool MakeExplicitParameterTypeInferences(BoundTupleLiteral argument, TypeWithAnnotations target, ExactOrBoundsKind kind, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // try match up element-wise to the destination tuple (or underlying type) // Example: // if "(a: 1, b: "qq")" is passed as (T, U) arg // then T becomes int and U becomes string if (target.Type.Kind != SymbolKind.NamedType) { // tuples can only match to tuples or tuple underlying types. return false; } var destination = (NamedTypeSymbol)target.Type; var sourceArguments = argument.Arguments; // check if the type is actually compatible type for a tuple of given cardinality if (!destination.IsTupleTypeOfCardinality(sourceArguments.Length)) { // target is not a tuple of appropriate shape return false; } var destTypes = destination.TupleElementTypesWithAnnotations; Debug.Assert(sourceArguments.Length == destTypes.Length); // NOTE: we are losing tuple element names when recursing into argument expressions. // that is ok, because we are inferring type parameters used in the matching elements, // This is not the situation where entire tuple literal is used to infer a single type param for (int i = 0; i < sourceArguments.Length; i++) { var sourceArgument = sourceArguments[i]; var destType = destTypes[i]; MakeExplicitParameterTypeInferences(sourceArgument, destType, kind, ref useSiteInfo); } return true; } //////////////////////////////////////////////////////////////////////////////// // // The second phase // private bool InferTypeArgsSecondPhase(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The second phase proceeds as follows: // SPEC: * If no unfixed type parameters exist then type inference succeeds. // SPEC: * Otherwise, if there exists one or more arguments Ei with corresponding // SPEC: parameter type Ti such that: // SPEC: o the output type of Ei with type Ti contains at least one unfixed // SPEC: type parameter Xj, and // SPEC: o none of the input types of Ei with type Ti contains any unfixed // SPEC: type parameter Xj, // SPEC: then an output type inference is made from all such Ei to Ti. // SPEC: * Whether or not the previous step actually made an inference, we must // SPEC: now fix at least one type parameter, as follows: // SPEC: * If there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o Xi does not depend on any Xj // SPEC: then each such Xi is fixed. If any fixing operation fails then type // SPEC: inference fails. // SPEC: * Otherwise, if there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o there is at least one type parameter Xj that depends on Xi // SPEC: then each such Xi is fixed. If any fixing operation fails then // SPEC: type inference fails. // SPEC: * Otherwise, we are unable to make progress and there are unfixed parameters. // SPEC: Type inference fails. // SPEC: * If type inference neither succeeds nor fails then the second phase is // SPEC: repeated until type inference succeeds or fails. (Since each repetition of // SPEC: the second phase either succeeds, fails or fixes an unfixed type parameter, // SPEC: the algorithm must terminate with no more repetitions than the number // SPEC: of type parameters. InitializeDependencies(); while (true) { var res = DoSecondPhase(binder, ref useSiteInfo); Debug.Assert(res != InferenceResult.NoProgress); if (res == InferenceResult.InferenceFailed) { return false; } if (res == InferenceResult.Success) { return true; } // Otherwise, we made some progress last time; do it again. } } private InferenceResult DoSecondPhase(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * If no unfixed type parameters exist then type inference succeeds. if (AllFixed()) { return InferenceResult.Success; } // SPEC: * Otherwise, if there exists one or more arguments Ei with // SPEC: corresponding parameter type Ti such that: // SPEC: o the output type of Ei with type Ti contains at least one unfixed // SPEC: type parameter Xj, and // SPEC: o none of the input types of Ei with type Ti contains any unfixed // SPEC: type parameter Xj, // SPEC: then an output type inference is made from all such Ei to Ti. MakeOutputTypeInferences(binder, ref useSiteInfo); // SPEC: * Whether or not the previous step actually made an inference, we // SPEC: must now fix at least one type parameter, as follows: // SPEC: * If there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o Xi does not depend on any Xj // SPEC: then each such Xi is fixed. If any fixing operation fails then // SPEC: type inference fails. InferenceResult res; res = FixNondependentParameters(ref useSiteInfo); if (res != InferenceResult.NoProgress) { return res; } // SPEC: * Otherwise, if there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o there is at least one type parameter Xj that depends on Xi // SPEC: then each such Xi is fixed. If any fixing operation fails then // SPEC: type inference fails. res = FixDependentParameters(ref useSiteInfo); if (res != InferenceResult.NoProgress) { return res; } // SPEC: * Otherwise, we are unable to make progress and there are // SPEC: unfixed parameters. Type inference fails. return InferenceResult.InferenceFailed; } private void MakeOutputTypeInferences(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: Otherwise, for all arguments Ei with corresponding parameter type Ti // SPEC: where the output types contain unfixed type parameters but the input // SPEC: types do not, an output type inference is made from Ei to Ti. for (int arg = 0, length = this.NumberArgumentsToProcess; arg < length; arg++) { var formalType = _formalParameterTypes[arg]; var argument = _arguments[arg]; MakeOutputTypeInferences(binder, argument, formalType, ref useSiteInfo); } } private void MakeOutputTypeInferences(Binder binder, BoundExpression argument, TypeWithAnnotations formalType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (argument.Kind == BoundKind.TupleLiteral && (object)argument.Type == null) { MakeOutputTypeInferences(binder, (BoundTupleLiteral)argument, formalType, ref useSiteInfo); } else { if (HasUnfixedParamInOutputType(argument, formalType.Type) && !HasUnfixedParamInInputType(argument, formalType.Type)) { //UNDONE: if (argument->isTYPEORNAMESPACEERROR() && argumentType->IsErrorType()) //UNDONE: { //UNDONE: argumentType = GetTypeManager().GetErrorSym(); //UNDONE: } OutputTypeInference(binder, argument, formalType, ref useSiteInfo); } } } private void MakeOutputTypeInferences(Binder binder, BoundTupleLiteral argument, TypeWithAnnotations formalType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (formalType.Type.Kind != SymbolKind.NamedType) { // tuples can only match to tuples or tuple underlying types. return; } var destination = (NamedTypeSymbol)formalType.Type; Debug.Assert((object)argument.Type == null, "should not need to dig into elements if tuple has natural type"); var sourceArguments = argument.Arguments; // check if the type is actually compatible type for a tuple of given cardinality if (!destination.IsTupleTypeOfCardinality(sourceArguments.Length)) { return; } var destTypes = destination.TupleElementTypesWithAnnotations; Debug.Assert(sourceArguments.Length == destTypes.Length); for (int i = 0; i < sourceArguments.Length; i++) { var sourceArgument = sourceArguments[i]; var destType = destTypes[i]; MakeOutputTypeInferences(binder, sourceArgument, destType, ref useSiteInfo); } } private InferenceResult FixNondependentParameters(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * Otherwise, if there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o Xi does not depend on any Xj // SPEC: then each such Xi is fixed. return FixParameters((inferrer, index) => !inferrer.DependsOnAny(index), ref useSiteInfo); } private InferenceResult FixDependentParameters(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * All unfixed type parameters Xi are fixed for which all of the following hold: // SPEC: * There is at least one type parameter Xj that depends on Xi. // SPEC: * Xi has a non-empty set of bounds. return FixParameters((inferrer, index) => inferrer.AnyDependsOn(index), ref useSiteInfo); } private InferenceResult FixParameters( Func<MethodTypeInferrer, int, bool> predicate, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // Dependency is only defined for unfixed parameters. Therefore, fixing // a parameter may cause all of its dependencies to become no longer // dependent on anything. We need to first determine which parameters need to be // fixed, and then fix them all at once. var needsFixing = new bool[_methodTypeParameters.Length]; var result = InferenceResult.NoProgress; for (int param = 0; param < _methodTypeParameters.Length; param++) { if (IsUnfixed(param) && HasBound(param) && predicate(this, param)) { needsFixing[param] = true; result = InferenceResult.MadeProgress; } } for (int param = 0; param < _methodTypeParameters.Length; param++) { // Fix as much as you can, even if there are errors. That will // help with intellisense. if (needsFixing[param]) { if (!Fix(param, ref useSiteInfo)) { result = InferenceResult.InferenceFailed; } } } return result; } //////////////////////////////////////////////////////////////////////////////// // // Input types // private static bool DoesInputTypeContain(BoundExpression argument, TypeSymbol formalParameterType, TypeParameterSymbol typeParameter) { // SPEC: If E is a method group or an anonymous function and T is a delegate // SPEC: type or expression tree type then all the parameter types of T are // SPEC: input types of E with type T. var delegateOrFunctionPointerType = formalParameterType.GetDelegateOrFunctionPointerType(); if ((object)delegateOrFunctionPointerType == null) { return false; // No input types. } var isFunctionPointer = delegateOrFunctionPointerType.IsFunctionPointer(); if ((isFunctionPointer && argument.Kind != BoundKind.UnconvertedAddressOfOperator) || (!isFunctionPointer && argument.Kind is not (BoundKind.UnboundLambda or BoundKind.MethodGroup))) { return false; // No input types. } var parameters = delegateOrFunctionPointerType.DelegateOrFunctionPointerParameters(); if (parameters.IsDefaultOrEmpty) { return false; } foreach (var parameter in parameters) { if (parameter.Type.ContainsTypeParameter(typeParameter)) { return true; } } return false; } private bool HasUnfixedParamInInputType(BoundExpression pSource, TypeSymbol pDest) { for (int iParam = 0; iParam < _methodTypeParameters.Length; iParam++) { if (IsUnfixed(iParam)) { if (DoesInputTypeContain(pSource, pDest, _methodTypeParameters[iParam])) { return true; } } } return false; } //////////////////////////////////////////////////////////////////////////////// // // Output types // private static bool DoesOutputTypeContain(BoundExpression argument, TypeSymbol formalParameterType, TypeParameterSymbol typeParameter) { // SPEC: If E is a method group or an anonymous function and T is a delegate // SPEC: type or expression tree type then the return type of T is an output type // SPEC: of E with type T. var delegateOrFunctionPointerType = formalParameterType.GetDelegateOrFunctionPointerType(); if ((object)delegateOrFunctionPointerType == null) { return false; } var isFunctionPointer = delegateOrFunctionPointerType.IsFunctionPointer(); if ((isFunctionPointer && argument.Kind != BoundKind.UnconvertedAddressOfOperator) || (!isFunctionPointer && argument.Kind is not (BoundKind.UnboundLambda or BoundKind.MethodGroup))) { return false; } MethodSymbol method = delegateOrFunctionPointerType switch { NamedTypeSymbol n => n.DelegateInvokeMethod, FunctionPointerTypeSymbol f => f.Signature, _ => throw ExceptionUtilities.UnexpectedValue(delegateOrFunctionPointerType) }; if ((object)method == null || method.HasUseSiteError) { return false; } var returnType = method.ReturnType; if ((object)returnType == null) { return false; } return returnType.ContainsTypeParameter(typeParameter); } private bool HasUnfixedParamInOutputType(BoundExpression argument, TypeSymbol formalParameterType) { for (int iParam = 0; iParam < _methodTypeParameters.Length; iParam++) { if (IsUnfixed(iParam)) { if (DoesOutputTypeContain(argument, formalParameterType, _methodTypeParameters[iParam])) { return true; } } } return false; } //////////////////////////////////////////////////////////////////////////////// // // Dependence // private bool DependsDirectlyOn(int iParam, int jParam) { Debug.Assert(ValidIndex(iParam)); Debug.Assert(ValidIndex(jParam)); // SPEC: An unfixed type parameter Xi depends directly on an unfixed type // SPEC: parameter Xj if for some argument Ek with type Tk, Xj occurs // SPEC: in an input type of Ek and Xi occurs in an output type of Ek // SPEC: with type Tk. // We compute and record the Depends Directly On relationship once, in // InitializeDependencies, below. // At this point, everything should be unfixed. Debug.Assert(IsUnfixed(iParam)); Debug.Assert(IsUnfixed(jParam)); for (int iArg = 0, length = this.NumberArgumentsToProcess; iArg < length; iArg++) { var formalParameterType = _formalParameterTypes[iArg].Type; var argument = _arguments[iArg]; if (DoesInputTypeContain(argument, formalParameterType, _methodTypeParameters[jParam]) && DoesOutputTypeContain(argument, formalParameterType, _methodTypeParameters[iParam])) { return true; } } return false; } private void InitializeDependencies() { // We track dependencies by a two-d square array that gives the known // relationship between every pair of type parameters. The relationship // is one of: // // * Unknown relationship // * known to be not dependent // * known to depend directly // * known to depend indirectly // // Since dependency is only defined on unfixed type parameters, fixing a type // parameter causes all dependencies involving that parameter to go to // the "known to be not dependent" state. Since dependency is a transitive property, // this means that doing so may require recalculating the indirect dependencies // from the now possibly smaller set of dependencies. // // Therefore, when we detect that the dependency state has possibly changed // due to fixing, we change all "depends indirectly" back into "unknown" and // recalculate from the remaining "depends directly". // // This algorithm thereby yields an extremely bad (but extremely unlikely) worst // case for asymptotic performance. Suppose there are n type parameters. // "DependsTransitivelyOn" below costs O(n) because it must potentially check // all n type parameters to see if there is any k such that Xj => Xk => Xi. // "DeduceDependencies" calls "DependsTransitivelyOn" for each "Unknown" // pair, and there could be O(n^2) such pairs, so DependsTransitivelyOn is // worst-case O(n^3). And we could have to recalculate the dependency graph // after each type parameter is fixed in turn, so that would be O(n) calls to // DependsTransitivelyOn, giving this algorithm a worst case of O(n^4). // // Of course, in reality, n is going to almost always be on the order of // "smaller than 5", and there will not be O(n^2) dependency relationships // between type parameters; it is far more likely that the transitivity chains // will be very short and not branch or loop at all. This is much more likely to // be an O(n^2) algorithm in practice. Debug.Assert(_dependencies == null); _dependencies = new Dependency[_methodTypeParameters.Length, _methodTypeParameters.Length]; int iParam; int jParam; Debug.Assert(0 == (int)Dependency.Unknown); for (iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (DependsDirectlyOn(iParam, jParam)) { _dependencies[iParam, jParam] = Dependency.Direct; } } } DeduceAllDependencies(); } private bool DependsOn(int iParam, int jParam) { Debug.Assert(_dependencies != null); // SPEC: Xj depends on Xi if Xj depends directly on Xi, or if Xi depends // SPEC: directly on Xk and Xk depends on Xj. Thus "depends on" is the // SPEC: transitive but not reflexive closure of "depends directly on". Debug.Assert(0 <= iParam && iParam < _methodTypeParameters.Length); Debug.Assert(0 <= jParam && jParam < _methodTypeParameters.Length); if (_dependenciesDirty) { SetIndirectsToUnknown(); DeduceAllDependencies(); } return 0 != ((_dependencies[iParam, jParam]) & Dependency.DependsMask); } private bool DependsTransitivelyOn(int iParam, int jParam) { Debug.Assert(_dependencies != null); Debug.Assert(ValidIndex(iParam)); Debug.Assert(ValidIndex(jParam)); // Can we find Xk such that Xi depends on Xk and Xk depends on Xj? // If so, then Xi depends indirectly on Xj. (Note that there is // a minor optimization here -- the spec comment above notes that // we want Xi to depend DIRECTLY on Xk, and Xk to depend directly // or indirectly on Xj. But if we already know that Xi depends // directly OR indirectly on Xk and Xk depends on Xj, then that's // good enough.) for (int kParam = 0; kParam < _methodTypeParameters.Length; ++kParam) { if (((_dependencies[iParam, kParam]) & Dependency.DependsMask) != 0 && ((_dependencies[kParam, jParam]) & Dependency.DependsMask) != 0) { return true; } } return false; } private void DeduceAllDependencies() { bool madeProgress; do { madeProgress = DeduceDependencies(); } while (madeProgress); SetUnknownsToNotDependent(); _dependenciesDirty = false; } private bool DeduceDependencies() { Debug.Assert(_dependencies != null); bool madeProgress = false; for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (_dependencies[iParam, jParam] == Dependency.Unknown) { if (DependsTransitivelyOn(iParam, jParam)) { _dependencies[iParam, jParam] = Dependency.Indirect; madeProgress = true; } } } } return madeProgress; } private void SetUnknownsToNotDependent() { Debug.Assert(_dependencies != null); for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (_dependencies[iParam, jParam] == Dependency.Unknown) { _dependencies[iParam, jParam] = Dependency.NotDependent; } } } } private void SetIndirectsToUnknown() { Debug.Assert(_dependencies != null); for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (_dependencies[iParam, jParam] == Dependency.Indirect) { _dependencies[iParam, jParam] = Dependency.Unknown; } } } } //////////////////////////////////////////////////////////////////////////////// // A fixed parameter never depends on anything, nor is depended upon by anything. private void UpdateDependenciesAfterFix(int iParam) { Debug.Assert(ValidIndex(iParam)); if (_dependencies == null) { return; } for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { _dependencies[iParam, jParam] = Dependency.NotDependent; _dependencies[jParam, iParam] = Dependency.NotDependent; } _dependenciesDirty = true; } private bool DependsOnAny(int iParam) { Debug.Assert(ValidIndex(iParam)); for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (DependsOn(iParam, jParam)) { return true; } } return false; } private bool AnyDependsOn(int iParam) { Debug.Assert(ValidIndex(iParam)); for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (DependsOn(jParam, iParam)) { return true; } } return false; } //////////////////////////////////////////////////////////////////////////////// // // Output type inferences // //////////////////////////////////////////////////////////////////////////////// private void OutputTypeInference(Binder binder, BoundExpression expression, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(expression != null); Debug.Assert(target.HasType); // SPEC: An output type inference is made from an expression E to a type T // SPEC: in the following way: // SPEC: * If E is an anonymous function with inferred return type U and // SPEC: T is a delegate type or expression tree with return type Tb // SPEC: then a lower bound inference is made from U to Tb. if (InferredReturnTypeInference(expression, target, ref useSiteInfo)) { return; } // SPEC: * Otherwise, if E is a method group and T is a delegate type or // SPEC: expression tree type with parameter types T1...Tk and return // SPEC: type Tb and overload resolution of E with the types T1...Tk // SPEC: yields a single method with return type U then a lower-bound // SPEC: inference is made from U to Tb. if (MethodGroupReturnTypeInference(binder, expression, target.Type, ref useSiteInfo)) { return; } // SPEC: * Otherwise, if E is an expression with type U then a lower-bound // SPEC: inference is made from U to T. var sourceType = _extensions.GetTypeWithAnnotations(expression); if (sourceType.HasType) { LowerBoundInference(sourceType, target, ref useSiteInfo); } // SPEC: * Otherwise, no inferences are made. } private bool InferredReturnTypeInference(BoundExpression source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert(target.HasType); // SPEC: * If E is an anonymous function with inferred return type U and // SPEC: T is a delegate type or expression tree with return type Tb // SPEC: then a lower bound inference is made from U to Tb. var delegateType = target.Type.GetDelegateType(); if ((object)delegateType == null) { return false; } // cannot be hit, because an invalid delegate does not have an unfixed return type // this will be checked earlier. Debug.Assert((object)delegateType.DelegateInvokeMethod != null && !delegateType.DelegateInvokeMethod.HasUseSiteError, "This method should only be called for valid delegate types."); var returnType = delegateType.DelegateInvokeMethod.ReturnTypeWithAnnotations; if (!returnType.HasType || returnType.SpecialType == SpecialType.System_Void) { return false; } var inferredReturnType = InferReturnType(source, delegateType, ref useSiteInfo); if (!inferredReturnType.HasType) { return false; } LowerBoundInference(inferredReturnType, returnType, ref useSiteInfo); return true; } private bool MethodGroupReturnTypeInference(Binder binder, BoundExpression source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert((object)target != null); // SPEC: * Otherwise, if E is a method group and T is a delegate type or // SPEC: expression tree type with parameter types T1...Tk and return // SPEC: type Tb and overload resolution of E with the types T1...Tk // SPEC: yields a single method with return type U then a lower-bound // SPEC: inference is made from U to Tb. if (source.Kind is not (BoundKind.MethodGroup or BoundKind.UnconvertedAddressOfOperator)) { return false; } var delegateOrFunctionPointerType = target.GetDelegateOrFunctionPointerType(); if ((object)delegateOrFunctionPointerType == null) { return false; } if (delegateOrFunctionPointerType.IsFunctionPointer() != (source.Kind == BoundKind.UnconvertedAddressOfOperator)) { return false; } // this part of the code is only called if the targetType has an unfixed type argument in the output // type, which is not the case for invalid delegate invoke methods. var (method, isFunctionPointerResolution) = delegateOrFunctionPointerType switch { NamedTypeSymbol n => (n.DelegateInvokeMethod, false), FunctionPointerTypeSymbol f => (f.Signature, true), _ => throw ExceptionUtilities.UnexpectedValue(delegateOrFunctionPointerType), }; Debug.Assert(method is { HasUseSiteError: false }, "This method should only be called for valid delegate or function pointer types"); TypeWithAnnotations sourceReturnType = method.ReturnTypeWithAnnotations; if (!sourceReturnType.HasType || sourceReturnType.SpecialType == SpecialType.System_Void) { return false; } // At this point we are in the second phase; we know that all the input types are fixed. var fixedParameters = GetFixedDelegateOrFunctionPointer(delegateOrFunctionPointerType).DelegateOrFunctionPointerParameters(); if (fixedParameters.IsDefault) { return false; } CallingConventionInfo callingConventionInfo = isFunctionPointerResolution ? new CallingConventionInfo(method.CallingConvention, ((FunctionPointerMethodSymbol)method).GetCallingConventionModifiers()) : default; BoundMethodGroup originalMethodGroup = source as BoundMethodGroup ?? ((BoundUnconvertedAddressOfOperator)source).Operand; var returnType = MethodGroupReturnType(binder, originalMethodGroup, fixedParameters, method.RefKind, isFunctionPointerResolution, ref useSiteInfo, in callingConventionInfo); if (returnType.IsDefault || returnType.IsVoidType()) { return false; } LowerBoundInference(returnType, sourceReturnType, ref useSiteInfo); return true; } private TypeWithAnnotations MethodGroupReturnType( Binder binder, BoundMethodGroup source, ImmutableArray<ParameterSymbol> delegateParameters, RefKind delegateRefKind, bool isFunctionPointerResolution, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, in CallingConventionInfo callingConventionInfo) { var analyzedArguments = AnalyzedArguments.GetInstance(); Conversions.GetDelegateOrFunctionPointerArguments(source.Syntax, analyzedArguments, delegateParameters, binder.Compilation); var resolution = binder.ResolveMethodGroup(source, analyzedArguments, useSiteInfo: ref useSiteInfo, isMethodGroupConversion: true, returnRefKind: delegateRefKind, // Since we are trying to infer the return type, it is not an input to resolving the method group returnType: null, isFunctionPointerResolution: isFunctionPointerResolution, callingConventionInfo: in callingConventionInfo); TypeWithAnnotations type = default; // The resolution could be empty (e.g. if there are no methods in the BoundMethodGroup). if (!resolution.IsEmpty) { var result = resolution.OverloadResolutionResult; if (result.Succeeded) { type = _extensions.GetMethodGroupResultType(source, result.BestResult.Member); } } analyzedArguments.Free(); resolution.Free(); return type; } //////////////////////////////////////////////////////////////////////////////// // // Explicit parameter type inferences // private void ExplicitParameterTypeInference(BoundExpression source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert(target.HasType); // SPEC: An explicit type parameter type inference is made from an expression // SPEC: E to a type T in the following way. // SPEC: If E is an explicitly typed anonymous function with parameter types // SPEC: U1...Uk and T is a delegate type or expression tree type with // SPEC: parameter types V1...Vk then for each Ui an exact inference is made // SPEC: from Ui to the corresponding Vi. if (source.Kind != BoundKind.UnboundLambda) { return; } UnboundLambda anonymousFunction = (UnboundLambda)source; if (!anonymousFunction.HasExplicitlyTypedParameterList) { return; } var delegateType = target.Type.GetDelegateType(); if ((object)delegateType == null) { return; } var delegateParameters = delegateType.DelegateParameters(); if (delegateParameters.IsDefault) { return; } int size = delegateParameters.Length; if (anonymousFunction.ParameterCount < size) { size = anonymousFunction.ParameterCount; } // SPEC ISSUE: What should we do if there is an out/ref mismatch between an // SPEC ISSUE: anonymous function parameter and a delegate parameter? // SPEC ISSUE: The result will not be applicable no matter what, but should // SPEC ISSUE: we make any inferences? This is going to be an error // SPEC ISSUE: ultimately, but it might make a difference for intellisense or // SPEC ISSUE: other analysis. for (int i = 0; i < size; ++i) { ExactInference(anonymousFunction.ParameterTypeWithAnnotations(i), delegateParameters[i].TypeWithAnnotations, ref useSiteInfo); } } //////////////////////////////////////////////////////////////////////////////// // // Exact inferences // private void ExactInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: An exact inference from a type U to a type V is made as follows: // SPEC: * Otherwise, if U is the type U1? and V is the type V1? then an // SPEC: exact inference is made from U to V. if (ExactNullableInference(source, target, ref useSiteInfo)) { return; } // SPEC: * If V is one of the unfixed Xi then U is added to the set of // SPEC: exact bounds for Xi. if (ExactTypeParameterInference(source, target)) { return; } // SPEC: * Otherwise, if U is an array type UE[...] and V is an array type VE[...] // SPEC: of the same rank then an exact inference from UE to VE is made. if (ExactArrayInference(source, target, ref useSiteInfo)) { return; } // SPEC: * Otherwise, if V is a constructed type C<V1...Vk> and U is a constructed // SPEC: type C<U1...Uk> then an exact inference is made // SPEC: from each Ui to the corresponding Vi. if (ExactConstructedInference(source, target, ref useSiteInfo)) { return; } // This can be valid via (where T : unmanaged) constraints if (ExactPointerInference(source, target, ref useSiteInfo)) { return; } // SPEC: * Otherwise no inferences are made. } private bool ExactTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * If V is one of the unfixed Xi then U is added to the set of bounds // SPEC: for Xi. if (IsUnfixedTypeParameter(target)) { AddBound(source, _exactBounds, target); return true; } return false; } private bool ExactArrayInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * Otherwise, if U is an array type UE[...] and V is an array type VE[...] // SPEC: of the same rank then an exact inference from UE to VE is made. if (!source.Type.IsArray() || !target.Type.IsArray()) { return false; } var arraySource = (ArrayTypeSymbol)source.Type; var arrayTarget = (ArrayTypeSymbol)target.Type; if (!arraySource.HasSameShapeAs(arrayTarget)) { return false; } ExactInference(arraySource.ElementTypeWithAnnotations, arrayTarget.ElementTypeWithAnnotations, ref useSiteInfo); return true; } private enum ExactOrBoundsKind { Exact, LowerBound, UpperBound, } private void ExactOrBoundsInference(ExactOrBoundsKind kind, TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (kind) { case ExactOrBoundsKind.Exact: ExactInference(source, target, ref useSiteInfo); break; case ExactOrBoundsKind.LowerBound: LowerBoundInference(source, target, ref useSiteInfo); break; case ExactOrBoundsKind.UpperBound: UpperBoundInference(source, target, ref useSiteInfo); break; } } private bool ExactOrBoundsNullableInference(ExactOrBoundsKind kind, TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); if (source.IsNullableType() && target.IsNullableType()) { ExactOrBoundsInference(kind, ((NamedTypeSymbol)source.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0], ((NamedTypeSymbol)target.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0], ref useSiteInfo); return true; } if (isNullableOnly(source) && isNullableOnly(target)) { ExactOrBoundsInference(kind, source.AsNotNullableReferenceType(), target.AsNotNullableReferenceType(), ref useSiteInfo); return true; } return false; // True if the type is nullable. static bool isNullableOnly(TypeWithAnnotations type) => type.NullableAnnotation.IsAnnotated(); } private bool ExactNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ExactOrBoundsNullableInference(ExactOrBoundsKind.Exact, source, target, ref useSiteInfo); } private bool LowerBoundTupleInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // NOTE: we are losing tuple element names when unwrapping tuple types to underlying types. // that is ok, because we are inferring type parameters used in the matching elements, // This is not the situation where entire tuple type used to infer a single type param ImmutableArray<TypeWithAnnotations> sourceTypes; ImmutableArray<TypeWithAnnotations> targetTypes; if (!source.Type.TryGetElementTypesWithAnnotationsIfTupleType(out sourceTypes) || !target.Type.TryGetElementTypesWithAnnotationsIfTupleType(out targetTypes) || sourceTypes.Length != targetTypes.Length) { return false; } for (int i = 0; i < sourceTypes.Length; i++) { LowerBoundInference(sourceTypes[i], targetTypes[i], ref useSiteInfo); } return true; } private bool ExactConstructedInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * Otherwise, if V is a constructed type C<V1...Vk> and U is a constructed // SPEC: type C<U1...Uk> then an exact inference // SPEC: is made from each Ui to the corresponding Vi. var namedSource = source.Type as NamedTypeSymbol; if ((object)namedSource == null) { return false; } var namedTarget = target.Type as NamedTypeSymbol; if ((object)namedTarget == null) { return false; } if (!TypeSymbol.Equals(namedSource.OriginalDefinition, namedTarget.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { return false; } ExactTypeArgumentInference(namedSource, namedTarget, ref useSiteInfo); return true; } private bool ExactPointerInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (source.TypeKind == TypeKind.Pointer && target.TypeKind == TypeKind.Pointer) { ExactInference(((PointerTypeSymbol)source.Type).PointedAtTypeWithAnnotations, ((PointerTypeSymbol)target.Type).PointedAtTypeWithAnnotations, ref useSiteInfo); return true; } else if (source.Type is FunctionPointerTypeSymbol { Signature: { ParameterCount: int sourceParameterCount } sourceSignature } && target.Type is FunctionPointerTypeSymbol { Signature: { ParameterCount: int targetParameterCount } targetSignature } && sourceParameterCount == targetParameterCount) { if (!FunctionPointerRefKindsEqual(sourceSignature, targetSignature) || !FunctionPointerCallingConventionsEqual(sourceSignature, targetSignature)) { return false; } for (int i = 0; i < sourceParameterCount; i++) { ExactInference(sourceSignature.ParameterTypesWithAnnotations[i], targetSignature.ParameterTypesWithAnnotations[i], ref useSiteInfo); } ExactInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); return true; } return false; } private static bool FunctionPointerCallingConventionsEqual(FunctionPointerMethodSymbol sourceSignature, FunctionPointerMethodSymbol targetSignature) { if (sourceSignature.CallingConvention != targetSignature.CallingConvention) { return false; } return (sourceSignature.GetCallingConventionModifiers(), targetSignature.GetCallingConventionModifiers()) switch { (null, null) => true, ({ } sourceModifiers, { } targetModifiers) when sourceModifiers.SetEquals(targetModifiers) => true, _ => false }; } private static bool FunctionPointerRefKindsEqual(FunctionPointerMethodSymbol sourceSignature, FunctionPointerMethodSymbol targetSignature) { return sourceSignature.RefKind == targetSignature.RefKind && (sourceSignature.ParameterRefKinds.IsDefault, targetSignature.ParameterRefKinds.IsDefault) switch { (true, false) or (false, true) => false, (true, true) => true, _ => sourceSignature.ParameterRefKinds.SequenceEqual(targetSignature.ParameterRefKinds) }; } private void ExactTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var targetTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); target.GetAllTypeArguments(targetTypeArguments, ref useSiteInfo); Debug.Assert(sourceTypeArguments.Count == targetTypeArguments.Count); for (int arg = 0; arg < sourceTypeArguments.Count; ++arg) { ExactInference(sourceTypeArguments[arg], targetTypeArguments[arg], ref useSiteInfo); } sourceTypeArguments.Free(); targetTypeArguments.Free(); } //////////////////////////////////////////////////////////////////////////////// // // Lower-bound inferences // private void LowerBoundInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: A lower-bound inference from a type U to a type V is made as follows: // SPEC: * Otherwise, if V is nullable type V1? and U is nullable type U1? // SPEC: then an exact inference is made from U1 to V1. // SPEC ERROR: The spec should say "lower" here; we can safely make a lower-bound // SPEC ERROR: inference to nullable even though it is a generic struct. That is, // SPEC ERROR: if we have M<T>(T?, T) called with (char?, int) then we can infer // SPEC ERROR: lower bounds of char and int, and choose int. If we make an exact // SPEC ERROR: inference of char then type inference fails. if (LowerBoundNullableInference(source, target, ref useSiteInfo)) { return; } // SPEC: * If V is one of the unfixed Xi then U is added to the set of // SPEC: lower bounds for Xi. if (LowerBoundTypeParameterInference(source, target)) { return; } // SPEC: * Otherwise, if U is an array type Ue[...] and V is either an array // SPEC: type Ve[...] of the same rank, or if U is a one-dimensional array // SPEC: type Ue[] and V is one of IEnumerable<Ve>, ICollection<Ve> or // SPEC: IList<Ve> then // SPEC: * if Ue is known to be a reference type then a lower-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (LowerBoundArrayInference(source.Type, target.Type, ref useSiteInfo)) { return; } // UNDONE: At this point we could also do an inference from non-nullable U // UNDONE: to nullable V. // UNDONE: // UNDONE: We tried implementing lower bound nullable inference as follows: // UNDONE: // UNDONE: * Otherwise, if V is nullable type V1? and U is a non-nullable // UNDONE: struct type then an exact inference is made from U to V1. // UNDONE: // UNDONE: However, this causes an unfortunate interaction with what // UNDONE: looks like a bug in our implementation of section 15.2 of // UNDONE: the specification. Namely, it appears that the code which // UNDONE: checks whether a given method is compatible with // UNDONE: a delegate type assumes that if method type inference succeeds, // UNDONE: then the inferred types are compatible with the delegate types. // UNDONE: This is not necessarily so; the inferred types could be compatible // UNDONE: via a conversion other than reference or identity. // UNDONE: // UNDONE: We should take an action item to investigate this problem. // UNDONE: Until then, we will turn off the proposed lower bound nullable // UNDONE: inference. // if (LowerBoundNullableInference(pSource, pDest)) // { // return; // } if (LowerBoundTupleInference(source, target, ref useSiteInfo)) { return; } // SPEC: Otherwise... many cases for constructed generic types. if (LowerBoundConstructedInference(source.Type, target.Type, ref useSiteInfo)) { return; } if (LowerBoundFunctionPointerTypeInference(source.Type, target.Type, ref useSiteInfo)) { return; } // SPEC: * Otherwise, no inferences are made. } private bool LowerBoundTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * If V is one of the unfixed Xi then U is added to the set of bounds // SPEC: for Xi. if (IsUnfixedTypeParameter(target)) { AddBound(source, _lowerBounds, target); return true; } return false; } private static TypeWithAnnotations GetMatchingElementType(ArrayTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); // It might be an array of same rank. if (target.IsArray()) { var arrayTarget = (ArrayTypeSymbol)target; if (!arrayTarget.HasSameShapeAs(source)) { return default; } return arrayTarget.ElementTypeWithAnnotations; } // Or it might be IEnum<T> and source is rank one. if (!source.IsSZArray) { return default; } // Arrays are specified as being convertible to IEnumerable<T>, ICollection<T> and // IList<T>; we also honor their convertibility to IReadOnlyCollection<T> and // IReadOnlyList<T>, and make inferences accordingly. if (!target.IsPossibleArrayGenericInterface()) { return default; } return ((NamedTypeSymbol)target).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo); } private bool LowerBoundArrayInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); // SPEC: * Otherwise, if U is an array type Ue[...] and V is either an array // SPEC: type Ve[...] of the same rank, or if U is a one-dimensional array // SPEC: type Ue[] and V is one of IEnumerable<Ve>, ICollection<Ve> or // SPEC: IList<Ve> then // SPEC: * if Ue is known to be a reference type then a lower-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (!source.IsArray()) { return false; } var arraySource = (ArrayTypeSymbol)source; var elementSource = arraySource.ElementTypeWithAnnotations; var elementTarget = GetMatchingElementType(arraySource, target, ref useSiteInfo); if (!elementTarget.HasType) { return false; } if (elementSource.Type.IsReferenceType) { LowerBoundInference(elementSource, elementTarget, ref useSiteInfo); } else { ExactInference(elementSource, elementTarget, ref useSiteInfo); } return true; } private bool LowerBoundNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ExactOrBoundsNullableInference(ExactOrBoundsKind.LowerBound, source, target, ref useSiteInfo); } private bool LowerBoundConstructedInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); var constructedTarget = target as NamedTypeSymbol; if ((object)constructedTarget == null) { return false; } if (constructedTarget.AllTypeArgumentCount() == 0) { return false; } // SPEC: * Otherwise, if V is a constructed class or struct type C<V1...Vk> // SPEC: and U is C<U1...Uk> then an exact inference // SPEC: is made from each Ui to the corresponding Vi. // SPEC: * Otherwise, if V is a constructed interface or delegate type C<V1...Vk> // SPEC: and U is C<U1...Uk> then an exact inference, // SPEC: lower bound inference or upper bound inference // SPEC: is made from each Ui to the corresponding Vi. var constructedSource = source as NamedTypeSymbol; if ((object)constructedSource != null && TypeSymbol.Equals(constructedSource.OriginalDefinition, constructedTarget.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { if (constructedSource.IsInterface || constructedSource.IsDelegateType()) { LowerBoundTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } else { ExactTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } return true; } // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a class type which // SPEC: inherits directly or indirectly from C<U1...Uk> then an exact ... // SPEC: * ... and U is a type parameter with effective base class ... // SPEC: * ... and U is a type parameter with an effective base class which inherits ... if (LowerBoundClassInference(source, constructedTarget, ref useSiteInfo)) { return true; } // SPEC: * Otherwise, if V is an interface type C<V1...Vk> and U is a class type // SPEC: or struct type and there is a unique set U1...Uk such that U directly // SPEC: or indirectly implements C<U1...Uk> then an exact ... // SPEC: * ... and U is an interface type ... // SPEC: * ... and U is a type parameter ... if (LowerBoundInterfaceInference(source, constructedTarget, ref useSiteInfo)) { return true; } return false; } private bool LowerBoundClassInference(TypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (target.TypeKind != TypeKind.Class) { return false; } // Spec: 7.5.2.9 Lower-bound interfaces // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a class type which // SPEC: inherits directly or indirectly from C<U1...Uk> // SPEC: then an exact inference is made from each Ui to the corresponding Vi. // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a type parameter // SPEC: with effective base class C<U1...Uk> // SPEC: then an exact inference is made from each Ui to the corresponding Vi. // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a type parameter // SPEC: with an effective base class which inherits directly or indirectly from // SPEC: C<U1...Uk> then an exact inference is made // SPEC: from each Ui to the corresponding Vi. NamedTypeSymbol sourceBase = null; if (source.TypeKind == TypeKind.Class) { sourceBase = source.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } else if (source.TypeKind == TypeKind.TypeParameter) { sourceBase = ((TypeParameterSymbol)source).EffectiveBaseClass(ref useSiteInfo); } while ((object)sourceBase != null) { if (TypeSymbol.Equals(sourceBase.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { ExactTypeArgumentInference(sourceBase, target, ref useSiteInfo); return true; } sourceBase = sourceBase.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } return false; } private bool LowerBoundInterfaceInference(TypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (!target.IsInterface) { return false; } // Spec 7.5.2.9 Lower-bound interfaces // SPEC: * Otherwise, if V [target] is an interface type C<V1...Vk> and U [source] is a class type // SPEC: or struct type and there is a unique set U1...Uk such that U directly // SPEC: or indirectly implements C<U1...Uk> then an // SPEC: exact, upper-bound, or lower-bound inference ... // SPEC: * ... and U is an interface type ... // SPEC: * ... and U is a type parameter ... ImmutableArray<NamedTypeSymbol> allInterfaces; switch (source.TypeKind) { case TypeKind.Struct: case TypeKind.Class: case TypeKind.Interface: allInterfaces = source.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); break; case TypeKind.TypeParameter: var typeParameter = (TypeParameterSymbol)source; allInterfaces = typeParameter.EffectiveBaseClass(ref useSiteInfo). AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo). Concat(typeParameter.AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)); break; default: return false; } // duplicates with only nullability differences can be merged (to avoid an error in type inference) allInterfaces = ModuloReferenceTypeNullabilityDifferences(allInterfaces, VarianceKind.In); NamedTypeSymbol matchingInterface = GetInterfaceInferenceBound(allInterfaces, target); if ((object)matchingInterface == null) { return false; } LowerBoundTypeArgumentInference(matchingInterface, target, ref useSiteInfo); return true; } internal static ImmutableArray<NamedTypeSymbol> ModuloReferenceTypeNullabilityDifferences(ImmutableArray<NamedTypeSymbol> interfaces, VarianceKind variance) { var dictionary = PooledDictionaryIgnoringNullableModifiersForReferenceTypes.GetInstance(); foreach (var @interface in interfaces) { if (dictionary.TryGetValue(@interface, out var found)) { var merged = (NamedTypeSymbol)found.MergeEquivalentTypes(@interface, variance); dictionary[@interface] = merged; } else { dictionary.Add(@interface, @interface); } } var result = dictionary.Count != interfaces.Length ? dictionary.Values.ToImmutableArray() : interfaces; dictionary.Free(); return result; } private void LowerBoundTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The choice of inference for the i-th type argument is made // SPEC: based on the declaration of the i-th type parameter of C, as // SPEC: follows: // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as covariant then a lower bound inference is made. // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as contravariant then an upper bound inference is made. // SPEC: * otherwise, an exact inference is made. Debug.Assert((object)source != null); Debug.Assert((object)target != null); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)); var typeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var targetTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); source.OriginalDefinition.GetAllTypeParameters(typeParameters); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); target.GetAllTypeArguments(targetTypeArguments, ref useSiteInfo); Debug.Assert(typeParameters.Count == sourceTypeArguments.Count); Debug.Assert(typeParameters.Count == targetTypeArguments.Count); for (int arg = 0; arg < sourceTypeArguments.Count; ++arg) { var typeParameter = typeParameters[arg]; var sourceTypeArgument = sourceTypeArguments[arg]; var targetTypeArgument = targetTypeArguments[arg]; if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.Out) { LowerBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.In) { UpperBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else { ExactInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } } typeParameters.Free(); sourceTypeArguments.Free(); targetTypeArguments.Free(); } #nullable enable private bool LowerBoundFunctionPointerTypeInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (source is not FunctionPointerTypeSymbol { Signature: { } sourceSignature } || target is not FunctionPointerTypeSymbol { Signature: { } targetSignature }) { return false; } if (sourceSignature.ParameterCount != targetSignature.ParameterCount) { return false; } if (!FunctionPointerRefKindsEqual(sourceSignature, targetSignature) || !FunctionPointerCallingConventionsEqual(sourceSignature, targetSignature)) { return false; } // Reference parameters are treated as "input" variance by default, and reference return types are treated as out variance by default. // If they have a ref kind or are not reference types, then they are treated as invariant. for (int i = 0; i < sourceSignature.ParameterCount; i++) { var sourceParam = sourceSignature.Parameters[i]; var targetParam = targetSignature.Parameters[i]; if ((sourceParam.Type.IsReferenceType || sourceParam.Type.IsFunctionPointer()) && sourceParam.RefKind == RefKind.None) { UpperBoundInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } } if ((sourceSignature.ReturnType.IsReferenceType || sourceSignature.ReturnType.IsFunctionPointer()) && sourceSignature.RefKind == RefKind.None) { LowerBoundInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } return true; } #nullable disable //////////////////////////////////////////////////////////////////////////////// // // Upper-bound inferences // private void UpperBoundInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: An upper-bound inference from a type U to a type V is made as follows: // SPEC: * Otherwise, if V is nullable type V1? and U is nullable type U1? // SPEC: then an exact inference is made from U1 to V1. if (UpperBoundNullableInference(source, target, ref useSiteInfo)) { return; } // SPEC: * If V is one of the unfixed Xi then U is added to the set of // SPEC: upper bounds for Xi. if (UpperBoundTypeParameterInference(source, target)) { return; } // SPEC: * Otherwise, if V is an array type Ve[...] and U is an array // SPEC: type Ue[...] of the same rank, or if V is a one-dimensional array // SPEC: type Ve[] and U is one of IEnumerable<Ue>, ICollection<Ue> or // SPEC: IList<Ue> then // SPEC: * if Ue is known to be a reference type then an upper-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (UpperBoundArrayInference(source, target, ref useSiteInfo)) { return; } Debug.Assert(source.Type.IsReferenceType || source.Type.IsFunctionPointer()); // NOTE: spec would ask us to do the following checks, but since the value types // are trivially handled as exact inference in the callers, we do not have to. //if (ExactTupleInference(source, target, ref useSiteInfo)) //{ // return; //} // SPEC: * Otherwise... cases for constructed types if (UpperBoundConstructedInference(source, target, ref useSiteInfo)) { return; } if (UpperBoundFunctionPointerTypeInference(source.Type, target.Type, ref useSiteInfo)) { return; } // SPEC: * Otherwise, no inferences are made. } private bool UpperBoundTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * If V is one of the unfixed Xi then U is added to the set of upper bounds // SPEC: for Xi. if (IsUnfixedTypeParameter(target)) { AddBound(source, _upperBounds, target); return true; } return false; } private bool UpperBoundArrayInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * Otherwise, if V is an array type Ve[...] and U is an array // SPEC: type Ue[...] of the same rank, or if V is a one-dimensional array // SPEC: type Ve[] and U is one of IEnumerable<Ue>, ICollection<Ue> or // SPEC: IList<Ue> then // SPEC: * if Ue is known to be a reference type then an upper-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (!target.Type.IsArray()) { return false; } var arrayTarget = (ArrayTypeSymbol)target.Type; var elementTarget = arrayTarget.ElementTypeWithAnnotations; var elementSource = GetMatchingElementType(arrayTarget, source.Type, ref useSiteInfo); if (!elementSource.HasType) { return false; } if (elementSource.Type.IsReferenceType) { UpperBoundInference(elementSource, elementTarget, ref useSiteInfo); } else { ExactInference(elementSource, elementTarget, ref useSiteInfo); } return true; } private bool UpperBoundNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ExactOrBoundsNullableInference(ExactOrBoundsKind.UpperBound, source, target, ref useSiteInfo); } private bool UpperBoundConstructedInference(TypeWithAnnotations sourceWithAnnotations, TypeWithAnnotations targetWithAnnotations, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceWithAnnotations.HasType); Debug.Assert(targetWithAnnotations.HasType); var source = sourceWithAnnotations.Type; var target = targetWithAnnotations.Type; var constructedSource = source as NamedTypeSymbol; if ((object)constructedSource == null) { return false; } if (constructedSource.AllTypeArgumentCount() == 0) { return false; } // SPEC: * Otherwise, if V is a constructed type C<V1...Vk> and U is // SPEC: C<U1...Uk> then an exact inference, // SPEC: lower bound inference or upper bound inference // SPEC: is made from each Ui to the corresponding Vi. var constructedTarget = target as NamedTypeSymbol; if ((object)constructedTarget != null && TypeSymbol.Equals(constructedSource.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { if (constructedTarget.IsInterface || constructedTarget.IsDelegateType()) { UpperBoundTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } else { ExactTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } return true; } // SPEC: * Otherwise, if U is a class type C<U1...Uk> and V is a class type which // SPEC: inherits directly or indirectly from C<V1...Vk> then an exact ... if (UpperBoundClassInference(constructedSource, target, ref useSiteInfo)) { return true; } // SPEC: * Otherwise, if U is an interface type C<U1...Uk> and V is a class type // SPEC: or struct type and there is a unique set V1...Vk such that V directly // SPEC: or indirectly implements C<V1...Vk> then an exact ... // SPEC: * ... and U is an interface type ... if (UpperBoundInterfaceInference(constructedSource, target, ref useSiteInfo)) { return true; } return false; } private bool UpperBoundClassInference(NamedTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (source.TypeKind != TypeKind.Class || target.TypeKind != TypeKind.Class) { return false; } // SPEC: * Otherwise, if U is a class type C<U1...Uk> and V is a class type which // SPEC: inherits directly or indirectly from C<V1...Vk> then an exact // SPEC: inference is made from each Ui to the corresponding Vi. var targetBase = target.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); while ((object)targetBase != null) { if (TypeSymbol.Equals(targetBase.OriginalDefinition, source.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { ExactTypeArgumentInference(source, targetBase, ref useSiteInfo); return true; } targetBase = targetBase.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } return false; } private bool UpperBoundInterfaceInference(NamedTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (!source.IsInterface) { return false; } // SPEC: * Otherwise, if U [source] is an interface type C<U1...Uk> and V [target] is a class type // SPEC: or struct type and there is a unique set V1...Vk such that V directly // SPEC: or indirectly implements C<V1...Vk> then an exact ... // SPEC: * ... and U is an interface type ... switch (target.TypeKind) { case TypeKind.Struct: case TypeKind.Class: case TypeKind.Interface: break; default: return false; } ImmutableArray<NamedTypeSymbol> allInterfaces = target.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); // duplicates with only nullability differences can be merged (to avoid an error in type inference) allInterfaces = ModuloReferenceTypeNullabilityDifferences(allInterfaces, VarianceKind.Out); NamedTypeSymbol bestInterface = GetInterfaceInferenceBound(allInterfaces, source); if ((object)bestInterface == null) { return false; } UpperBoundTypeArgumentInference(source, bestInterface, ref useSiteInfo); return true; } private void UpperBoundTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The choice of inference for the i-th type argument is made // SPEC: based on the declaration of the i-th type parameter of C, as // SPEC: follows: // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as covariant then an upper-bound inference is made. // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as contravariant then a lower-bound inference is made. // SPEC: * otherwise, an exact inference is made. Debug.Assert((object)source != null); Debug.Assert((object)target != null); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)); var typeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var targetTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); source.OriginalDefinition.GetAllTypeParameters(typeParameters); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); target.GetAllTypeArguments(targetTypeArguments, ref useSiteInfo); Debug.Assert(typeParameters.Count == sourceTypeArguments.Count); Debug.Assert(typeParameters.Count == targetTypeArguments.Count); for (int arg = 0; arg < sourceTypeArguments.Count; ++arg) { var typeParameter = typeParameters[arg]; var sourceTypeArgument = sourceTypeArguments[arg]; var targetTypeArgument = targetTypeArguments[arg]; if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.Out) { UpperBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.In) { LowerBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else { ExactInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } } typeParameters.Free(); sourceTypeArguments.Free(); targetTypeArguments.Free(); } #nullable enable private bool UpperBoundFunctionPointerTypeInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (source is not FunctionPointerTypeSymbol { Signature: { } sourceSignature } || target is not FunctionPointerTypeSymbol { Signature: { } targetSignature }) { return false; } if (sourceSignature.ParameterCount != targetSignature.ParameterCount) { return false; } if (!FunctionPointerRefKindsEqual(sourceSignature, targetSignature) || !FunctionPointerCallingConventionsEqual(sourceSignature, targetSignature)) { return false; } // Reference parameters are treated as "input" variance by default, and reference return types are treated as out variance by default. // If they have a ref kind or are not reference types, then they are treated as invariant. for (int i = 0; i < sourceSignature.ParameterCount; i++) { var sourceParam = sourceSignature.Parameters[i]; var targetParam = targetSignature.Parameters[i]; if ((sourceParam.Type.IsReferenceType || sourceParam.Type.IsFunctionPointer()) && sourceParam.RefKind == RefKind.None) { LowerBoundInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } } if ((sourceSignature.ReturnType.IsReferenceType || sourceSignature.ReturnType.IsFunctionPointer()) && sourceSignature.RefKind == RefKind.None) { UpperBoundInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } return true; } #nullable disable //////////////////////////////////////////////////////////////////////////////// // // Fixing // private bool Fix(int iParam, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(IsUnfixed(iParam)); var exact = _exactBounds[iParam]; var lower = _lowerBounds[iParam]; var upper = _upperBounds[iParam]; var best = Fix(exact, lower, upper, ref useSiteInfo, _conversions); if (!best.HasType) { return false; } #if DEBUG if (_conversions.IncludeNullability) { // If the first attempt succeeded, the result should be the same as // the second attempt, although perhaps with different nullability. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var withoutNullability = Fix(exact, lower, upper, ref discardedUseSiteInfo, _conversions.WithNullability(false)); // https://github.com/dotnet/roslyn/issues/27961 Results may differ by tuple names or dynamic. // See NullableReferenceTypesTests.TypeInference_TupleNameDifferences_01 for example. Debug.Assert(best.Type.Equals(withoutNullability.Type, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); } #endif _fixedResults[iParam] = best; UpdateDependenciesAfterFix(iParam); return true; } private static TypeWithAnnotations Fix( HashSet<TypeWithAnnotations> exact, HashSet<TypeWithAnnotations> lower, HashSet<TypeWithAnnotations> upper, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConversionsBase conversions) { // UNDONE: This method makes a lot of garbage. // SPEC: An unfixed type parameter with a set of bounds is fixed as follows: // SPEC: * The set of candidate types starts out as the set of all types in // SPEC: the bounds. // SPEC: * We then examine each bound in turn. For each exact bound U of Xi, // SPEC: all types which are not identical to U are removed from the candidate set. // Optimization: if we have two or more exact bounds, fixing is impossible. var candidates = new Dictionary<TypeWithAnnotations, TypeWithAnnotations>(EqualsIgnoringDynamicTupleNamesAndNullabilityComparer.Instance); // Optimization: if we have one exact bound then we need not add any // inexact bounds; we're just going to remove them anyway. if (exact == null) { if (lower != null) { // Lower bounds represent co-variance. AddAllCandidates(candidates, lower, VarianceKind.Out, conversions); } if (upper != null) { // Lower bounds represent contra-variance. AddAllCandidates(candidates, upper, VarianceKind.In, conversions); } } else { // Exact bounds represent invariance. AddAllCandidates(candidates, exact, VarianceKind.None, conversions); if (candidates.Count >= 2) { return default; } } if (candidates.Count == 0) { return default; } // Don't mutate the collection as we're iterating it. var initialCandidates = ArrayBuilder<TypeWithAnnotations>.GetInstance(); GetAllCandidates(candidates, initialCandidates); // SPEC: For each lower bound U of Xi all types to which there is not an // SPEC: implicit conversion from U are removed from the candidate set. if (lower != null) { MergeOrRemoveCandidates(candidates, lower, initialCandidates, conversions, VarianceKind.Out, ref useSiteInfo); } // SPEC: For each upper bound U of Xi all types from which there is not an // SPEC: implicit conversion to U are removed from the candidate set. if (upper != null) { MergeOrRemoveCandidates(candidates, upper, initialCandidates, conversions, VarianceKind.In, ref useSiteInfo); } initialCandidates.Clear(); GetAllCandidates(candidates, initialCandidates); // SPEC: * If among the remaining candidate types there is a unique type V to // SPEC: which there is an implicit conversion from all the other candidate // SPEC: types, then the parameter is fixed to V. TypeWithAnnotations best = default; foreach (var candidate in initialCandidates) { foreach (var candidate2 in initialCandidates) { if (!candidate.Equals(candidate2, TypeCompareKind.ConsiderEverything) && !ImplicitConversionExists(candidate2, candidate, ref useSiteInfo, conversions.WithNullability(false))) { goto OuterBreak; } } if (!best.HasType) { best = candidate; } else { Debug.Assert(!best.Equals(candidate, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); // best candidate is not unique best = default; break; } OuterBreak: ; } initialCandidates.Free(); return best; } private static bool ImplicitConversionExists(TypeWithAnnotations sourceWithAnnotations, TypeWithAnnotations destinationWithAnnotations, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConversionsBase conversions) { var source = sourceWithAnnotations.Type; var destination = destinationWithAnnotations.Type; // SPEC VIOLATION: For the purpose of algorithm in Fix method, dynamic type is not considered convertible to any other type, including object. if (source.IsDynamic() && !destination.IsDynamic()) { return false; } if (!conversions.HasTopLevelNullabilityImplicitConversion(sourceWithAnnotations, destinationWithAnnotations)) { return false; } return conversions.ClassifyImplicitConversionFromType(source, destination, ref useSiteInfo).Exists; } //////////////////////////////////////////////////////////////////////////////// // // Inferred return type // private TypeWithAnnotations InferReturnType(BoundExpression source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)target != null); Debug.Assert(target.IsDelegateType()); Debug.Assert((object)target.DelegateInvokeMethod != null && !target.DelegateInvokeMethod.HasUseSiteError, "This method should only be called for legal delegate types."); Debug.Assert(!target.DelegateInvokeMethod.ReturnsVoid); // We should not be computing the inferred return type unless we are converting // to a delegate type where all the input types are fixed. Debug.Assert(!HasUnfixedParamInInputType(source, target)); // Spec 7.5.2.12: Inferred return type: // The inferred return type of an anonymous function F is used during // type inference and overload resolution. The inferred return type // can only be determined for an anonymous function where all parameter // types are known, either because they are explicitly given, provided // through an anonymous function conversion, or inferred during type // inference on an enclosing generic method invocation. // The inferred return type is determined as follows: // * If the body of F is an expression (that has a type) then the // inferred return type of F is the type of that expression. // * If the body of F is a block and the set of expressions in the // blocks return statements has a best common type T then the // inferred return type of F is T. // * Otherwise, a return type cannot be inferred for F. if (source.Kind != BoundKind.UnboundLambda) { return default; } var anonymousFunction = (UnboundLambda)source; if (anonymousFunction.HasSignature) { // Optimization: // We know that the anonymous function has a parameter list. If it does not // have the same arity as the delegate, then it cannot possibly be applicable. // Rather than have type inference fail, we will simply not make a return // type inference and have type inference continue on. Either inference // will fail, or we will infer a nonapplicable method. Either way, there // is no change to the semantics of overload resolution. var originalDelegateParameters = target.DelegateParameters(); if (originalDelegateParameters.IsDefault) { return default; } if (originalDelegateParameters.Length != anonymousFunction.ParameterCount) { return default; } } var fixedDelegate = (NamedTypeSymbol)GetFixedDelegateOrFunctionPointer(target); var fixedDelegateParameters = fixedDelegate.DelegateParameters(); // Optimization: // Similarly, if we have an entirely fixed delegate and an explicitly typed // anonymous function, then the parameter types had better be identical. // If not, applicability will eventually fail, so there is no semantic // difference caused by failing to make a return type inference. if (anonymousFunction.HasExplicitlyTypedParameterList) { for (int p = 0; p < anonymousFunction.ParameterCount; ++p) { if (!anonymousFunction.ParameterType(p).Equals(fixedDelegateParameters[p].Type, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { return default; } } } // Future optimization: We could return default if the delegate has out or ref parameters // and the anonymous function is an implicitly typed lambda. It will not be applicable. // We have an entirely fixed delegate parameter list, which is of the same arity as // the anonymous function parameter list, and possibly exactly the same types if // the anonymous function is explicitly typed. Make an inference from the // delegate parameters to the return type. return anonymousFunction.InferReturnType(_conversions, fixedDelegate, ref useSiteInfo); } /// <summary> /// Return the interface with an original definition matches /// the original definition of the target. If the are no matches, /// or multiple matches, the return value is null. /// </summary> private static NamedTypeSymbol GetInterfaceInferenceBound(ImmutableArray<NamedTypeSymbol> interfaces, NamedTypeSymbol target) { Debug.Assert(target.IsInterface); NamedTypeSymbol matchingInterface = null; foreach (var currentInterface in interfaces) { if (TypeSymbol.Equals(currentInterface.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything)) { if ((object)matchingInterface == null) { matchingInterface = currentInterface; } else if (!TypeSymbol.Equals(matchingInterface, currentInterface, TypeCompareKind.ConsiderEverything)) { // Not unique. Bail out. return null; } } } return matchingInterface; } //////////////////////////////////////////////////////////////////////////////// // // Helper methods // //////////////////////////////////////////////////////////////////////////////// // // In error recovery and reporting scenarios we sometimes end up in a situation // like this: // // x.Goo( y=> // // and the question is, "is Goo a valid extension method of x?" If Goo is // generic, then Goo will be something like: // // static Blah Goo<T>(this Bar<T> bar, Func<T, T> f){ ... } // // What we would like to know is: given _only_ the expression x, can we infer // what T is in Bar<T> ? If we can, then for error recovery and reporting // we can provisionally consider Goo to be an extension method of x. If we // cannot deduce this just from x then we should consider Goo to not be an // extension method of x, at least until we have more information. // // Clearly it is pointless to run multiple phases public static ImmutableArray<TypeWithAnnotations> InferTypeArgumentsFromFirstArgument( ConversionsBase conversions, MethodSymbol method, ImmutableArray<BoundExpression> arguments, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)method != null); Debug.Assert(method.Arity > 0); Debug.Assert(!arguments.IsDefault); // We need at least one formal parameter type and at least one argument. if ((method.ParameterCount < 1) || (arguments.Length < 1)) { return default(ImmutableArray<TypeWithAnnotations>); } Debug.Assert(!method.GetParameterType(0).IsDynamic()); var constructedFromMethod = method.ConstructedFrom; var inferrer = new MethodTypeInferrer( conversions, constructedFromMethod.TypeParameters, constructedFromMethod.ContainingType, constructedFromMethod.GetParameterTypes(), constructedFromMethod.ParameterRefKinds, arguments, extensions: null); if (!inferrer.InferTypeArgumentsFromFirstArgument(ref useSiteInfo)) { return default(ImmutableArray<TypeWithAnnotations>); } return inferrer.GetInferredTypeArguments(); } //////////////////////////////////////////////////////////////////////////////// private bool InferTypeArgumentsFromFirstArgument(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(!_formalParameterTypes.IsDefault); Debug.Assert(_formalParameterTypes.Length >= 1); Debug.Assert(!_arguments.IsDefault); Debug.Assert(_arguments.Length >= 1); var dest = _formalParameterTypes[0]; var argument = _arguments[0]; TypeSymbol source = argument.Type; // Rule out lambdas, nulls, and so on. if (!IsReallyAType(source)) { return false; } LowerBoundInference(_extensions.GetTypeWithAnnotations(argument), dest, ref useSiteInfo); // Now check to see that every type parameter used by the first // formal parameter type was successfully inferred. for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { TypeParameterSymbol pParam = _methodTypeParameters[iParam]; if (!dest.Type.ContainsTypeParameter(pParam)) { continue; } Debug.Assert(IsUnfixed(iParam)); if (!HasBound(iParam) || !Fix(iParam, ref useSiteInfo)) { return false; } } return true; } /// <summary> /// Return the inferred type arguments using null /// for any type arguments that were not inferred. /// </summary> private ImmutableArray<TypeWithAnnotations> GetInferredTypeArguments() { return _fixedResults.AsImmutable(); } private static bool IsReallyAType(TypeSymbol type) { return (object)type != null && !type.IsErrorType() && !type.IsVoidType(); } private static void GetAllCandidates(Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, ArrayBuilder<TypeWithAnnotations> builder) { builder.AddRange(candidates.Values); } private static void AddAllCandidates( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, HashSet<TypeWithAnnotations> bounds, VarianceKind variance, ConversionsBase conversions) { foreach (var candidate in bounds) { var type = candidate; if (!conversions.IncludeNullability) { // https://github.com/dotnet/roslyn/issues/30534: Should preserve // distinct "not computed" state from initial binding. type = type.SetUnknownNullabilityForReferenceTypes(); } AddOrMergeCandidate(candidates, type, variance, conversions); } } private static void AddOrMergeCandidate( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, TypeWithAnnotations newCandidate, VarianceKind variance, ConversionsBase conversions) { Debug.Assert(conversions.IncludeNullability || newCandidate.SetUnknownNullabilityForReferenceTypes().Equals(newCandidate, TypeCompareKind.ConsiderEverything)); if (candidates.TryGetValue(newCandidate, out TypeWithAnnotations oldCandidate)) { MergeAndReplaceIfStillCandidate(candidates, oldCandidate, newCandidate, variance, conversions); } else { candidates.Add(newCandidate, newCandidate); } } private static void MergeOrRemoveCandidates( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, HashSet<TypeWithAnnotations> bounds, ArrayBuilder<TypeWithAnnotations> initialCandidates, ConversionsBase conversions, VarianceKind variance, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(variance == VarianceKind.In || variance == VarianceKind.Out); // SPEC: For each lower (upper) bound U of Xi all types to which there is not an // SPEC: implicit conversion from (to) U are removed from the candidate set. var comparison = conversions.IncludeNullability ? TypeCompareKind.ConsiderEverything : TypeCompareKind.IgnoreNullableModifiersForReferenceTypes; foreach (var bound in bounds) { foreach (var candidate in initialCandidates) { if (bound.Equals(candidate, comparison)) { continue; } TypeWithAnnotations source; TypeWithAnnotations destination; if (variance == VarianceKind.Out) { source = bound; destination = candidate; } else { source = candidate; destination = bound; } if (!ImplicitConversionExists(source, destination, ref useSiteInfo, conversions.WithNullability(false))) { candidates.Remove(candidate); if (conversions.IncludeNullability && candidates.TryGetValue(bound, out var oldBound)) { // merge the nullability from candidate into bound var oldAnnotation = oldBound.NullableAnnotation; var newAnnotation = oldAnnotation.MergeNullableAnnotation(candidate.NullableAnnotation, variance); if (oldAnnotation != newAnnotation) { var newBound = TypeWithAnnotations.Create(oldBound.Type, newAnnotation); candidates[bound] = newBound; } } } else if (bound.Equals(candidate, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { // SPEC: 4.7 The Dynamic Type // Type inference (7.5.2) will prefer dynamic over object if both are candidates. // // This rule doesn't have to be implemented explicitly due to special handling of // conversions from dynamic in ImplicitConversionExists helper. // MergeAndReplaceIfStillCandidate(candidates, candidate, bound, variance, conversions); } } } } private static void MergeAndReplaceIfStillCandidate( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, TypeWithAnnotations oldCandidate, TypeWithAnnotations newCandidate, VarianceKind variance, ConversionsBase conversions) { // We make an exception when new candidate is dynamic, for backwards compatibility if (newCandidate.Type.IsDynamic()) { return; } if (candidates.TryGetValue(oldCandidate, out TypeWithAnnotations latest)) { // Note: we're ignoring the variance used merging previous candidates into `latest`. // If that variance is different than `variance`, we might infer the wrong nullability, but in that case, // we assume we'll report a warning when converting the arguments to the inferred parameter types. // (For instance, with F<T>(T x, T y, IIn<T> z) and interface IIn<in T> and interface IIOut<out T>, the // call F(IOut<object?>, IOut<object!>, IIn<IOut<object!>>) should find a nullability mismatch. Instead, // we'll merge the lower bounds IOut<object?> with IOut<object!> (using VarianceKind.Out) to produce // IOut<object?>, then merge that result with upper bound IOut<object!> (using VarianceKind.In) // to produce IOut<object?>. But then conversion of argument IIn<IOut<object!>> to parameter // IIn<IOut<object?>> will generate a warning at that point.) TypeWithAnnotations merged = latest.MergeEquivalentTypes(newCandidate, variance); candidates[oldCandidate] = merged; } } /// <summary> /// This is a comparer that ignores differences in dynamic-ness and tuple names. /// But it has a special case for top-level object vs. dynamic for purpose of method type inference. /// </summary> private sealed class EqualsIgnoringDynamicTupleNamesAndNullabilityComparer : EqualityComparer<TypeWithAnnotations> { internal static readonly EqualsIgnoringDynamicTupleNamesAndNullabilityComparer Instance = new EqualsIgnoringDynamicTupleNamesAndNullabilityComparer(); public override int GetHashCode(TypeWithAnnotations obj) { return obj.Type.GetHashCode(); } public override bool Equals(TypeWithAnnotations x, TypeWithAnnotations y) { // We do a equality test ignoring dynamic and tuple names differences, // but dynamic and object are not considered equal for backwards compatibility. if (x.Type.IsDynamic() ^ y.Type.IsDynamic()) { return false; } return x.Equals(y, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; /* SPEC: Type inference occurs as part of the compile-time processing of a method invocation and takes place before the overload resolution step of the invocation. When a particular method group is specified in a method invocation, and no type arguments are specified as part of the method invocation, type inference is applied to each generic method in the method group. If type inference succeeds, then the inferred type arguments are used to determine the types of formal parameters for subsequent overload resolution. If overload resolution chooses a generic method as the one to invoke then the inferred type arguments are used as the actual type arguments for the invocation. If type inference for a particular method fails, that method does not participate in overload resolution. The failure of type inference, in and of itself, does not cause a compile-time error. However, it often leads to a compile-time error when overload resolution then fails to find any applicable methods. If the supplied number of arguments is different than the number of parameters in the method, then inference immediately fails. Otherwise, assume that the generic method has the following signature: Tr M<X1...Xn>(T1 x1 ... Tm xm) With a method call of the form M(E1...Em) the task of type inference is to find unique type arguments S1...Sn for each of the type parameters X1...Xn so that the call M<S1...Sn>(E1...Em)becomes valid. During the process of inference each type parameter Xi is either fixed to a particular type Si or unfixed with an associated set of bounds. Each of the bounds is some type T. Each bound is classified as an upper bound, lower bound or exact bound. Initially each type variable Xi is unfixed with an empty set of bounds. */ // This file contains the implementation for method type inference on calls (with // arguments, and method type inference on conversion of method groups to delegate // types (which will not have arguments.) namespace Microsoft.CodeAnalysis.CSharp { internal static class PooledDictionaryIgnoringNullableModifiersForReferenceTypes { private static readonly ObjectPool<PooledDictionary<NamedTypeSymbol, NamedTypeSymbol>> s_poolInstance = PooledDictionary<NamedTypeSymbol, NamedTypeSymbol>.CreatePool(Symbols.SymbolEqualityComparer.IgnoringNullable); internal static PooledDictionary<NamedTypeSymbol, NamedTypeSymbol> GetInstance() { var instance = s_poolInstance.Allocate(); Debug.Assert(instance.Count == 0); return instance; } } // Method type inference can fail, but we still might have some best guesses. internal struct MethodTypeInferenceResult { public readonly ImmutableArray<TypeWithAnnotations> InferredTypeArguments; public readonly bool Success; public MethodTypeInferenceResult( bool success, ImmutableArray<TypeWithAnnotations> inferredTypeArguments) { this.Success = success; this.InferredTypeArguments = inferredTypeArguments; } } internal sealed class MethodTypeInferrer { internal abstract class Extensions { internal static readonly Extensions Default = new DefaultExtensions(); internal abstract TypeWithAnnotations GetTypeWithAnnotations(BoundExpression expr); internal abstract TypeWithAnnotations GetMethodGroupResultType(BoundMethodGroup group, MethodSymbol method); private sealed class DefaultExtensions : Extensions { internal override TypeWithAnnotations GetTypeWithAnnotations(BoundExpression expr) { return TypeWithAnnotations.Create(expr.Type); } internal override TypeWithAnnotations GetMethodGroupResultType(BoundMethodGroup group, MethodSymbol method) { return method.ReturnTypeWithAnnotations; } } } private enum InferenceResult { InferenceFailed, MadeProgress, NoProgress, Success } private enum Dependency { Unknown = 0x00, NotDependent = 0x01, DependsMask = 0x10, Direct = 0x11, Indirect = 0x12 } private readonly ConversionsBase _conversions; private readonly ImmutableArray<TypeParameterSymbol> _methodTypeParameters; private readonly NamedTypeSymbol _constructedContainingTypeOfMethod; private readonly ImmutableArray<TypeWithAnnotations> _formalParameterTypes; private readonly ImmutableArray<RefKind> _formalParameterRefKinds; private readonly ImmutableArray<BoundExpression> _arguments; private readonly Extensions _extensions; private readonly TypeWithAnnotations[] _fixedResults; private readonly HashSet<TypeWithAnnotations>[] _exactBounds; private readonly HashSet<TypeWithAnnotations>[] _upperBounds; private readonly HashSet<TypeWithAnnotations>[] _lowerBounds; private Dependency[,] _dependencies; // Initialized lazily private bool _dependenciesDirty; /// <summary> /// For error recovery, we allow a mismatch between the number of arguments and parameters /// during type inference. This sometimes enables inferring the type for a lambda parameter. /// </summary> private int NumberArgumentsToProcess => System.Math.Min(_arguments.Length, _formalParameterTypes.Length); public static MethodTypeInferenceResult Infer( Binder binder, ConversionsBase conversions, ImmutableArray<TypeParameterSymbol> methodTypeParameters, // We are attempting to build a map from method type parameters // to inferred type arguments. NamedTypeSymbol constructedContainingTypeOfMethod, ImmutableArray<TypeWithAnnotations> formalParameterTypes, // We have some unusual requirements for the types that flow into the inference engine. // Consider the following inference problems: // // Scenario one: // // class C<T> // { // delegate Y FT<X, Y>(T t, X x); // static void M<U, V>(U u, FT<U, V> f); // ... // C<double>.M(123, (t,x)=>t+x); // // From the first argument we infer that U is int. How now must we make an inference on // the second argument? The *declared* type of the formal is C<T>.FT<U,V>. The // actual type at the time of inference is known to be C<double>.FT<int, something> // where "something" is to be determined by inferring the return type of the // lambda by determine the type of "double + int". // // Therefore when we do type inference, if a formal parameter type is a generic delegate // then *its* formal parameter types must be the formal parameter types of the // *constructed* generic delegate C<double>.FT<...>, not C<T>.FT<...>. // // One would therefore suppose that we'd expect the formal parameter types to here // be passed in with the types constructed with the information known from the // call site, not the declared types. // // Contrast that with this scenario: // // Scenario Two: // // interface I<T> // { // void M<U>(T t, U u); // } // ... // static void Goo<V>(V v, I<V> iv) // { // iv.M(v, ""); // } // // Obviously inference should succeed here; it should infer that U is string. // // But consider what happens during the inference process on the first argument. // The first thing we will do is say "what's the type of the argument? V. What's // the type of the corresponding formal parameter? The first formal parameter of // I<V>.M<whatever> is of type V. The inference engine will then say "V is a // method type parameter, and therefore we have an inference from V to V". // But *V* is not one of the method type parameters being inferred; the only // method type parameter being inferred here is *U*. // // This is perhaps some evidence that the formal parameters passed in should be // the formal parameters of the *declared* method; in this case, (T, U), not // the formal parameters of the *constructed* method, (V, U). // // However, one might make the argument that no, we could just add a check // to ensure that if we see a method type parameter as a formal parameter type, // then we only perform the inference if the method type parameter is a type // parameter of the method for which inference is being performed. // // Unfortunately, that does not work either: // // Scenario three: // // class C<T> // { // static void M<U>(T t, U u) // { // ... // C<U>.M(u, 123); // ... // } // } // // The *original* formal parameter types are (T, U); the *constructed* formal parameter types // are (U, U), but *those are logically two different U's*. The first U is from the outer caller; // the second U is the U of the recursive call. // // That is, suppose someone called C<string>.M<double>(string, double). The recursive call should be to // C<double>.M<int>(double, int). We should absolutely not make an inference on the first argument // from U to U just because C<U>.M<something>'s first formal parameter is of type U. If we did then // inference would fail, because we'd end up with two bounds on 'U' -- 'U' and 'int'. We only want // the latter bound. // // What these three scenarios show is that for a "normal" inference we need to have the // formal parameters of the *original* method definition, but when making an inference from a lambda // to a delegate, we need to have the *constructed* method signature in order that the formal // parameters *of the delegate* be correct. // // How to solve this problem? // // We solve it by passing in the formal parameters in their *original* form, but also getting // the *fully constructed* type that the method call is on. When constructing the fixed // delegate type for inference from a lambda, we do the appropriate type substitution on // the delegate. ImmutableArray<RefKind> formalParameterRefKinds, // Optional; assume all value if missing. ImmutableArray<BoundExpression> arguments,// Required; in scenarios like method group conversions where there are // no arguments per se we cons up some fake arguments. ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, Extensions extensions = null) { Debug.Assert(!methodTypeParameters.IsDefault); Debug.Assert(methodTypeParameters.Length > 0); Debug.Assert(!formalParameterTypes.IsDefault); Debug.Assert(formalParameterRefKinds.IsDefault || formalParameterRefKinds.Length == formalParameterTypes.Length); Debug.Assert(!arguments.IsDefault); // Early out: if the method has no formal parameters then we know that inference will fail. if (formalParameterTypes.Length == 0) { return new MethodTypeInferenceResult(false, default(ImmutableArray<TypeWithAnnotations>)); // UNDONE: OPTIMIZATION: We could check to see whether there is a type // UNDONE: parameter which is never used in any formal parameter; if // UNDONE: so then we know ahead of time that inference will fail. } var inferrer = new MethodTypeInferrer( conversions, methodTypeParameters, constructedContainingTypeOfMethod, formalParameterTypes, formalParameterRefKinds, arguments, extensions); return inferrer.InferTypeArgs(binder, ref useSiteInfo); } //////////////////////////////////////////////////////////////////////////////// // // Fixed, unfixed and bounded type parameters // // SPEC: During the process of inference each type parameter is either fixed to // SPEC: a particular type or unfixed with an associated set of bounds. Each of // SPEC: the bounds is of some type T. Initially each type parameter is unfixed // SPEC: with an empty set of bounds. private MethodTypeInferrer( ConversionsBase conversions, ImmutableArray<TypeParameterSymbol> methodTypeParameters, NamedTypeSymbol constructedContainingTypeOfMethod, ImmutableArray<TypeWithAnnotations> formalParameterTypes, ImmutableArray<RefKind> formalParameterRefKinds, ImmutableArray<BoundExpression> arguments, Extensions extensions) { _conversions = conversions; _methodTypeParameters = methodTypeParameters; _constructedContainingTypeOfMethod = constructedContainingTypeOfMethod; _formalParameterTypes = formalParameterTypes; _formalParameterRefKinds = formalParameterRefKinds; _arguments = arguments; _extensions = extensions ?? Extensions.Default; _fixedResults = new TypeWithAnnotations[methodTypeParameters.Length]; _exactBounds = new HashSet<TypeWithAnnotations>[methodTypeParameters.Length]; _upperBounds = new HashSet<TypeWithAnnotations>[methodTypeParameters.Length]; _lowerBounds = new HashSet<TypeWithAnnotations>[methodTypeParameters.Length]; _dependencies = null; _dependenciesDirty = false; } #if DEBUG internal string Dump() { var sb = new System.Text.StringBuilder(); sb.AppendLine("Method type inference internal state"); sb.AppendFormat("Inferring method type parameters <{0}>\n", string.Join(", ", _methodTypeParameters)); sb.Append("Formal parameter types ("); for (int i = 0; i < _formalParameterTypes.Length; ++i) { if (i != 0) { sb.Append(", "); } sb.Append(GetRefKind(i).ToParameterPrefix()); sb.Append(_formalParameterTypes[i]); } sb.Append("\n"); sb.AppendFormat("Argument types ({0})\n", string.Join(", ", from a in _arguments select a.Type)); if (_dependencies == null) { sb.AppendLine("Dependencies are not yet calculated"); } else { sb.AppendFormat("Dependencies are {0}\n", _dependenciesDirty ? "out of date" : "up to date"); sb.AppendLine("dependency matrix (Not dependent / Direct / Indirect / Unknown):"); for (int i = 0; i < _methodTypeParameters.Length; ++i) { for (int j = 0; j < _methodTypeParameters.Length; ++j) { switch (_dependencies[i, j]) { case Dependency.NotDependent: sb.Append("N"); break; case Dependency.Direct: sb.Append("D"); break; case Dependency.Indirect: sb.Append("I"); break; case Dependency.Unknown: sb.Append("U"); break; } } sb.AppendLine(); } } for (int i = 0; i < _methodTypeParameters.Length; ++i) { sb.AppendFormat("Method type parameter {0}: ", _methodTypeParameters[i].Name); var fixedType = _fixedResults[i]; if (!fixedType.HasType) { sb.Append("UNFIXED "); } else { sb.AppendFormat("FIXED to {0} ", fixedType); } sb.AppendFormat("upper bounds: ({0}) ", (_upperBounds[i] == null) ? "" : string.Join(", ", _upperBounds[i])); sb.AppendFormat("lower bounds: ({0}) ", (_lowerBounds[i] == null) ? "" : string.Join(", ", _lowerBounds[i])); sb.AppendFormat("exact bounds: ({0}) ", (_exactBounds[i] == null) ? "" : string.Join(", ", _exactBounds[i])); sb.AppendLine(); } return sb.ToString(); } #endif private RefKind GetRefKind(int index) { Debug.Assert(0 <= index && index < _formalParameterTypes.Length); return _formalParameterRefKinds.IsDefault ? RefKind.None : _formalParameterRefKinds[index]; } private ImmutableArray<TypeWithAnnotations> GetResults() { // Anything we didn't infer a type for, give the error type. // Note: the error type will have the same name as the name // of the type parameter we were trying to infer. This will give a // nice user experience where by we will show something like // the following: // // user types: customers.Select( // we show : IE<TResult> IE<Customer>.Select<Customer,TResult>(Func<Customer,TResult> selector) // // Initially we thought we'd just show ?. i.e.: // // IE<?> IE<Customer>.Select<Customer,?>(Func<Customer,?> selector) // // This is nice and concise. However, it falls down if there are multiple // type params that we have left. for (int i = 0; i < _methodTypeParameters.Length; i++) { if (_fixedResults[i].HasType) { if (!_fixedResults[i].Type.IsErrorType()) { continue; } var errorTypeName = _fixedResults[i].Type.Name; if (errorTypeName != null) { continue; } } _fixedResults[i] = TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol(_constructedContainingTypeOfMethod, _methodTypeParameters[i].Name, 0, null, false)); } return _fixedResults.AsImmutable(); } private bool ValidIndex(int index) { return 0 <= index && index < _methodTypeParameters.Length; } private bool IsUnfixed(int methodTypeParameterIndex) { Debug.Assert(ValidIndex(methodTypeParameterIndex)); return !_fixedResults[methodTypeParameterIndex].HasType; } private bool IsUnfixedTypeParameter(TypeWithAnnotations type) { Debug.Assert(type.HasType); if (type.TypeKind != TypeKind.TypeParameter) return false; TypeParameterSymbol typeParameter = (TypeParameterSymbol)type.Type; int ordinal = typeParameter.Ordinal; return ValidIndex(ordinal) && TypeSymbol.Equals(typeParameter, _methodTypeParameters[ordinal], TypeCompareKind.ConsiderEverything2) && IsUnfixed(ordinal); } private bool AllFixed() { for (int methodTypeParameterIndex = 0; methodTypeParameterIndex < _methodTypeParameters.Length; ++methodTypeParameterIndex) { if (IsUnfixed(methodTypeParameterIndex)) { return false; } } return true; } private void AddBound(TypeWithAnnotations addedBound, HashSet<TypeWithAnnotations>[] collectedBounds, TypeWithAnnotations methodTypeParameterWithAnnotations) { Debug.Assert(IsUnfixedTypeParameter(methodTypeParameterWithAnnotations)); var methodTypeParameter = (TypeParameterSymbol)methodTypeParameterWithAnnotations.Type; int methodTypeParameterIndex = methodTypeParameter.Ordinal; if (collectedBounds[methodTypeParameterIndex] == null) { collectedBounds[methodTypeParameterIndex] = new HashSet<TypeWithAnnotations>(TypeWithAnnotations.EqualsComparer.ConsiderEverythingComparer); } collectedBounds[methodTypeParameterIndex].Add(addedBound); } private bool HasBound(int methodTypeParameterIndex) { Debug.Assert(ValidIndex(methodTypeParameterIndex)); return _lowerBounds[methodTypeParameterIndex] != null || _upperBounds[methodTypeParameterIndex] != null || _exactBounds[methodTypeParameterIndex] != null; } private TypeSymbol GetFixedDelegateOrFunctionPointer(TypeSymbol delegateOrFunctionPointerType) { Debug.Assert((object)delegateOrFunctionPointerType != null); Debug.Assert(delegateOrFunctionPointerType.IsDelegateType() || delegateOrFunctionPointerType is FunctionPointerTypeSymbol); // We have a delegate where the input types use no unfixed parameters. Create // a substitution context; we can substitute unfixed parameters for themselves // since they don't actually occur in the inputs. (They may occur in the outputs, // or there may be input parameters fixed to _unfixed_ method type variables. // Both of those scenarios are legal.) var fixedArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(_methodTypeParameters.Length); for (int iParam = 0; iParam < _methodTypeParameters.Length; iParam++) { fixedArguments.Add(IsUnfixed(iParam) ? TypeWithAnnotations.Create(_methodTypeParameters[iParam]) : _fixedResults[iParam]); } TypeMap typeMap = new TypeMap(_constructedContainingTypeOfMethod, _methodTypeParameters, fixedArguments.ToImmutableAndFree()); return typeMap.SubstituteType(delegateOrFunctionPointerType).Type; } //////////////////////////////////////////////////////////////////////////////// // // Phases // private MethodTypeInferenceResult InferTypeArgs(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: Type inference takes place in phases. Each phase will try to infer type // SPEC: arguments for more type parameters based on the findings of the previous // SPEC: phase. The first phase makes some initial inferences of bounds, whereas // SPEC: the second phase fixes type parameters to specific types and infers further // SPEC: bounds. The second phase may have to be repeated a number of times. InferTypeArgsFirstPhase(ref useSiteInfo); bool success = InferTypeArgsSecondPhase(binder, ref useSiteInfo); return new MethodTypeInferenceResult(success, GetResults()); } //////////////////////////////////////////////////////////////////////////////// // // The first phase // private void InferTypeArgsFirstPhase(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(!_formalParameterTypes.IsDefault); Debug.Assert(!_arguments.IsDefault); // We expect that we have been handed a list of arguments and a list of the // formal parameter types they correspond to; all the details about named and // optional parameters have already been dealt with. // SPEC: For each of the method arguments Ei: for (int arg = 0, length = this.NumberArgumentsToProcess; arg < length; arg++) { BoundExpression argument = _arguments[arg]; TypeWithAnnotations target = _formalParameterTypes[arg]; ExactOrBoundsKind kind = GetRefKind(arg).IsManagedReference() || target.Type.IsPointerType() ? ExactOrBoundsKind.Exact : ExactOrBoundsKind.LowerBound; MakeExplicitParameterTypeInferences(argument, target, kind, ref useSiteInfo); } } private void MakeExplicitParameterTypeInferences(BoundExpression argument, TypeWithAnnotations target, ExactOrBoundsKind kind, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * If Ei is an anonymous function, an explicit type parameter // SPEC: inference is made from Ei to Ti. // (We cannot make an output type inference from a method group // at this time because we have no fixed types yet to use for // overload resolution.) // SPEC: * Otherwise, if Ei has a type U then a lower-bound inference // SPEC: or exact inference is made from U to Ti. // SPEC: * Otherwise, no inference is made for this argument if (argument.Kind == BoundKind.UnboundLambda) { ExplicitParameterTypeInference(argument, target, ref useSiteInfo); } else if (argument.Kind != BoundKind.TupleLiteral || !MakeExplicitParameterTypeInferences((BoundTupleLiteral)argument, target, kind, ref useSiteInfo)) { // Either the argument is not a tuple literal, or we were unable to do the inference from its elements, let's try to infer from argument type if (IsReallyAType(argument.Type)) { ExactOrBoundsInference(kind, _extensions.GetTypeWithAnnotations(argument), target, ref useSiteInfo); } } } private bool MakeExplicitParameterTypeInferences(BoundTupleLiteral argument, TypeWithAnnotations target, ExactOrBoundsKind kind, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // try match up element-wise to the destination tuple (or underlying type) // Example: // if "(a: 1, b: "qq")" is passed as (T, U) arg // then T becomes int and U becomes string if (target.Type.Kind != SymbolKind.NamedType) { // tuples can only match to tuples or tuple underlying types. return false; } var destination = (NamedTypeSymbol)target.Type; var sourceArguments = argument.Arguments; // check if the type is actually compatible type for a tuple of given cardinality if (!destination.IsTupleTypeOfCardinality(sourceArguments.Length)) { // target is not a tuple of appropriate shape return false; } var destTypes = destination.TupleElementTypesWithAnnotations; Debug.Assert(sourceArguments.Length == destTypes.Length); // NOTE: we are losing tuple element names when recursing into argument expressions. // that is ok, because we are inferring type parameters used in the matching elements, // This is not the situation where entire tuple literal is used to infer a single type param for (int i = 0; i < sourceArguments.Length; i++) { var sourceArgument = sourceArguments[i]; var destType = destTypes[i]; MakeExplicitParameterTypeInferences(sourceArgument, destType, kind, ref useSiteInfo); } return true; } //////////////////////////////////////////////////////////////////////////////// // // The second phase // private bool InferTypeArgsSecondPhase(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The second phase proceeds as follows: // SPEC: * If no unfixed type parameters exist then type inference succeeds. // SPEC: * Otherwise, if there exists one or more arguments Ei with corresponding // SPEC: parameter type Ti such that: // SPEC: o the output type of Ei with type Ti contains at least one unfixed // SPEC: type parameter Xj, and // SPEC: o none of the input types of Ei with type Ti contains any unfixed // SPEC: type parameter Xj, // SPEC: then an output type inference is made from all such Ei to Ti. // SPEC: * Whether or not the previous step actually made an inference, we must // SPEC: now fix at least one type parameter, as follows: // SPEC: * If there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o Xi does not depend on any Xj // SPEC: then each such Xi is fixed. If any fixing operation fails then type // SPEC: inference fails. // SPEC: * Otherwise, if there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o there is at least one type parameter Xj that depends on Xi // SPEC: then each such Xi is fixed. If any fixing operation fails then // SPEC: type inference fails. // SPEC: * Otherwise, we are unable to make progress and there are unfixed parameters. // SPEC: Type inference fails. // SPEC: * If type inference neither succeeds nor fails then the second phase is // SPEC: repeated until type inference succeeds or fails. (Since each repetition of // SPEC: the second phase either succeeds, fails or fixes an unfixed type parameter, // SPEC: the algorithm must terminate with no more repetitions than the number // SPEC: of type parameters. InitializeDependencies(); while (true) { var res = DoSecondPhase(binder, ref useSiteInfo); Debug.Assert(res != InferenceResult.NoProgress); if (res == InferenceResult.InferenceFailed) { return false; } if (res == InferenceResult.Success) { return true; } // Otherwise, we made some progress last time; do it again. } } private InferenceResult DoSecondPhase(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * If no unfixed type parameters exist then type inference succeeds. if (AllFixed()) { return InferenceResult.Success; } // SPEC: * Otherwise, if there exists one or more arguments Ei with // SPEC: corresponding parameter type Ti such that: // SPEC: o the output type of Ei with type Ti contains at least one unfixed // SPEC: type parameter Xj, and // SPEC: o none of the input types of Ei with type Ti contains any unfixed // SPEC: type parameter Xj, // SPEC: then an output type inference is made from all such Ei to Ti. MakeOutputTypeInferences(binder, ref useSiteInfo); // SPEC: * Whether or not the previous step actually made an inference, we // SPEC: must now fix at least one type parameter, as follows: // SPEC: * If there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o Xi does not depend on any Xj // SPEC: then each such Xi is fixed. If any fixing operation fails then // SPEC: type inference fails. InferenceResult res; res = FixNondependentParameters(ref useSiteInfo); if (res != InferenceResult.NoProgress) { return res; } // SPEC: * Otherwise, if there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o there is at least one type parameter Xj that depends on Xi // SPEC: then each such Xi is fixed. If any fixing operation fails then // SPEC: type inference fails. res = FixDependentParameters(ref useSiteInfo); if (res != InferenceResult.NoProgress) { return res; } // SPEC: * Otherwise, we are unable to make progress and there are // SPEC: unfixed parameters. Type inference fails. return InferenceResult.InferenceFailed; } private void MakeOutputTypeInferences(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: Otherwise, for all arguments Ei with corresponding parameter type Ti // SPEC: where the output types contain unfixed type parameters but the input // SPEC: types do not, an output type inference is made from Ei to Ti. for (int arg = 0, length = this.NumberArgumentsToProcess; arg < length; arg++) { var formalType = _formalParameterTypes[arg]; var argument = _arguments[arg]; MakeOutputTypeInferences(binder, argument, formalType, ref useSiteInfo); } } private void MakeOutputTypeInferences(Binder binder, BoundExpression argument, TypeWithAnnotations formalType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (argument.Kind == BoundKind.TupleLiteral && (object)argument.Type == null) { MakeOutputTypeInferences(binder, (BoundTupleLiteral)argument, formalType, ref useSiteInfo); } else { if (HasUnfixedParamInOutputType(argument, formalType.Type) && !HasUnfixedParamInInputType(argument, formalType.Type)) { //UNDONE: if (argument->isTYPEORNAMESPACEERROR() && argumentType->IsErrorType()) //UNDONE: { //UNDONE: argumentType = GetTypeManager().GetErrorSym(); //UNDONE: } OutputTypeInference(binder, argument, formalType, ref useSiteInfo); } } } private void MakeOutputTypeInferences(Binder binder, BoundTupleLiteral argument, TypeWithAnnotations formalType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (formalType.Type.Kind != SymbolKind.NamedType) { // tuples can only match to tuples or tuple underlying types. return; } var destination = (NamedTypeSymbol)formalType.Type; Debug.Assert((object)argument.Type == null, "should not need to dig into elements if tuple has natural type"); var sourceArguments = argument.Arguments; // check if the type is actually compatible type for a tuple of given cardinality if (!destination.IsTupleTypeOfCardinality(sourceArguments.Length)) { return; } var destTypes = destination.TupleElementTypesWithAnnotations; Debug.Assert(sourceArguments.Length == destTypes.Length); for (int i = 0; i < sourceArguments.Length; i++) { var sourceArgument = sourceArguments[i]; var destType = destTypes[i]; MakeOutputTypeInferences(binder, sourceArgument, destType, ref useSiteInfo); } } private InferenceResult FixNondependentParameters(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * Otherwise, if there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o Xi does not depend on any Xj // SPEC: then each such Xi is fixed. return FixParameters((inferrer, index) => !inferrer.DependsOnAny(index), ref useSiteInfo); } private InferenceResult FixDependentParameters(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * All unfixed type parameters Xi are fixed for which all of the following hold: // SPEC: * There is at least one type parameter Xj that depends on Xi. // SPEC: * Xi has a non-empty set of bounds. return FixParameters((inferrer, index) => inferrer.AnyDependsOn(index), ref useSiteInfo); } private InferenceResult FixParameters( Func<MethodTypeInferrer, int, bool> predicate, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // Dependency is only defined for unfixed parameters. Therefore, fixing // a parameter may cause all of its dependencies to become no longer // dependent on anything. We need to first determine which parameters need to be // fixed, and then fix them all at once. var needsFixing = new bool[_methodTypeParameters.Length]; var result = InferenceResult.NoProgress; for (int param = 0; param < _methodTypeParameters.Length; param++) { if (IsUnfixed(param) && HasBound(param) && predicate(this, param)) { needsFixing[param] = true; result = InferenceResult.MadeProgress; } } for (int param = 0; param < _methodTypeParameters.Length; param++) { // Fix as much as you can, even if there are errors. That will // help with intellisense. if (needsFixing[param]) { if (!Fix(param, ref useSiteInfo)) { result = InferenceResult.InferenceFailed; } } } return result; } //////////////////////////////////////////////////////////////////////////////// // // Input types // private static bool DoesInputTypeContain(BoundExpression argument, TypeSymbol formalParameterType, TypeParameterSymbol typeParameter) { // SPEC: If E is a method group or an anonymous function and T is a delegate // SPEC: type or expression tree type then all the parameter types of T are // SPEC: input types of E with type T. var delegateOrFunctionPointerType = formalParameterType.GetDelegateOrFunctionPointerType(); if ((object)delegateOrFunctionPointerType == null) { return false; // No input types. } var isFunctionPointer = delegateOrFunctionPointerType.IsFunctionPointer(); if ((isFunctionPointer && argument.Kind != BoundKind.UnconvertedAddressOfOperator) || (!isFunctionPointer && argument.Kind is not (BoundKind.UnboundLambda or BoundKind.MethodGroup))) { return false; // No input types. } var parameters = delegateOrFunctionPointerType.DelegateOrFunctionPointerParameters(); if (parameters.IsDefaultOrEmpty) { return false; } foreach (var parameter in parameters) { if (parameter.Type.ContainsTypeParameter(typeParameter)) { return true; } } return false; } private bool HasUnfixedParamInInputType(BoundExpression pSource, TypeSymbol pDest) { for (int iParam = 0; iParam < _methodTypeParameters.Length; iParam++) { if (IsUnfixed(iParam)) { if (DoesInputTypeContain(pSource, pDest, _methodTypeParameters[iParam])) { return true; } } } return false; } //////////////////////////////////////////////////////////////////////////////// // // Output types // private static bool DoesOutputTypeContain(BoundExpression argument, TypeSymbol formalParameterType, TypeParameterSymbol typeParameter) { // SPEC: If E is a method group or an anonymous function and T is a delegate // SPEC: type or expression tree type then the return type of T is an output type // SPEC: of E with type T. var delegateOrFunctionPointerType = formalParameterType.GetDelegateOrFunctionPointerType(); if ((object)delegateOrFunctionPointerType == null) { return false; } var isFunctionPointer = delegateOrFunctionPointerType.IsFunctionPointer(); if ((isFunctionPointer && argument.Kind != BoundKind.UnconvertedAddressOfOperator) || (!isFunctionPointer && argument.Kind is not (BoundKind.UnboundLambda or BoundKind.MethodGroup))) { return false; } MethodSymbol method = delegateOrFunctionPointerType switch { NamedTypeSymbol n => n.DelegateInvokeMethod, FunctionPointerTypeSymbol f => f.Signature, _ => throw ExceptionUtilities.UnexpectedValue(delegateOrFunctionPointerType) }; if ((object)method == null || method.HasUseSiteError) { return false; } var returnType = method.ReturnType; if ((object)returnType == null) { return false; } return returnType.ContainsTypeParameter(typeParameter); } private bool HasUnfixedParamInOutputType(BoundExpression argument, TypeSymbol formalParameterType) { for (int iParam = 0; iParam < _methodTypeParameters.Length; iParam++) { if (IsUnfixed(iParam)) { if (DoesOutputTypeContain(argument, formalParameterType, _methodTypeParameters[iParam])) { return true; } } } return false; } //////////////////////////////////////////////////////////////////////////////// // // Dependence // private bool DependsDirectlyOn(int iParam, int jParam) { Debug.Assert(ValidIndex(iParam)); Debug.Assert(ValidIndex(jParam)); // SPEC: An unfixed type parameter Xi depends directly on an unfixed type // SPEC: parameter Xj if for some argument Ek with type Tk, Xj occurs // SPEC: in an input type of Ek and Xi occurs in an output type of Ek // SPEC: with type Tk. // We compute and record the Depends Directly On relationship once, in // InitializeDependencies, below. // At this point, everything should be unfixed. Debug.Assert(IsUnfixed(iParam)); Debug.Assert(IsUnfixed(jParam)); for (int iArg = 0, length = this.NumberArgumentsToProcess; iArg < length; iArg++) { var formalParameterType = _formalParameterTypes[iArg].Type; var argument = _arguments[iArg]; if (DoesInputTypeContain(argument, formalParameterType, _methodTypeParameters[jParam]) && DoesOutputTypeContain(argument, formalParameterType, _methodTypeParameters[iParam])) { return true; } } return false; } private void InitializeDependencies() { // We track dependencies by a two-d square array that gives the known // relationship between every pair of type parameters. The relationship // is one of: // // * Unknown relationship // * known to be not dependent // * known to depend directly // * known to depend indirectly // // Since dependency is only defined on unfixed type parameters, fixing a type // parameter causes all dependencies involving that parameter to go to // the "known to be not dependent" state. Since dependency is a transitive property, // this means that doing so may require recalculating the indirect dependencies // from the now possibly smaller set of dependencies. // // Therefore, when we detect that the dependency state has possibly changed // due to fixing, we change all "depends indirectly" back into "unknown" and // recalculate from the remaining "depends directly". // // This algorithm thereby yields an extremely bad (but extremely unlikely) worst // case for asymptotic performance. Suppose there are n type parameters. // "DependsTransitivelyOn" below costs O(n) because it must potentially check // all n type parameters to see if there is any k such that Xj => Xk => Xi. // "DeduceDependencies" calls "DependsTransitivelyOn" for each "Unknown" // pair, and there could be O(n^2) such pairs, so DependsTransitivelyOn is // worst-case O(n^3). And we could have to recalculate the dependency graph // after each type parameter is fixed in turn, so that would be O(n) calls to // DependsTransitivelyOn, giving this algorithm a worst case of O(n^4). // // Of course, in reality, n is going to almost always be on the order of // "smaller than 5", and there will not be O(n^2) dependency relationships // between type parameters; it is far more likely that the transitivity chains // will be very short and not branch or loop at all. This is much more likely to // be an O(n^2) algorithm in practice. Debug.Assert(_dependencies == null); _dependencies = new Dependency[_methodTypeParameters.Length, _methodTypeParameters.Length]; int iParam; int jParam; Debug.Assert(0 == (int)Dependency.Unknown); for (iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (DependsDirectlyOn(iParam, jParam)) { _dependencies[iParam, jParam] = Dependency.Direct; } } } DeduceAllDependencies(); } private bool DependsOn(int iParam, int jParam) { Debug.Assert(_dependencies != null); // SPEC: Xj depends on Xi if Xj depends directly on Xi, or if Xi depends // SPEC: directly on Xk and Xk depends on Xj. Thus "depends on" is the // SPEC: transitive but not reflexive closure of "depends directly on". Debug.Assert(0 <= iParam && iParam < _methodTypeParameters.Length); Debug.Assert(0 <= jParam && jParam < _methodTypeParameters.Length); if (_dependenciesDirty) { SetIndirectsToUnknown(); DeduceAllDependencies(); } return 0 != ((_dependencies[iParam, jParam]) & Dependency.DependsMask); } private bool DependsTransitivelyOn(int iParam, int jParam) { Debug.Assert(_dependencies != null); Debug.Assert(ValidIndex(iParam)); Debug.Assert(ValidIndex(jParam)); // Can we find Xk such that Xi depends on Xk and Xk depends on Xj? // If so, then Xi depends indirectly on Xj. (Note that there is // a minor optimization here -- the spec comment above notes that // we want Xi to depend DIRECTLY on Xk, and Xk to depend directly // or indirectly on Xj. But if we already know that Xi depends // directly OR indirectly on Xk and Xk depends on Xj, then that's // good enough.) for (int kParam = 0; kParam < _methodTypeParameters.Length; ++kParam) { if (((_dependencies[iParam, kParam]) & Dependency.DependsMask) != 0 && ((_dependencies[kParam, jParam]) & Dependency.DependsMask) != 0) { return true; } } return false; } private void DeduceAllDependencies() { bool madeProgress; do { madeProgress = DeduceDependencies(); } while (madeProgress); SetUnknownsToNotDependent(); _dependenciesDirty = false; } private bool DeduceDependencies() { Debug.Assert(_dependencies != null); bool madeProgress = false; for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (_dependencies[iParam, jParam] == Dependency.Unknown) { if (DependsTransitivelyOn(iParam, jParam)) { _dependencies[iParam, jParam] = Dependency.Indirect; madeProgress = true; } } } } return madeProgress; } private void SetUnknownsToNotDependent() { Debug.Assert(_dependencies != null); for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (_dependencies[iParam, jParam] == Dependency.Unknown) { _dependencies[iParam, jParam] = Dependency.NotDependent; } } } } private void SetIndirectsToUnknown() { Debug.Assert(_dependencies != null); for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (_dependencies[iParam, jParam] == Dependency.Indirect) { _dependencies[iParam, jParam] = Dependency.Unknown; } } } } //////////////////////////////////////////////////////////////////////////////// // A fixed parameter never depends on anything, nor is depended upon by anything. private void UpdateDependenciesAfterFix(int iParam) { Debug.Assert(ValidIndex(iParam)); if (_dependencies == null) { return; } for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { _dependencies[iParam, jParam] = Dependency.NotDependent; _dependencies[jParam, iParam] = Dependency.NotDependent; } _dependenciesDirty = true; } private bool DependsOnAny(int iParam) { Debug.Assert(ValidIndex(iParam)); for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (DependsOn(iParam, jParam)) { return true; } } return false; } private bool AnyDependsOn(int iParam) { Debug.Assert(ValidIndex(iParam)); for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (DependsOn(jParam, iParam)) { return true; } } return false; } //////////////////////////////////////////////////////////////////////////////// // // Output type inferences // //////////////////////////////////////////////////////////////////////////////// private void OutputTypeInference(Binder binder, BoundExpression expression, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(expression != null); Debug.Assert(target.HasType); // SPEC: An output type inference is made from an expression E to a type T // SPEC: in the following way: // SPEC: * If E is an anonymous function with inferred return type U and // SPEC: T is a delegate type or expression tree with return type Tb // SPEC: then a lower bound inference is made from U to Tb. if (InferredReturnTypeInference(expression, target, ref useSiteInfo)) { return; } // SPEC: * Otherwise, if E is a method group and T is a delegate type or // SPEC: expression tree type with parameter types T1...Tk and return // SPEC: type Tb and overload resolution of E with the types T1...Tk // SPEC: yields a single method with return type U then a lower-bound // SPEC: inference is made from U to Tb. if (MethodGroupReturnTypeInference(binder, expression, target.Type, ref useSiteInfo)) { return; } // SPEC: * Otherwise, if E is an expression with type U then a lower-bound // SPEC: inference is made from U to T. var sourceType = _extensions.GetTypeWithAnnotations(expression); if (sourceType.HasType) { LowerBoundInference(sourceType, target, ref useSiteInfo); } // SPEC: * Otherwise, no inferences are made. } private bool InferredReturnTypeInference(BoundExpression source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert(target.HasType); // SPEC: * If E is an anonymous function with inferred return type U and // SPEC: T is a delegate type or expression tree with return type Tb // SPEC: then a lower bound inference is made from U to Tb. var delegateType = target.Type.GetDelegateType(); if ((object)delegateType == null) { return false; } // cannot be hit, because an invalid delegate does not have an unfixed return type // this will be checked earlier. Debug.Assert((object)delegateType.DelegateInvokeMethod != null && !delegateType.DelegateInvokeMethod.HasUseSiteError, "This method should only be called for valid delegate types."); var returnType = delegateType.DelegateInvokeMethod.ReturnTypeWithAnnotations; if (!returnType.HasType || returnType.SpecialType == SpecialType.System_Void) { return false; } var inferredReturnType = InferReturnType(source, delegateType, ref useSiteInfo); if (!inferredReturnType.HasType) { return false; } LowerBoundInference(inferredReturnType, returnType, ref useSiteInfo); return true; } private bool MethodGroupReturnTypeInference(Binder binder, BoundExpression source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert((object)target != null); // SPEC: * Otherwise, if E is a method group and T is a delegate type or // SPEC: expression tree type with parameter types T1...Tk and return // SPEC: type Tb and overload resolution of E with the types T1...Tk // SPEC: yields a single method with return type U then a lower-bound // SPEC: inference is made from U to Tb. if (source.Kind is not (BoundKind.MethodGroup or BoundKind.UnconvertedAddressOfOperator)) { return false; } var delegateOrFunctionPointerType = target.GetDelegateOrFunctionPointerType(); if ((object)delegateOrFunctionPointerType == null) { return false; } if (delegateOrFunctionPointerType.IsFunctionPointer() != (source.Kind == BoundKind.UnconvertedAddressOfOperator)) { return false; } // this part of the code is only called if the targetType has an unfixed type argument in the output // type, which is not the case for invalid delegate invoke methods. var (method, isFunctionPointerResolution) = delegateOrFunctionPointerType switch { NamedTypeSymbol n => (n.DelegateInvokeMethod, false), FunctionPointerTypeSymbol f => (f.Signature, true), _ => throw ExceptionUtilities.UnexpectedValue(delegateOrFunctionPointerType), }; Debug.Assert(method is { HasUseSiteError: false }, "This method should only be called for valid delegate or function pointer types"); TypeWithAnnotations sourceReturnType = method.ReturnTypeWithAnnotations; if (!sourceReturnType.HasType || sourceReturnType.SpecialType == SpecialType.System_Void) { return false; } // At this point we are in the second phase; we know that all the input types are fixed. var fixedParameters = GetFixedDelegateOrFunctionPointer(delegateOrFunctionPointerType).DelegateOrFunctionPointerParameters(); if (fixedParameters.IsDefault) { return false; } CallingConventionInfo callingConventionInfo = isFunctionPointerResolution ? new CallingConventionInfo(method.CallingConvention, ((FunctionPointerMethodSymbol)method).GetCallingConventionModifiers()) : default; BoundMethodGroup originalMethodGroup = source as BoundMethodGroup ?? ((BoundUnconvertedAddressOfOperator)source).Operand; var returnType = MethodGroupReturnType(binder, originalMethodGroup, fixedParameters, method.RefKind, isFunctionPointerResolution, ref useSiteInfo, in callingConventionInfo); if (returnType.IsDefault || returnType.IsVoidType()) { return false; } LowerBoundInference(returnType, sourceReturnType, ref useSiteInfo); return true; } private TypeWithAnnotations MethodGroupReturnType( Binder binder, BoundMethodGroup source, ImmutableArray<ParameterSymbol> delegateParameters, RefKind delegateRefKind, bool isFunctionPointerResolution, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, in CallingConventionInfo callingConventionInfo) { var analyzedArguments = AnalyzedArguments.GetInstance(); Conversions.GetDelegateOrFunctionPointerArguments(source.Syntax, analyzedArguments, delegateParameters, binder.Compilation); var resolution = binder.ResolveMethodGroup(source, analyzedArguments, useSiteInfo: ref useSiteInfo, isMethodGroupConversion: true, returnRefKind: delegateRefKind, // Since we are trying to infer the return type, it is not an input to resolving the method group returnType: null, isFunctionPointerResolution: isFunctionPointerResolution, callingConventionInfo: in callingConventionInfo); TypeWithAnnotations type = default; // The resolution could be empty (e.g. if there are no methods in the BoundMethodGroup). if (!resolution.IsEmpty) { var result = resolution.OverloadResolutionResult; if (result.Succeeded) { type = _extensions.GetMethodGroupResultType(source, result.BestResult.Member); } } analyzedArguments.Free(); resolution.Free(); return type; } //////////////////////////////////////////////////////////////////////////////// // // Explicit parameter type inferences // private void ExplicitParameterTypeInference(BoundExpression source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert(target.HasType); // SPEC: An explicit type parameter type inference is made from an expression // SPEC: E to a type T in the following way. // SPEC: If E is an explicitly typed anonymous function with parameter types // SPEC: U1...Uk and T is a delegate type or expression tree type with // SPEC: parameter types V1...Vk then for each Ui an exact inference is made // SPEC: from Ui to the corresponding Vi. if (source.Kind != BoundKind.UnboundLambda) { return; } UnboundLambda anonymousFunction = (UnboundLambda)source; if (!anonymousFunction.HasExplicitlyTypedParameterList) { return; } var delegateType = target.Type.GetDelegateType(); if ((object)delegateType == null) { return; } var delegateParameters = delegateType.DelegateParameters(); if (delegateParameters.IsDefault) { return; } int size = delegateParameters.Length; if (anonymousFunction.ParameterCount < size) { size = anonymousFunction.ParameterCount; } // SPEC ISSUE: What should we do if there is an out/ref mismatch between an // SPEC ISSUE: anonymous function parameter and a delegate parameter? // SPEC ISSUE: The result will not be applicable no matter what, but should // SPEC ISSUE: we make any inferences? This is going to be an error // SPEC ISSUE: ultimately, but it might make a difference for intellisense or // SPEC ISSUE: other analysis. for (int i = 0; i < size; ++i) { ExactInference(anonymousFunction.ParameterTypeWithAnnotations(i), delegateParameters[i].TypeWithAnnotations, ref useSiteInfo); } } //////////////////////////////////////////////////////////////////////////////// // // Exact inferences // private void ExactInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: An exact inference from a type U to a type V is made as follows: // SPEC: * Otherwise, if U is the type U1? and V is the type V1? then an // SPEC: exact inference is made from U to V. if (ExactNullableInference(source, target, ref useSiteInfo)) { return; } // SPEC: * If V is one of the unfixed Xi then U is added to the set of // SPEC: exact bounds for Xi. if (ExactTypeParameterInference(source, target)) { return; } // SPEC: * Otherwise, if U is an array type UE[...] and V is an array type VE[...] // SPEC: of the same rank then an exact inference from UE to VE is made. if (ExactArrayInference(source, target, ref useSiteInfo)) { return; } // SPEC: * Otherwise, if V is a constructed type C<V1...Vk> and U is a constructed // SPEC: type C<U1...Uk> then an exact inference is made // SPEC: from each Ui to the corresponding Vi. if (ExactConstructedInference(source, target, ref useSiteInfo)) { return; } // This can be valid via (where T : unmanaged) constraints if (ExactPointerInference(source, target, ref useSiteInfo)) { return; } // SPEC: * Otherwise no inferences are made. } private bool ExactTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * If V is one of the unfixed Xi then U is added to the set of bounds // SPEC: for Xi. if (IsUnfixedTypeParameter(target)) { AddBound(source, _exactBounds, target); return true; } return false; } private bool ExactArrayInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * Otherwise, if U is an array type UE[...] and V is an array type VE[...] // SPEC: of the same rank then an exact inference from UE to VE is made. if (!source.Type.IsArray() || !target.Type.IsArray()) { return false; } var arraySource = (ArrayTypeSymbol)source.Type; var arrayTarget = (ArrayTypeSymbol)target.Type; if (!arraySource.HasSameShapeAs(arrayTarget)) { return false; } ExactInference(arraySource.ElementTypeWithAnnotations, arrayTarget.ElementTypeWithAnnotations, ref useSiteInfo); return true; } private enum ExactOrBoundsKind { Exact, LowerBound, UpperBound, } private void ExactOrBoundsInference(ExactOrBoundsKind kind, TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (kind) { case ExactOrBoundsKind.Exact: ExactInference(source, target, ref useSiteInfo); break; case ExactOrBoundsKind.LowerBound: LowerBoundInference(source, target, ref useSiteInfo); break; case ExactOrBoundsKind.UpperBound: UpperBoundInference(source, target, ref useSiteInfo); break; } } private bool ExactOrBoundsNullableInference(ExactOrBoundsKind kind, TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); if (source.IsNullableType() && target.IsNullableType()) { ExactOrBoundsInference(kind, ((NamedTypeSymbol)source.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0], ((NamedTypeSymbol)target.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0], ref useSiteInfo); return true; } if (isNullableOnly(source) && isNullableOnly(target)) { ExactOrBoundsInference(kind, source.AsNotNullableReferenceType(), target.AsNotNullableReferenceType(), ref useSiteInfo); return true; } return false; // True if the type is nullable. static bool isNullableOnly(TypeWithAnnotations type) => type.NullableAnnotation.IsAnnotated(); } private bool ExactNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ExactOrBoundsNullableInference(ExactOrBoundsKind.Exact, source, target, ref useSiteInfo); } private bool LowerBoundTupleInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // NOTE: we are losing tuple element names when unwrapping tuple types to underlying types. // that is ok, because we are inferring type parameters used in the matching elements, // This is not the situation where entire tuple type used to infer a single type param ImmutableArray<TypeWithAnnotations> sourceTypes; ImmutableArray<TypeWithAnnotations> targetTypes; if (!source.Type.TryGetElementTypesWithAnnotationsIfTupleType(out sourceTypes) || !target.Type.TryGetElementTypesWithAnnotationsIfTupleType(out targetTypes) || sourceTypes.Length != targetTypes.Length) { return false; } for (int i = 0; i < sourceTypes.Length; i++) { LowerBoundInference(sourceTypes[i], targetTypes[i], ref useSiteInfo); } return true; } private bool ExactConstructedInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * Otherwise, if V is a constructed type C<V1...Vk> and U is a constructed // SPEC: type C<U1...Uk> then an exact inference // SPEC: is made from each Ui to the corresponding Vi. var namedSource = source.Type as NamedTypeSymbol; if ((object)namedSource == null) { return false; } var namedTarget = target.Type as NamedTypeSymbol; if ((object)namedTarget == null) { return false; } if (!TypeSymbol.Equals(namedSource.OriginalDefinition, namedTarget.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { return false; } ExactTypeArgumentInference(namedSource, namedTarget, ref useSiteInfo); return true; } private bool ExactPointerInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (source.TypeKind == TypeKind.Pointer && target.TypeKind == TypeKind.Pointer) { ExactInference(((PointerTypeSymbol)source.Type).PointedAtTypeWithAnnotations, ((PointerTypeSymbol)target.Type).PointedAtTypeWithAnnotations, ref useSiteInfo); return true; } else if (source.Type is FunctionPointerTypeSymbol { Signature: { ParameterCount: int sourceParameterCount } sourceSignature } && target.Type is FunctionPointerTypeSymbol { Signature: { ParameterCount: int targetParameterCount } targetSignature } && sourceParameterCount == targetParameterCount) { if (!FunctionPointerRefKindsEqual(sourceSignature, targetSignature) || !FunctionPointerCallingConventionsEqual(sourceSignature, targetSignature)) { return false; } for (int i = 0; i < sourceParameterCount; i++) { ExactInference(sourceSignature.ParameterTypesWithAnnotations[i], targetSignature.ParameterTypesWithAnnotations[i], ref useSiteInfo); } ExactInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); return true; } return false; } private static bool FunctionPointerCallingConventionsEqual(FunctionPointerMethodSymbol sourceSignature, FunctionPointerMethodSymbol targetSignature) { if (sourceSignature.CallingConvention != targetSignature.CallingConvention) { return false; } return (sourceSignature.GetCallingConventionModifiers(), targetSignature.GetCallingConventionModifiers()) switch { (null, null) => true, ({ } sourceModifiers, { } targetModifiers) when sourceModifiers.SetEquals(targetModifiers) => true, _ => false }; } private static bool FunctionPointerRefKindsEqual(FunctionPointerMethodSymbol sourceSignature, FunctionPointerMethodSymbol targetSignature) { return sourceSignature.RefKind == targetSignature.RefKind && (sourceSignature.ParameterRefKinds.IsDefault, targetSignature.ParameterRefKinds.IsDefault) switch { (true, false) or (false, true) => false, (true, true) => true, _ => sourceSignature.ParameterRefKinds.SequenceEqual(targetSignature.ParameterRefKinds) }; } private void ExactTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var targetTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); target.GetAllTypeArguments(targetTypeArguments, ref useSiteInfo); Debug.Assert(sourceTypeArguments.Count == targetTypeArguments.Count); for (int arg = 0; arg < sourceTypeArguments.Count; ++arg) { ExactInference(sourceTypeArguments[arg], targetTypeArguments[arg], ref useSiteInfo); } sourceTypeArguments.Free(); targetTypeArguments.Free(); } //////////////////////////////////////////////////////////////////////////////// // // Lower-bound inferences // private void LowerBoundInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: A lower-bound inference from a type U to a type V is made as follows: // SPEC: * Otherwise, if V is nullable type V1? and U is nullable type U1? // SPEC: then an exact inference is made from U1 to V1. // SPEC ERROR: The spec should say "lower" here; we can safely make a lower-bound // SPEC ERROR: inference to nullable even though it is a generic struct. That is, // SPEC ERROR: if we have M<T>(T?, T) called with (char?, int) then we can infer // SPEC ERROR: lower bounds of char and int, and choose int. If we make an exact // SPEC ERROR: inference of char then type inference fails. if (LowerBoundNullableInference(source, target, ref useSiteInfo)) { return; } // SPEC: * If V is one of the unfixed Xi then U is added to the set of // SPEC: lower bounds for Xi. if (LowerBoundTypeParameterInference(source, target)) { return; } // SPEC: * Otherwise, if U is an array type Ue[...] and V is either an array // SPEC: type Ve[...] of the same rank, or if U is a one-dimensional array // SPEC: type Ue[] and V is one of IEnumerable<Ve>, ICollection<Ve> or // SPEC: IList<Ve> then // SPEC: * if Ue is known to be a reference type then a lower-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (LowerBoundArrayInference(source.Type, target.Type, ref useSiteInfo)) { return; } // UNDONE: At this point we could also do an inference from non-nullable U // UNDONE: to nullable V. // UNDONE: // UNDONE: We tried implementing lower bound nullable inference as follows: // UNDONE: // UNDONE: * Otherwise, if V is nullable type V1? and U is a non-nullable // UNDONE: struct type then an exact inference is made from U to V1. // UNDONE: // UNDONE: However, this causes an unfortunate interaction with what // UNDONE: looks like a bug in our implementation of section 15.2 of // UNDONE: the specification. Namely, it appears that the code which // UNDONE: checks whether a given method is compatible with // UNDONE: a delegate type assumes that if method type inference succeeds, // UNDONE: then the inferred types are compatible with the delegate types. // UNDONE: This is not necessarily so; the inferred types could be compatible // UNDONE: via a conversion other than reference or identity. // UNDONE: // UNDONE: We should take an action item to investigate this problem. // UNDONE: Until then, we will turn off the proposed lower bound nullable // UNDONE: inference. // if (LowerBoundNullableInference(pSource, pDest)) // { // return; // } if (LowerBoundTupleInference(source, target, ref useSiteInfo)) { return; } // SPEC: Otherwise... many cases for constructed generic types. if (LowerBoundConstructedInference(source.Type, target.Type, ref useSiteInfo)) { return; } if (LowerBoundFunctionPointerTypeInference(source.Type, target.Type, ref useSiteInfo)) { return; } // SPEC: * Otherwise, no inferences are made. } private bool LowerBoundTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * If V is one of the unfixed Xi then U is added to the set of bounds // SPEC: for Xi. if (IsUnfixedTypeParameter(target)) { AddBound(source, _lowerBounds, target); return true; } return false; } private static TypeWithAnnotations GetMatchingElementType(ArrayTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); // It might be an array of same rank. if (target.IsArray()) { var arrayTarget = (ArrayTypeSymbol)target; if (!arrayTarget.HasSameShapeAs(source)) { return default; } return arrayTarget.ElementTypeWithAnnotations; } // Or it might be IEnum<T> and source is rank one. if (!source.IsSZArray) { return default; } // Arrays are specified as being convertible to IEnumerable<T>, ICollection<T> and // IList<T>; we also honor their convertibility to IReadOnlyCollection<T> and // IReadOnlyList<T>, and make inferences accordingly. if (!target.IsPossibleArrayGenericInterface()) { return default; } return ((NamedTypeSymbol)target).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo); } private bool LowerBoundArrayInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); // SPEC: * Otherwise, if U is an array type Ue[...] and V is either an array // SPEC: type Ve[...] of the same rank, or if U is a one-dimensional array // SPEC: type Ue[] and V is one of IEnumerable<Ve>, ICollection<Ve> or // SPEC: IList<Ve> then // SPEC: * if Ue is known to be a reference type then a lower-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (!source.IsArray()) { return false; } var arraySource = (ArrayTypeSymbol)source; var elementSource = arraySource.ElementTypeWithAnnotations; var elementTarget = GetMatchingElementType(arraySource, target, ref useSiteInfo); if (!elementTarget.HasType) { return false; } if (elementSource.Type.IsReferenceType) { LowerBoundInference(elementSource, elementTarget, ref useSiteInfo); } else { ExactInference(elementSource, elementTarget, ref useSiteInfo); } return true; } private bool LowerBoundNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ExactOrBoundsNullableInference(ExactOrBoundsKind.LowerBound, source, target, ref useSiteInfo); } private bool LowerBoundConstructedInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); var constructedTarget = target as NamedTypeSymbol; if ((object)constructedTarget == null) { return false; } if (constructedTarget.AllTypeArgumentCount() == 0) { return false; } // SPEC: * Otherwise, if V is a constructed class or struct type C<V1...Vk> // SPEC: and U is C<U1...Uk> then an exact inference // SPEC: is made from each Ui to the corresponding Vi. // SPEC: * Otherwise, if V is a constructed interface or delegate type C<V1...Vk> // SPEC: and U is C<U1...Uk> then an exact inference, // SPEC: lower bound inference or upper bound inference // SPEC: is made from each Ui to the corresponding Vi. var constructedSource = source as NamedTypeSymbol; if ((object)constructedSource != null && TypeSymbol.Equals(constructedSource.OriginalDefinition, constructedTarget.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { if (constructedSource.IsInterface || constructedSource.IsDelegateType()) { LowerBoundTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } else { ExactTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } return true; } // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a class type which // SPEC: inherits directly or indirectly from C<U1...Uk> then an exact ... // SPEC: * ... and U is a type parameter with effective base class ... // SPEC: * ... and U is a type parameter with an effective base class which inherits ... if (LowerBoundClassInference(source, constructedTarget, ref useSiteInfo)) { return true; } // SPEC: * Otherwise, if V is an interface type C<V1...Vk> and U is a class type // SPEC: or struct type and there is a unique set U1...Uk such that U directly // SPEC: or indirectly implements C<U1...Uk> then an exact ... // SPEC: * ... and U is an interface type ... // SPEC: * ... and U is a type parameter ... if (LowerBoundInterfaceInference(source, constructedTarget, ref useSiteInfo)) { return true; } return false; } private bool LowerBoundClassInference(TypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (target.TypeKind != TypeKind.Class) { return false; } // Spec: 7.5.2.9 Lower-bound interfaces // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a class type which // SPEC: inherits directly or indirectly from C<U1...Uk> // SPEC: then an exact inference is made from each Ui to the corresponding Vi. // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a type parameter // SPEC: with effective base class C<U1...Uk> // SPEC: then an exact inference is made from each Ui to the corresponding Vi. // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a type parameter // SPEC: with an effective base class which inherits directly or indirectly from // SPEC: C<U1...Uk> then an exact inference is made // SPEC: from each Ui to the corresponding Vi. NamedTypeSymbol sourceBase = null; if (source.TypeKind == TypeKind.Class) { sourceBase = source.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } else if (source.TypeKind == TypeKind.TypeParameter) { sourceBase = ((TypeParameterSymbol)source).EffectiveBaseClass(ref useSiteInfo); } while ((object)sourceBase != null) { if (TypeSymbol.Equals(sourceBase.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { ExactTypeArgumentInference(sourceBase, target, ref useSiteInfo); return true; } sourceBase = sourceBase.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } return false; } private bool LowerBoundInterfaceInference(TypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (!target.IsInterface) { return false; } // Spec 7.5.2.9 Lower-bound interfaces // SPEC: * Otherwise, if V [target] is an interface type C<V1...Vk> and U [source] is a class type // SPEC: or struct type and there is a unique set U1...Uk such that U directly // SPEC: or indirectly implements C<U1...Uk> then an // SPEC: exact, upper-bound, or lower-bound inference ... // SPEC: * ... and U is an interface type ... // SPEC: * ... and U is a type parameter ... ImmutableArray<NamedTypeSymbol> allInterfaces; switch (source.TypeKind) { case TypeKind.Struct: case TypeKind.Class: case TypeKind.Interface: allInterfaces = source.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); break; case TypeKind.TypeParameter: var typeParameter = (TypeParameterSymbol)source; allInterfaces = typeParameter.EffectiveBaseClass(ref useSiteInfo). AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo). Concat(typeParameter.AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)); break; default: return false; } // duplicates with only nullability differences can be merged (to avoid an error in type inference) allInterfaces = ModuloReferenceTypeNullabilityDifferences(allInterfaces, VarianceKind.In); NamedTypeSymbol matchingInterface = GetInterfaceInferenceBound(allInterfaces, target); if ((object)matchingInterface == null) { return false; } LowerBoundTypeArgumentInference(matchingInterface, target, ref useSiteInfo); return true; } internal static ImmutableArray<NamedTypeSymbol> ModuloReferenceTypeNullabilityDifferences(ImmutableArray<NamedTypeSymbol> interfaces, VarianceKind variance) { var dictionary = PooledDictionaryIgnoringNullableModifiersForReferenceTypes.GetInstance(); foreach (var @interface in interfaces) { if (dictionary.TryGetValue(@interface, out var found)) { var merged = (NamedTypeSymbol)found.MergeEquivalentTypes(@interface, variance); dictionary[@interface] = merged; } else { dictionary.Add(@interface, @interface); } } var result = dictionary.Count != interfaces.Length ? dictionary.Values.ToImmutableArray() : interfaces; dictionary.Free(); return result; } private void LowerBoundTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The choice of inference for the i-th type argument is made // SPEC: based on the declaration of the i-th type parameter of C, as // SPEC: follows: // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as covariant then a lower bound inference is made. // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as contravariant then an upper bound inference is made. // SPEC: * otherwise, an exact inference is made. Debug.Assert((object)source != null); Debug.Assert((object)target != null); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)); var typeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var targetTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); source.OriginalDefinition.GetAllTypeParameters(typeParameters); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); target.GetAllTypeArguments(targetTypeArguments, ref useSiteInfo); Debug.Assert(typeParameters.Count == sourceTypeArguments.Count); Debug.Assert(typeParameters.Count == targetTypeArguments.Count); for (int arg = 0; arg < sourceTypeArguments.Count; ++arg) { var typeParameter = typeParameters[arg]; var sourceTypeArgument = sourceTypeArguments[arg]; var targetTypeArgument = targetTypeArguments[arg]; if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.Out) { LowerBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.In) { UpperBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else { ExactInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } } typeParameters.Free(); sourceTypeArguments.Free(); targetTypeArguments.Free(); } #nullable enable private bool LowerBoundFunctionPointerTypeInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (source is not FunctionPointerTypeSymbol { Signature: { } sourceSignature } || target is not FunctionPointerTypeSymbol { Signature: { } targetSignature }) { return false; } if (sourceSignature.ParameterCount != targetSignature.ParameterCount) { return false; } if (!FunctionPointerRefKindsEqual(sourceSignature, targetSignature) || !FunctionPointerCallingConventionsEqual(sourceSignature, targetSignature)) { return false; } // Reference parameters are treated as "input" variance by default, and reference return types are treated as out variance by default. // If they have a ref kind or are not reference types, then they are treated as invariant. for (int i = 0; i < sourceSignature.ParameterCount; i++) { var sourceParam = sourceSignature.Parameters[i]; var targetParam = targetSignature.Parameters[i]; if ((sourceParam.Type.IsReferenceType || sourceParam.Type.IsFunctionPointer()) && sourceParam.RefKind == RefKind.None) { UpperBoundInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } } if ((sourceSignature.ReturnType.IsReferenceType || sourceSignature.ReturnType.IsFunctionPointer()) && sourceSignature.RefKind == RefKind.None) { LowerBoundInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } return true; } #nullable disable //////////////////////////////////////////////////////////////////////////////// // // Upper-bound inferences // private void UpperBoundInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: An upper-bound inference from a type U to a type V is made as follows: // SPEC: * Otherwise, if V is nullable type V1? and U is nullable type U1? // SPEC: then an exact inference is made from U1 to V1. if (UpperBoundNullableInference(source, target, ref useSiteInfo)) { return; } // SPEC: * If V is one of the unfixed Xi then U is added to the set of // SPEC: upper bounds for Xi. if (UpperBoundTypeParameterInference(source, target)) { return; } // SPEC: * Otherwise, if V is an array type Ve[...] and U is an array // SPEC: type Ue[...] of the same rank, or if V is a one-dimensional array // SPEC: type Ve[] and U is one of IEnumerable<Ue>, ICollection<Ue> or // SPEC: IList<Ue> then // SPEC: * if Ue is known to be a reference type then an upper-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (UpperBoundArrayInference(source, target, ref useSiteInfo)) { return; } Debug.Assert(source.Type.IsReferenceType || source.Type.IsFunctionPointer()); // NOTE: spec would ask us to do the following checks, but since the value types // are trivially handled as exact inference in the callers, we do not have to. //if (ExactTupleInference(source, target, ref useSiteInfo)) //{ // return; //} // SPEC: * Otherwise... cases for constructed types if (UpperBoundConstructedInference(source, target, ref useSiteInfo)) { return; } if (UpperBoundFunctionPointerTypeInference(source.Type, target.Type, ref useSiteInfo)) { return; } // SPEC: * Otherwise, no inferences are made. } private bool UpperBoundTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * If V is one of the unfixed Xi then U is added to the set of upper bounds // SPEC: for Xi. if (IsUnfixedTypeParameter(target)) { AddBound(source, _upperBounds, target); return true; } return false; } private bool UpperBoundArrayInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * Otherwise, if V is an array type Ve[...] and U is an array // SPEC: type Ue[...] of the same rank, or if V is a one-dimensional array // SPEC: type Ve[] and U is one of IEnumerable<Ue>, ICollection<Ue> or // SPEC: IList<Ue> then // SPEC: * if Ue is known to be a reference type then an upper-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (!target.Type.IsArray()) { return false; } var arrayTarget = (ArrayTypeSymbol)target.Type; var elementTarget = arrayTarget.ElementTypeWithAnnotations; var elementSource = GetMatchingElementType(arrayTarget, source.Type, ref useSiteInfo); if (!elementSource.HasType) { return false; } if (elementSource.Type.IsReferenceType) { UpperBoundInference(elementSource, elementTarget, ref useSiteInfo); } else { ExactInference(elementSource, elementTarget, ref useSiteInfo); } return true; } private bool UpperBoundNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ExactOrBoundsNullableInference(ExactOrBoundsKind.UpperBound, source, target, ref useSiteInfo); } private bool UpperBoundConstructedInference(TypeWithAnnotations sourceWithAnnotations, TypeWithAnnotations targetWithAnnotations, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceWithAnnotations.HasType); Debug.Assert(targetWithAnnotations.HasType); var source = sourceWithAnnotations.Type; var target = targetWithAnnotations.Type; var constructedSource = source as NamedTypeSymbol; if ((object)constructedSource == null) { return false; } if (constructedSource.AllTypeArgumentCount() == 0) { return false; } // SPEC: * Otherwise, if V is a constructed type C<V1...Vk> and U is // SPEC: C<U1...Uk> then an exact inference, // SPEC: lower bound inference or upper bound inference // SPEC: is made from each Ui to the corresponding Vi. var constructedTarget = target as NamedTypeSymbol; if ((object)constructedTarget != null && TypeSymbol.Equals(constructedSource.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { if (constructedTarget.IsInterface || constructedTarget.IsDelegateType()) { UpperBoundTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } else { ExactTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } return true; } // SPEC: * Otherwise, if U is a class type C<U1...Uk> and V is a class type which // SPEC: inherits directly or indirectly from C<V1...Vk> then an exact ... if (UpperBoundClassInference(constructedSource, target, ref useSiteInfo)) { return true; } // SPEC: * Otherwise, if U is an interface type C<U1...Uk> and V is a class type // SPEC: or struct type and there is a unique set V1...Vk such that V directly // SPEC: or indirectly implements C<V1...Vk> then an exact ... // SPEC: * ... and U is an interface type ... if (UpperBoundInterfaceInference(constructedSource, target, ref useSiteInfo)) { return true; } return false; } private bool UpperBoundClassInference(NamedTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (source.TypeKind != TypeKind.Class || target.TypeKind != TypeKind.Class) { return false; } // SPEC: * Otherwise, if U is a class type C<U1...Uk> and V is a class type which // SPEC: inherits directly or indirectly from C<V1...Vk> then an exact // SPEC: inference is made from each Ui to the corresponding Vi. var targetBase = target.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); while ((object)targetBase != null) { if (TypeSymbol.Equals(targetBase.OriginalDefinition, source.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { ExactTypeArgumentInference(source, targetBase, ref useSiteInfo); return true; } targetBase = targetBase.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } return false; } private bool UpperBoundInterfaceInference(NamedTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (!source.IsInterface) { return false; } // SPEC: * Otherwise, if U [source] is an interface type C<U1...Uk> and V [target] is a class type // SPEC: or struct type and there is a unique set V1...Vk such that V directly // SPEC: or indirectly implements C<V1...Vk> then an exact ... // SPEC: * ... and U is an interface type ... switch (target.TypeKind) { case TypeKind.Struct: case TypeKind.Class: case TypeKind.Interface: break; default: return false; } ImmutableArray<NamedTypeSymbol> allInterfaces = target.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); // duplicates with only nullability differences can be merged (to avoid an error in type inference) allInterfaces = ModuloReferenceTypeNullabilityDifferences(allInterfaces, VarianceKind.Out); NamedTypeSymbol bestInterface = GetInterfaceInferenceBound(allInterfaces, source); if ((object)bestInterface == null) { return false; } UpperBoundTypeArgumentInference(source, bestInterface, ref useSiteInfo); return true; } private void UpperBoundTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The choice of inference for the i-th type argument is made // SPEC: based on the declaration of the i-th type parameter of C, as // SPEC: follows: // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as covariant then an upper-bound inference is made. // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as contravariant then a lower-bound inference is made. // SPEC: * otherwise, an exact inference is made. Debug.Assert((object)source != null); Debug.Assert((object)target != null); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)); var typeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var targetTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); source.OriginalDefinition.GetAllTypeParameters(typeParameters); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); target.GetAllTypeArguments(targetTypeArguments, ref useSiteInfo); Debug.Assert(typeParameters.Count == sourceTypeArguments.Count); Debug.Assert(typeParameters.Count == targetTypeArguments.Count); for (int arg = 0; arg < sourceTypeArguments.Count; ++arg) { var typeParameter = typeParameters[arg]; var sourceTypeArgument = sourceTypeArguments[arg]; var targetTypeArgument = targetTypeArguments[arg]; if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.Out) { UpperBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.In) { LowerBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else { ExactInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } } typeParameters.Free(); sourceTypeArguments.Free(); targetTypeArguments.Free(); } #nullable enable private bool UpperBoundFunctionPointerTypeInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (source is not FunctionPointerTypeSymbol { Signature: { } sourceSignature } || target is not FunctionPointerTypeSymbol { Signature: { } targetSignature }) { return false; } if (sourceSignature.ParameterCount != targetSignature.ParameterCount) { return false; } if (!FunctionPointerRefKindsEqual(sourceSignature, targetSignature) || !FunctionPointerCallingConventionsEqual(sourceSignature, targetSignature)) { return false; } // Reference parameters are treated as "input" variance by default, and reference return types are treated as out variance by default. // If they have a ref kind or are not reference types, then they are treated as invariant. for (int i = 0; i < sourceSignature.ParameterCount; i++) { var sourceParam = sourceSignature.Parameters[i]; var targetParam = targetSignature.Parameters[i]; if ((sourceParam.Type.IsReferenceType || sourceParam.Type.IsFunctionPointer()) && sourceParam.RefKind == RefKind.None) { LowerBoundInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } } if ((sourceSignature.ReturnType.IsReferenceType || sourceSignature.ReturnType.IsFunctionPointer()) && sourceSignature.RefKind == RefKind.None) { UpperBoundInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } return true; } #nullable disable //////////////////////////////////////////////////////////////////////////////// // // Fixing // private bool Fix(int iParam, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(IsUnfixed(iParam)); var exact = _exactBounds[iParam]; var lower = _lowerBounds[iParam]; var upper = _upperBounds[iParam]; var best = Fix(exact, lower, upper, ref useSiteInfo, _conversions); if (!best.HasType) { return false; } #if DEBUG if (_conversions.IncludeNullability) { // If the first attempt succeeded, the result should be the same as // the second attempt, although perhaps with different nullability. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var withoutNullability = Fix(exact, lower, upper, ref discardedUseSiteInfo, _conversions.WithNullability(false)); // https://github.com/dotnet/roslyn/issues/27961 Results may differ by tuple names or dynamic. // See NullableReferenceTypesTests.TypeInference_TupleNameDifferences_01 for example. Debug.Assert(best.Type.Equals(withoutNullability.Type, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); } #endif _fixedResults[iParam] = best; UpdateDependenciesAfterFix(iParam); return true; } private static TypeWithAnnotations Fix( HashSet<TypeWithAnnotations> exact, HashSet<TypeWithAnnotations> lower, HashSet<TypeWithAnnotations> upper, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConversionsBase conversions) { // UNDONE: This method makes a lot of garbage. // SPEC: An unfixed type parameter with a set of bounds is fixed as follows: // SPEC: * The set of candidate types starts out as the set of all types in // SPEC: the bounds. // SPEC: * We then examine each bound in turn. For each exact bound U of Xi, // SPEC: all types which are not identical to U are removed from the candidate set. // Optimization: if we have two or more exact bounds, fixing is impossible. var candidates = new Dictionary<TypeWithAnnotations, TypeWithAnnotations>(EqualsIgnoringDynamicTupleNamesAndNullabilityComparer.Instance); // Optimization: if we have one exact bound then we need not add any // inexact bounds; we're just going to remove them anyway. if (exact == null) { if (lower != null) { // Lower bounds represent co-variance. AddAllCandidates(candidates, lower, VarianceKind.Out, conversions); } if (upper != null) { // Lower bounds represent contra-variance. AddAllCandidates(candidates, upper, VarianceKind.In, conversions); } } else { // Exact bounds represent invariance. AddAllCandidates(candidates, exact, VarianceKind.None, conversions); if (candidates.Count >= 2) { return default; } } if (candidates.Count == 0) { return default; } // Don't mutate the collection as we're iterating it. var initialCandidates = ArrayBuilder<TypeWithAnnotations>.GetInstance(); GetAllCandidates(candidates, initialCandidates); // SPEC: For each lower bound U of Xi all types to which there is not an // SPEC: implicit conversion from U are removed from the candidate set. if (lower != null) { MergeOrRemoveCandidates(candidates, lower, initialCandidates, conversions, VarianceKind.Out, ref useSiteInfo); } // SPEC: For each upper bound U of Xi all types from which there is not an // SPEC: implicit conversion to U are removed from the candidate set. if (upper != null) { MergeOrRemoveCandidates(candidates, upper, initialCandidates, conversions, VarianceKind.In, ref useSiteInfo); } initialCandidates.Clear(); GetAllCandidates(candidates, initialCandidates); // SPEC: * If among the remaining candidate types there is a unique type V to // SPEC: which there is an implicit conversion from all the other candidate // SPEC: types, then the parameter is fixed to V. TypeWithAnnotations best = default; foreach (var candidate in initialCandidates) { foreach (var candidate2 in initialCandidates) { if (!candidate.Equals(candidate2, TypeCompareKind.ConsiderEverything) && !ImplicitConversionExists(candidate2, candidate, ref useSiteInfo, conversions.WithNullability(false))) { goto OuterBreak; } } if (!best.HasType) { best = candidate; } else { Debug.Assert(!best.Equals(candidate, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); // best candidate is not unique best = default; break; } OuterBreak: ; } initialCandidates.Free(); return best; } private static bool ImplicitConversionExists(TypeWithAnnotations sourceWithAnnotations, TypeWithAnnotations destinationWithAnnotations, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConversionsBase conversions) { var source = sourceWithAnnotations.Type; var destination = destinationWithAnnotations.Type; // SPEC VIOLATION: For the purpose of algorithm in Fix method, dynamic type is not considered convertible to any other type, including object. if (source.IsDynamic() && !destination.IsDynamic()) { return false; } if (!conversions.HasTopLevelNullabilityImplicitConversion(sourceWithAnnotations, destinationWithAnnotations)) { return false; } return conversions.ClassifyImplicitConversionFromType(source, destination, ref useSiteInfo).Exists; } //////////////////////////////////////////////////////////////////////////////// // // Inferred return type // private TypeWithAnnotations InferReturnType(BoundExpression source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)target != null); Debug.Assert(target.IsDelegateType()); Debug.Assert((object)target.DelegateInvokeMethod != null && !target.DelegateInvokeMethod.HasUseSiteError, "This method should only be called for legal delegate types."); Debug.Assert(!target.DelegateInvokeMethod.ReturnsVoid); // We should not be computing the inferred return type unless we are converting // to a delegate type where all the input types are fixed. Debug.Assert(!HasUnfixedParamInInputType(source, target)); // Spec 7.5.2.12: Inferred return type: // The inferred return type of an anonymous function F is used during // type inference and overload resolution. The inferred return type // can only be determined for an anonymous function where all parameter // types are known, either because they are explicitly given, provided // through an anonymous function conversion, or inferred during type // inference on an enclosing generic method invocation. // The inferred return type is determined as follows: // * If the body of F is an expression (that has a type) then the // inferred return type of F is the type of that expression. // * If the body of F is a block and the set of expressions in the // blocks return statements has a best common type T then the // inferred return type of F is T. // * Otherwise, a return type cannot be inferred for F. if (source.Kind != BoundKind.UnboundLambda) { return default; } var anonymousFunction = (UnboundLambda)source; if (anonymousFunction.HasSignature) { // Optimization: // We know that the anonymous function has a parameter list. If it does not // have the same arity as the delegate, then it cannot possibly be applicable. // Rather than have type inference fail, we will simply not make a return // type inference and have type inference continue on. Either inference // will fail, or we will infer a nonapplicable method. Either way, there // is no change to the semantics of overload resolution. var originalDelegateParameters = target.DelegateParameters(); if (originalDelegateParameters.IsDefault) { return default; } if (originalDelegateParameters.Length != anonymousFunction.ParameterCount) { return default; } } var fixedDelegate = (NamedTypeSymbol)GetFixedDelegateOrFunctionPointer(target); var fixedDelegateParameters = fixedDelegate.DelegateParameters(); // Optimization: // Similarly, if we have an entirely fixed delegate and an explicitly typed // anonymous function, then the parameter types had better be identical. // If not, applicability will eventually fail, so there is no semantic // difference caused by failing to make a return type inference. if (anonymousFunction.HasExplicitlyTypedParameterList) { for (int p = 0; p < anonymousFunction.ParameterCount; ++p) { if (!anonymousFunction.ParameterType(p).Equals(fixedDelegateParameters[p].Type, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { return default; } } } // Future optimization: We could return default if the delegate has out or ref parameters // and the anonymous function is an implicitly typed lambda. It will not be applicable. // We have an entirely fixed delegate parameter list, which is of the same arity as // the anonymous function parameter list, and possibly exactly the same types if // the anonymous function is explicitly typed. Make an inference from the // delegate parameters to the return type. return anonymousFunction.InferReturnType(_conversions, fixedDelegate, ref useSiteInfo); } /// <summary> /// Return the interface with an original definition matches /// the original definition of the target. If the are no matches, /// or multiple matches, the return value is null. /// </summary> private static NamedTypeSymbol GetInterfaceInferenceBound(ImmutableArray<NamedTypeSymbol> interfaces, NamedTypeSymbol target) { Debug.Assert(target.IsInterface); NamedTypeSymbol matchingInterface = null; foreach (var currentInterface in interfaces) { if (TypeSymbol.Equals(currentInterface.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything)) { if ((object)matchingInterface == null) { matchingInterface = currentInterface; } else if (!TypeSymbol.Equals(matchingInterface, currentInterface, TypeCompareKind.ConsiderEverything)) { // Not unique. Bail out. return null; } } } return matchingInterface; } //////////////////////////////////////////////////////////////////////////////// // // Helper methods // //////////////////////////////////////////////////////////////////////////////// // // In error recovery and reporting scenarios we sometimes end up in a situation // like this: // // x.Goo( y=> // // and the question is, "is Goo a valid extension method of x?" If Goo is // generic, then Goo will be something like: // // static Blah Goo<T>(this Bar<T> bar, Func<T, T> f){ ... } // // What we would like to know is: given _only_ the expression x, can we infer // what T is in Bar<T> ? If we can, then for error recovery and reporting // we can provisionally consider Goo to be an extension method of x. If we // cannot deduce this just from x then we should consider Goo to not be an // extension method of x, at least until we have more information. // // Clearly it is pointless to run multiple phases public static ImmutableArray<TypeWithAnnotations> InferTypeArgumentsFromFirstArgument( ConversionsBase conversions, MethodSymbol method, ImmutableArray<BoundExpression> arguments, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)method != null); Debug.Assert(method.Arity > 0); Debug.Assert(!arguments.IsDefault); // We need at least one formal parameter type and at least one argument. if ((method.ParameterCount < 1) || (arguments.Length < 1)) { return default(ImmutableArray<TypeWithAnnotations>); } Debug.Assert(!method.GetParameterType(0).IsDynamic()); var constructedFromMethod = method.ConstructedFrom; var inferrer = new MethodTypeInferrer( conversions, constructedFromMethod.TypeParameters, constructedFromMethod.ContainingType, constructedFromMethod.GetParameterTypes(), constructedFromMethod.ParameterRefKinds, arguments, extensions: null); if (!inferrer.InferTypeArgumentsFromFirstArgument(ref useSiteInfo)) { return default(ImmutableArray<TypeWithAnnotations>); } return inferrer.GetInferredTypeArguments(); } //////////////////////////////////////////////////////////////////////////////// private bool InferTypeArgumentsFromFirstArgument(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(!_formalParameterTypes.IsDefault); Debug.Assert(_formalParameterTypes.Length >= 1); Debug.Assert(!_arguments.IsDefault); Debug.Assert(_arguments.Length >= 1); var dest = _formalParameterTypes[0]; var argument = _arguments[0]; TypeSymbol source = argument.Type; // Rule out lambdas, nulls, and so on. if (!IsReallyAType(source)) { return false; } LowerBoundInference(_extensions.GetTypeWithAnnotations(argument), dest, ref useSiteInfo); // Now check to see that every type parameter used by the first // formal parameter type was successfully inferred. for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { TypeParameterSymbol pParam = _methodTypeParameters[iParam]; if (!dest.Type.ContainsTypeParameter(pParam)) { continue; } Debug.Assert(IsUnfixed(iParam)); if (!HasBound(iParam) || !Fix(iParam, ref useSiteInfo)) { return false; } } return true; } /// <summary> /// Return the inferred type arguments using null /// for any type arguments that were not inferred. /// </summary> private ImmutableArray<TypeWithAnnotations> GetInferredTypeArguments() { return _fixedResults.AsImmutable(); } private static bool IsReallyAType(TypeSymbol type) { return (object)type != null && !type.IsErrorType() && !type.IsVoidType(); } private static void GetAllCandidates(Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, ArrayBuilder<TypeWithAnnotations> builder) { builder.AddRange(candidates.Values); } private static void AddAllCandidates( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, HashSet<TypeWithAnnotations> bounds, VarianceKind variance, ConversionsBase conversions) { foreach (var candidate in bounds) { var type = candidate; if (!conversions.IncludeNullability) { // https://github.com/dotnet/roslyn/issues/30534: Should preserve // distinct "not computed" state from initial binding. type = type.SetUnknownNullabilityForReferenceTypes(); } AddOrMergeCandidate(candidates, type, variance, conversions); } } private static void AddOrMergeCandidate( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, TypeWithAnnotations newCandidate, VarianceKind variance, ConversionsBase conversions) { Debug.Assert(conversions.IncludeNullability || newCandidate.SetUnknownNullabilityForReferenceTypes().Equals(newCandidate, TypeCompareKind.ConsiderEverything)); if (candidates.TryGetValue(newCandidate, out TypeWithAnnotations oldCandidate)) { MergeAndReplaceIfStillCandidate(candidates, oldCandidate, newCandidate, variance, conversions); } else { candidates.Add(newCandidate, newCandidate); } } private static void MergeOrRemoveCandidates( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, HashSet<TypeWithAnnotations> bounds, ArrayBuilder<TypeWithAnnotations> initialCandidates, ConversionsBase conversions, VarianceKind variance, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(variance == VarianceKind.In || variance == VarianceKind.Out); // SPEC: For each lower (upper) bound U of Xi all types to which there is not an // SPEC: implicit conversion from (to) U are removed from the candidate set. var comparison = conversions.IncludeNullability ? TypeCompareKind.ConsiderEverything : TypeCompareKind.IgnoreNullableModifiersForReferenceTypes; foreach (var bound in bounds) { foreach (var candidate in initialCandidates) { if (bound.Equals(candidate, comparison)) { continue; } TypeWithAnnotations source; TypeWithAnnotations destination; if (variance == VarianceKind.Out) { source = bound; destination = candidate; } else { source = candidate; destination = bound; } if (!ImplicitConversionExists(source, destination, ref useSiteInfo, conversions.WithNullability(false))) { candidates.Remove(candidate); if (conversions.IncludeNullability && candidates.TryGetValue(bound, out var oldBound)) { // merge the nullability from candidate into bound var oldAnnotation = oldBound.NullableAnnotation; var newAnnotation = oldAnnotation.MergeNullableAnnotation(candidate.NullableAnnotation, variance); if (oldAnnotation != newAnnotation) { var newBound = TypeWithAnnotations.Create(oldBound.Type, newAnnotation); candidates[bound] = newBound; } } } else if (bound.Equals(candidate, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { // SPEC: 4.7 The Dynamic Type // Type inference (7.5.2) will prefer dynamic over object if both are candidates. // // This rule doesn't have to be implemented explicitly due to special handling of // conversions from dynamic in ImplicitConversionExists helper. // MergeAndReplaceIfStillCandidate(candidates, candidate, bound, variance, conversions); } } } } private static void MergeAndReplaceIfStillCandidate( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, TypeWithAnnotations oldCandidate, TypeWithAnnotations newCandidate, VarianceKind variance, ConversionsBase conversions) { // We make an exception when new candidate is dynamic, for backwards compatibility if (newCandidate.Type.IsDynamic()) { return; } if (candidates.TryGetValue(oldCandidate, out TypeWithAnnotations latest)) { // Note: we're ignoring the variance used merging previous candidates into `latest`. // If that variance is different than `variance`, we might infer the wrong nullability, but in that case, // we assume we'll report a warning when converting the arguments to the inferred parameter types. // (For instance, with F<T>(T x, T y, IIn<T> z) and interface IIn<in T> and interface IIOut<out T>, the // call F(IOut<object?>, IOut<object!>, IIn<IOut<object!>>) should find a nullability mismatch. Instead, // we'll merge the lower bounds IOut<object?> with IOut<object!> (using VarianceKind.Out) to produce // IOut<object?>, then merge that result with upper bound IOut<object!> (using VarianceKind.In) // to produce IOut<object?>. But then conversion of argument IIn<IOut<object!>> to parameter // IIn<IOut<object?>> will generate a warning at that point.) TypeWithAnnotations merged = latest.MergeEquivalentTypes(newCandidate, variance); candidates[oldCandidate] = merged; } } /// <summary> /// This is a comparer that ignores differences in dynamic-ness and tuple names. /// But it has a special case for top-level object vs. dynamic for purpose of method type inference. /// </summary> private sealed class EqualsIgnoringDynamicTupleNamesAndNullabilityComparer : EqualityComparer<TypeWithAnnotations> { internal static readonly EqualsIgnoringDynamicTupleNamesAndNullabilityComparer Instance = new EqualsIgnoringDynamicTupleNamesAndNullabilityComparer(); public override int GetHashCode(TypeWithAnnotations obj) { return obj.Type.GetHashCode(); } public override bool Equals(TypeWithAnnotations x, TypeWithAnnotations y) { // We do a equality test ignoring dynamic and tuple names differences, // but dynamic and object are not considered equal for backwards compatibility. if (x.Type.IsDynamic() ^ y.Type.IsDynamic()) { return false; } return x.Equals(y, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } } } }
-1
dotnet/roslyn
55,364
Fix crash with convert namespace
Oopsie.
CyrusNajmabadi
2021-08-03T02:29:24Z
2021-08-03T12:57:53Z
a80a5868188242800f4615dc51ab30ed5e9eaf76
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
Fix crash with convert namespace. Oopsie.
./src/Workspaces/Core/Portable/LanguageServices/DeclaredSymbolFactoryService/AbstractDeclaredSymbolInfoFactoryService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Globalization; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.LanguageServices { internal abstract class AbstractDeclaredSymbolInfoFactoryService< TCompilationUnitSyntax, TUsingDirectiveSyntax, TNamespaceDeclarationSyntax, TTypeDeclarationSyntax, TEnumDeclarationSyntax, TMemberDeclarationSyntax> : IDeclaredSymbolInfoFactoryService where TCompilationUnitSyntax : SyntaxNode where TUsingDirectiveSyntax : SyntaxNode where TNamespaceDeclarationSyntax : TMemberDeclarationSyntax where TTypeDeclarationSyntax : TMemberDeclarationSyntax where TEnumDeclarationSyntax : TMemberDeclarationSyntax where TMemberDeclarationSyntax : SyntaxNode { private static readonly ObjectPool<List<Dictionary<string, string>>> s_aliasMapListPool = SharedPools.Default<List<Dictionary<string, string>>>(); // Note: these names are stored case insensitively. That way the alias mapping works // properly for VB. It will mean that our inheritance maps may store more links in them // for C#. However, that's ok. It will be rare in practice, and all it means is that // we'll end up examining slightly more types (likely 0) when doing operations like // Find all references. private static readonly ObjectPool<Dictionary<string, string>> s_aliasMapPool = SharedPools.StringIgnoreCaseDictionary<string>(); protected AbstractDeclaredSymbolInfoFactoryService() { } protected abstract SyntaxList<TMemberDeclarationSyntax> GetChildren(TCompilationUnitSyntax node); protected abstract SyntaxList<TMemberDeclarationSyntax> GetChildren(TNamespaceDeclarationSyntax node); protected abstract SyntaxList<TMemberDeclarationSyntax> GetChildren(TTypeDeclarationSyntax node); protected abstract IEnumerable<TMemberDeclarationSyntax> GetChildren(TEnumDeclarationSyntax node); protected abstract SyntaxList<TUsingDirectiveSyntax> GetUsingAliases(TCompilationUnitSyntax node); protected abstract SyntaxList<TUsingDirectiveSyntax> GetUsingAliases(TNamespaceDeclarationSyntax node); protected abstract string GetContainerDisplayName(TMemberDeclarationSyntax namespaceDeclaration); protected abstract string GetFullyQualifiedContainerName(TMemberDeclarationSyntax memberDeclaration, string rootNamespace); protected abstract void AddDeclaredSymbolInfosWorker( SyntaxNode container, TMemberDeclarationSyntax memberDeclaration, StringTable stringTable, ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos, Dictionary<string, string> aliases, Dictionary<string, ArrayBuilder<int>> extensionMethodInfo, string containerDisplayName, string fullyQualifiedContainerName, CancellationToken cancellationToken); /// <summary> /// Get the name of the target type of specified extension method declaration. /// The node provided must be an extension method declaration, i.e. calling `TryGetDeclaredSymbolInfo()` /// on `node` should return a `DeclaredSymbolInfo` of kind `ExtensionMethod`. /// If the return value is null, then it means this is a "complex" method (as described at <see cref="SyntaxTreeIndex.ExtensionMethodInfo"/>). /// </summary> protected abstract string GetReceiverTypeName(TMemberDeclarationSyntax node); protected abstract bool TryGetAliasesFromUsingDirective(TUsingDirectiveSyntax node, out ImmutableArray<(string aliasName, string name)> aliases); protected abstract string GetRootNamespace(CompilationOptions compilationOptions); protected static List<Dictionary<string, string>> AllocateAliasMapList() => s_aliasMapListPool.Allocate(); // We do not differentiate arrays of different kinds for simplicity. // e.g. int[], int[][], int[,], etc. are all represented as int[] in the index. protected static string CreateReceiverTypeString(string typeName, bool isArray) { if (string.IsNullOrEmpty(typeName)) { return isArray ? FindSymbols.Extensions.ComplexArrayReceiverTypeName : FindSymbols.Extensions.ComplexReceiverTypeName; } else { return isArray ? typeName + FindSymbols.Extensions.ArrayReceiverTypeNameSuffix : typeName; } } protected static string CreateValueTupleTypeString(int elementCount) { const string ValueTupleName = "ValueTuple"; if (elementCount == 0) { return ValueTupleName; } // A ValueTuple can have up to 8 type parameters. return ValueTupleName + ArityUtilities.GetMetadataAritySuffix(elementCount > 8 ? 8 : elementCount); } protected static void FreeAliasMapList(List<Dictionary<string, string>> list) { if (list != null) { foreach (var aliasMap in list) { FreeAliasMap(aliasMap); } s_aliasMapListPool.ClearAndFree(list); } } protected static void FreeAliasMap(Dictionary<string, string> aliasMap) { if (aliasMap != null) { s_aliasMapPool.ClearAndFree(aliasMap); } } protected static Dictionary<string, string> AllocateAliasMap() => s_aliasMapPool.Allocate(); protected static void AppendTokens(SyntaxNode node, StringBuilder builder) { foreach (var child in node.ChildNodesAndTokens()) { if (child.IsToken) { builder.Append(child.AsToken().Text); } else { AppendTokens(child.AsNode(), builder); } } } protected static void Intern(StringTable stringTable, ArrayBuilder<string> builder) { for (int i = 0, n = builder.Count; i < n; i++) { builder[i] = stringTable.Add(builder[i]); } } public void AddDeclaredSymbolInfos( Document document, SyntaxNode root, ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos, Dictionary<string, ArrayBuilder<int>> extensionMethodInfo, CancellationToken cancellationToken) { var project = document.Project; var stringTable = SyntaxTreeIndex.GetStringTable(project); var rootNamespace = this.GetRootNamespace(project.CompilationOptions); using var _1 = PooledDictionary<string, string>.GetInstance(out var aliases); foreach (var usingAlias in GetUsingAliases((TCompilationUnitSyntax)root)) { if (this.TryGetAliasesFromUsingDirective(usingAlias, out var current)) AddAliases(aliases, current); } foreach (var child in GetChildren((TCompilationUnitSyntax)root)) AddDeclaredSymbolInfos(root, child, stringTable, rootNamespace, declaredSymbolInfos, aliases, extensionMethodInfo, "", "", cancellationToken); } private void AddDeclaredSymbolInfos( SyntaxNode container, TMemberDeclarationSyntax memberDeclaration, StringTable stringTable, string rootNamespace, ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos, Dictionary<string, string> aliases, Dictionary<string, ArrayBuilder<int>> extensionMethodInfo, string containerDisplayName, string fullyQualifiedContainerName, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (memberDeclaration is TNamespaceDeclarationSyntax namespaceDeclaration) { var innerContainerDisplayName = GetContainerDisplayName(memberDeclaration); var innerFullyQualifiedContainerName = GetFullyQualifiedContainerName(memberDeclaration, rootNamespace); foreach (var usingAlias in GetUsingAliases(namespaceDeclaration)) { if (this.TryGetAliasesFromUsingDirective(usingAlias, out var current)) AddAliases(aliases, current); } foreach (var child in GetChildren(namespaceDeclaration)) { AddDeclaredSymbolInfos( memberDeclaration, child, stringTable, rootNamespace, declaredSymbolInfos, aliases, extensionMethodInfo, innerContainerDisplayName, innerFullyQualifiedContainerName, cancellationToken); } } else if (memberDeclaration is TTypeDeclarationSyntax baseTypeDeclaration) { var innerContainerDisplayName = GetContainerDisplayName(memberDeclaration); var innerFullyQualifiedContainerName = GetFullyQualifiedContainerName(memberDeclaration, rootNamespace); foreach (var child in GetChildren(baseTypeDeclaration)) { AddDeclaredSymbolInfos( memberDeclaration, child, stringTable, rootNamespace, declaredSymbolInfos, aliases, extensionMethodInfo, innerContainerDisplayName, innerFullyQualifiedContainerName, cancellationToken); } } else if (memberDeclaration is TEnumDeclarationSyntax enumDeclaration) { var innerContainerDisplayName = GetContainerDisplayName(memberDeclaration); var innerFullyQualifiedContainerName = GetFullyQualifiedContainerName(memberDeclaration, rootNamespace); foreach (var child in GetChildren(enumDeclaration)) { AddDeclaredSymbolInfos( memberDeclaration, child, stringTable, rootNamespace, declaredSymbolInfos, aliases, extensionMethodInfo, innerContainerDisplayName, innerFullyQualifiedContainerName, cancellationToken); } } AddDeclaredSymbolInfosWorker( container, memberDeclaration, stringTable, declaredSymbolInfos, aliases, extensionMethodInfo, containerDisplayName, fullyQualifiedContainerName, cancellationToken); } protected void AddExtensionMethodInfo( TMemberDeclarationSyntax node, Dictionary<string, string> aliases, int declaredSymbolInfoIndex, Dictionary<string, ArrayBuilder<int>> extensionMethodsInfoBuilder) { var receiverTypeName = this.GetReceiverTypeName(node); // Target type is an alias if (aliases.TryGetValue(receiverTypeName, out var originalName)) { // it is an alias of multiple with identical name, // simply treat it as a complex method. if (originalName == null) { receiverTypeName = FindSymbols.Extensions.ComplexReceiverTypeName; } else { // replace the alias with its original name. receiverTypeName = originalName; } } if (!extensionMethodsInfoBuilder.TryGetValue(receiverTypeName, out var arrayBuilder)) { arrayBuilder = ArrayBuilder<int>.GetInstance(); extensionMethodsInfoBuilder[receiverTypeName] = arrayBuilder; } arrayBuilder.Add(declaredSymbolInfoIndex); } private static void AddAliases(Dictionary<string, string> allAliases, ImmutableArray<(string aliasName, string name)> aliases) { foreach (var (aliasName, name) in aliases) { // In C#, it's valid to declare two alias with identical name, // as long as they are in different containers. // // e.g. // using X = System.String; // namespace N // { // using X = System.Int32; // } // // If we detect this, we will simply treat extension methods whose // target type is this alias as complex method. if (allAliases.ContainsKey(aliasName)) { allAliases[aliasName] = null; } else { allAliases[aliasName] = name; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Globalization; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.LanguageServices { internal abstract class AbstractDeclaredSymbolInfoFactoryService< TCompilationUnitSyntax, TUsingDirectiveSyntax, TNamespaceDeclarationSyntax, TTypeDeclarationSyntax, TEnumDeclarationSyntax, TMemberDeclarationSyntax> : IDeclaredSymbolInfoFactoryService where TCompilationUnitSyntax : SyntaxNode where TUsingDirectiveSyntax : SyntaxNode where TNamespaceDeclarationSyntax : TMemberDeclarationSyntax where TTypeDeclarationSyntax : TMemberDeclarationSyntax where TEnumDeclarationSyntax : TMemberDeclarationSyntax where TMemberDeclarationSyntax : SyntaxNode { private static readonly ObjectPool<List<Dictionary<string, string>>> s_aliasMapListPool = SharedPools.Default<List<Dictionary<string, string>>>(); // Note: these names are stored case insensitively. That way the alias mapping works // properly for VB. It will mean that our inheritance maps may store more links in them // for C#. However, that's ok. It will be rare in practice, and all it means is that // we'll end up examining slightly more types (likely 0) when doing operations like // Find all references. private static readonly ObjectPool<Dictionary<string, string>> s_aliasMapPool = SharedPools.StringIgnoreCaseDictionary<string>(); protected AbstractDeclaredSymbolInfoFactoryService() { } protected abstract SyntaxList<TMemberDeclarationSyntax> GetChildren(TCompilationUnitSyntax node); protected abstract SyntaxList<TMemberDeclarationSyntax> GetChildren(TNamespaceDeclarationSyntax node); protected abstract SyntaxList<TMemberDeclarationSyntax> GetChildren(TTypeDeclarationSyntax node); protected abstract IEnumerable<TMemberDeclarationSyntax> GetChildren(TEnumDeclarationSyntax node); protected abstract SyntaxList<TUsingDirectiveSyntax> GetUsingAliases(TCompilationUnitSyntax node); protected abstract SyntaxList<TUsingDirectiveSyntax> GetUsingAliases(TNamespaceDeclarationSyntax node); protected abstract string GetContainerDisplayName(TMemberDeclarationSyntax namespaceDeclaration); protected abstract string GetFullyQualifiedContainerName(TMemberDeclarationSyntax memberDeclaration, string rootNamespace); protected abstract void AddDeclaredSymbolInfosWorker( SyntaxNode container, TMemberDeclarationSyntax memberDeclaration, StringTable stringTable, ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos, Dictionary<string, string> aliases, Dictionary<string, ArrayBuilder<int>> extensionMethodInfo, string containerDisplayName, string fullyQualifiedContainerName, CancellationToken cancellationToken); /// <summary> /// Get the name of the target type of specified extension method declaration. /// The node provided must be an extension method declaration, i.e. calling `TryGetDeclaredSymbolInfo()` /// on `node` should return a `DeclaredSymbolInfo` of kind `ExtensionMethod`. /// If the return value is null, then it means this is a "complex" method (as described at <see cref="SyntaxTreeIndex.ExtensionMethodInfo"/>). /// </summary> protected abstract string GetReceiverTypeName(TMemberDeclarationSyntax node); protected abstract bool TryGetAliasesFromUsingDirective(TUsingDirectiveSyntax node, out ImmutableArray<(string aliasName, string name)> aliases); protected abstract string GetRootNamespace(CompilationOptions compilationOptions); protected static List<Dictionary<string, string>> AllocateAliasMapList() => s_aliasMapListPool.Allocate(); // We do not differentiate arrays of different kinds for simplicity. // e.g. int[], int[][], int[,], etc. are all represented as int[] in the index. protected static string CreateReceiverTypeString(string typeName, bool isArray) { if (string.IsNullOrEmpty(typeName)) { return isArray ? FindSymbols.Extensions.ComplexArrayReceiverTypeName : FindSymbols.Extensions.ComplexReceiverTypeName; } else { return isArray ? typeName + FindSymbols.Extensions.ArrayReceiverTypeNameSuffix : typeName; } } protected static string CreateValueTupleTypeString(int elementCount) { const string ValueTupleName = "ValueTuple"; if (elementCount == 0) { return ValueTupleName; } // A ValueTuple can have up to 8 type parameters. return ValueTupleName + ArityUtilities.GetMetadataAritySuffix(elementCount > 8 ? 8 : elementCount); } protected static void FreeAliasMapList(List<Dictionary<string, string>> list) { if (list != null) { foreach (var aliasMap in list) { FreeAliasMap(aliasMap); } s_aliasMapListPool.ClearAndFree(list); } } protected static void FreeAliasMap(Dictionary<string, string> aliasMap) { if (aliasMap != null) { s_aliasMapPool.ClearAndFree(aliasMap); } } protected static Dictionary<string, string> AllocateAliasMap() => s_aliasMapPool.Allocate(); protected static void AppendTokens(SyntaxNode node, StringBuilder builder) { foreach (var child in node.ChildNodesAndTokens()) { if (child.IsToken) { builder.Append(child.AsToken().Text); } else { AppendTokens(child.AsNode(), builder); } } } protected static void Intern(StringTable stringTable, ArrayBuilder<string> builder) { for (int i = 0, n = builder.Count; i < n; i++) { builder[i] = stringTable.Add(builder[i]); } } public void AddDeclaredSymbolInfos( Document document, SyntaxNode root, ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos, Dictionary<string, ArrayBuilder<int>> extensionMethodInfo, CancellationToken cancellationToken) { var project = document.Project; var stringTable = SyntaxTreeIndex.GetStringTable(project); var rootNamespace = this.GetRootNamespace(project.CompilationOptions); using var _1 = PooledDictionary<string, string>.GetInstance(out var aliases); foreach (var usingAlias in GetUsingAliases((TCompilationUnitSyntax)root)) { if (this.TryGetAliasesFromUsingDirective(usingAlias, out var current)) AddAliases(aliases, current); } foreach (var child in GetChildren((TCompilationUnitSyntax)root)) AddDeclaredSymbolInfos(root, child, stringTable, rootNamespace, declaredSymbolInfos, aliases, extensionMethodInfo, "", "", cancellationToken); } private void AddDeclaredSymbolInfos( SyntaxNode container, TMemberDeclarationSyntax memberDeclaration, StringTable stringTable, string rootNamespace, ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos, Dictionary<string, string> aliases, Dictionary<string, ArrayBuilder<int>> extensionMethodInfo, string containerDisplayName, string fullyQualifiedContainerName, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (memberDeclaration is TNamespaceDeclarationSyntax namespaceDeclaration) { var innerContainerDisplayName = GetContainerDisplayName(memberDeclaration); var innerFullyQualifiedContainerName = GetFullyQualifiedContainerName(memberDeclaration, rootNamespace); foreach (var usingAlias in GetUsingAliases(namespaceDeclaration)) { if (this.TryGetAliasesFromUsingDirective(usingAlias, out var current)) AddAliases(aliases, current); } foreach (var child in GetChildren(namespaceDeclaration)) { AddDeclaredSymbolInfos( memberDeclaration, child, stringTable, rootNamespace, declaredSymbolInfos, aliases, extensionMethodInfo, innerContainerDisplayName, innerFullyQualifiedContainerName, cancellationToken); } } else if (memberDeclaration is TTypeDeclarationSyntax baseTypeDeclaration) { var innerContainerDisplayName = GetContainerDisplayName(memberDeclaration); var innerFullyQualifiedContainerName = GetFullyQualifiedContainerName(memberDeclaration, rootNamespace); foreach (var child in GetChildren(baseTypeDeclaration)) { AddDeclaredSymbolInfos( memberDeclaration, child, stringTable, rootNamespace, declaredSymbolInfos, aliases, extensionMethodInfo, innerContainerDisplayName, innerFullyQualifiedContainerName, cancellationToken); } } else if (memberDeclaration is TEnumDeclarationSyntax enumDeclaration) { var innerContainerDisplayName = GetContainerDisplayName(memberDeclaration); var innerFullyQualifiedContainerName = GetFullyQualifiedContainerName(memberDeclaration, rootNamespace); foreach (var child in GetChildren(enumDeclaration)) { AddDeclaredSymbolInfos( memberDeclaration, child, stringTable, rootNamespace, declaredSymbolInfos, aliases, extensionMethodInfo, innerContainerDisplayName, innerFullyQualifiedContainerName, cancellationToken); } } AddDeclaredSymbolInfosWorker( container, memberDeclaration, stringTable, declaredSymbolInfos, aliases, extensionMethodInfo, containerDisplayName, fullyQualifiedContainerName, cancellationToken); } protected void AddExtensionMethodInfo( TMemberDeclarationSyntax node, Dictionary<string, string> aliases, int declaredSymbolInfoIndex, Dictionary<string, ArrayBuilder<int>> extensionMethodsInfoBuilder) { var receiverTypeName = this.GetReceiverTypeName(node); // Target type is an alias if (aliases.TryGetValue(receiverTypeName, out var originalName)) { // it is an alias of multiple with identical name, // simply treat it as a complex method. if (originalName == null) { receiverTypeName = FindSymbols.Extensions.ComplexReceiverTypeName; } else { // replace the alias with its original name. receiverTypeName = originalName; } } if (!extensionMethodsInfoBuilder.TryGetValue(receiverTypeName, out var arrayBuilder)) { arrayBuilder = ArrayBuilder<int>.GetInstance(); extensionMethodsInfoBuilder[receiverTypeName] = arrayBuilder; } arrayBuilder.Add(declaredSymbolInfoIndex); } private static void AddAliases(Dictionary<string, string> allAliases, ImmutableArray<(string aliasName, string name)> aliases) { foreach (var (aliasName, name) in aliases) { // In C#, it's valid to declare two alias with identical name, // as long as they are in different containers. // // e.g. // using X = System.String; // namespace N // { // using X = System.Int32; // } // // If we detect this, we will simply treat extension methods whose // target type is this alias as complex method. if (allAliases.ContainsKey(aliasName)) { allAliases[aliasName] = null; } else { allAliases[aliasName] = name; } } } } }
-1
dotnet/roslyn
55,364
Fix crash with convert namespace
Oopsie.
CyrusNajmabadi
2021-08-03T02:29:24Z
2021-08-03T12:57:53Z
a80a5868188242800f4615dc51ab30ed5e9eaf76
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
Fix crash with convert namespace. Oopsie.
./src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/IRemoteExtensionMethodImportCompletionService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Remote; namespace Microsoft.CodeAnalysis.Completion.Providers { internal interface IRemoteExtensionMethodImportCompletionService { public ValueTask<SerializableUnimportedExtensionMethods> GetUnimportedExtensionMethodsAsync( PinnedSolutionInfo solutionInfo, DocumentId documentId, int position, string receiverTypeSymbolKeyData, ImmutableArray<string> namespaceInScope, ImmutableArray<string> targetTypesSymbolKeyData, bool forceIndexCreation, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Remote; namespace Microsoft.CodeAnalysis.Completion.Providers { internal interface IRemoteExtensionMethodImportCompletionService { public ValueTask<SerializableUnimportedExtensionMethods> GetUnimportedExtensionMethodsAsync( PinnedSolutionInfo solutionInfo, DocumentId documentId, int position, string receiverTypeSymbolKeyData, ImmutableArray<string> namespaceInScope, ImmutableArray<string> targetTypesSymbolKeyData, bool forceIndexCreation, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,364
Fix crash with convert namespace
Oopsie.
CyrusNajmabadi
2021-08-03T02:29:24Z
2021-08-03T12:57:53Z
a80a5868188242800f4615dc51ab30ed5e9eaf76
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
Fix crash with convert namespace. Oopsie.
./src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.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="../CSharpCodeFixesResources.resx"> <body> <trans-unit id="Add_this"> <source>Add 'this.'</source> <target state="translated">添加 "this."</target> <note /> </trans-unit> <trans-unit id="Convert_typeof_to_nameof"> <source>Convert 'typeof' to 'nameof'</source> <target state="translated">将 "typeof" 转换为 "nameof"</target> <note /> </trans-unit> <trans-unit id="Pass_in_captured_variables_as_arguments"> <source>Pass in captured variables as arguments</source> <target state="translated">以参数形式传入捕获的变量</target> <note /> </trans-unit> <trans-unit id="Place_colon_on_following_line"> <source>Place colon on following line</source> <target state="translated">将冒号另起一行</target> <note /> </trans-unit> <trans-unit id="Place_statement_on_following_line"> <source>Place statement on following line</source> <target state="translated">将语句另起一行</target> <note /> </trans-unit> <trans-unit id="Remove_Unnecessary_Usings"> <source>Remove Unnecessary Usings</source> <target state="translated">删除不必要的 Using</target> <note /> </trans-unit> <trans-unit id="Remove_blank_lines_between_braces"> <source>Remove blank line between braces</source> <target state="translated">删除括号之间的空白行</target> <note /> </trans-unit> <trans-unit id="Remove_unreachable_code"> <source>Remove unreachable code</source> <target state="translated">删除无法访问的代码</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Adding_parameters_to_local_function_declaration_may_produce_invalid_code"> <source>Warning: Adding parameters to local function declaration may produce invalid code.</source> <target state="translated">警告: 将参数添加到本地函数声明可能产生无效的代码。</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="zh-Hans" original="../CSharpCodeFixesResources.resx"> <body> <trans-unit id="Add_this"> <source>Add 'this.'</source> <target state="translated">添加 "this."</target> <note /> </trans-unit> <trans-unit id="Convert_typeof_to_nameof"> <source>Convert 'typeof' to 'nameof'</source> <target state="translated">将 "typeof" 转换为 "nameof"</target> <note /> </trans-unit> <trans-unit id="Pass_in_captured_variables_as_arguments"> <source>Pass in captured variables as arguments</source> <target state="translated">以参数形式传入捕获的变量</target> <note /> </trans-unit> <trans-unit id="Place_colon_on_following_line"> <source>Place colon on following line</source> <target state="translated">将冒号另起一行</target> <note /> </trans-unit> <trans-unit id="Place_statement_on_following_line"> <source>Place statement on following line</source> <target state="translated">将语句另起一行</target> <note /> </trans-unit> <trans-unit id="Remove_Unnecessary_Usings"> <source>Remove Unnecessary Usings</source> <target state="translated">删除不必要的 Using</target> <note /> </trans-unit> <trans-unit id="Remove_blank_lines_between_braces"> <source>Remove blank line between braces</source> <target state="translated">删除括号之间的空白行</target> <note /> </trans-unit> <trans-unit id="Remove_unreachable_code"> <source>Remove unreachable code</source> <target state="translated">删除无法访问的代码</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Adding_parameters_to_local_function_declaration_may_produce_invalid_code"> <source>Warning: Adding parameters to local function declaration may produce invalid code.</source> <target state="translated">警告: 将参数添加到本地函数声明可能产生无效的代码。</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,364
Fix crash with convert namespace
Oopsie.
CyrusNajmabadi
2021-08-03T02:29:24Z
2021-08-03T12:57:53Z
a80a5868188242800f4615dc51ab30ed5e9eaf76
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
Fix crash with convert namespace. Oopsie.
./src/Compilers/Core/Portable/InternalUtilities/KeyValuePairUtil.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Roslyn.Utilities { internal static class KeyValuePairUtil { public static KeyValuePair<K, V> Create<K, V>(K key, V value) { return new KeyValuePair<K, V>(key, value); } public static void Deconstruct<TKey, TValue>(this KeyValuePair<TKey, TValue> keyValuePair, out TKey key, out TValue value) { key = keyValuePair.Key; value = keyValuePair.Value; } public static KeyValuePair<TKey, TValue> ToKeyValuePair<TKey, TValue>(this (TKey, TValue) tuple) => Create(tuple.Item1, tuple.Item2); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Roslyn.Utilities { internal static class KeyValuePairUtil { public static KeyValuePair<K, V> Create<K, V>(K key, V value) { return new KeyValuePair<K, V>(key, value); } public static void Deconstruct<TKey, TValue>(this KeyValuePair<TKey, TValue> keyValuePair, out TKey key, out TValue value) { key = keyValuePair.Key; value = keyValuePair.Value; } public static KeyValuePair<TKey, TValue> ToKeyValuePair<TKey, TValue>(this (TKey, TValue) tuple) => Create(tuple.Item1, tuple.Item2); } }
-1
dotnet/roslyn
55,364
Fix crash with convert namespace
Oopsie.
CyrusNajmabadi
2021-08-03T02:29:24Z
2021-08-03T12:57:53Z
a80a5868188242800f4615dc51ab30ed5e9eaf76
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
Fix crash with convert namespace. Oopsie.
./src/EditorFeatures/Test2/FindReferences/FindReferencesTests.ExplicitInterfaceMethodSymbols.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences Partial Public Class FindReferencesTests <WorkItem(538972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538972")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestExplicitMethod1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I { void {|Definition:G$$oo|}(); } class C : I { void I.{|Definition:Goo|}() { } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(538972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538972")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestExplicitMethod2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I { void {|Definition:Goo|}(); } class C : I { void I.{|Definition:G$$oo|}() { } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestExplicitMethod3(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I { void {|Definition:G$$oo|}() {} } class C : I { void I.{|Definition:Goo|}() { } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestExplicitMethod4(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I { void {|Definition:Goo|}() {} } class C : I { void I.{|Definition:G$$oo|}() { } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestExplicitMethod5(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I { void {|Definition:G$$oo|}(); } interface C : I { void I.{|Definition:Goo|}() { } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestExplicitMethod6(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I { void {|Definition:Goo|}(); } interface C : I { void I.{|Definition:G$$oo|}() { } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestExplicitMethod7(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I { void {|Definition:G$$oo|}() {} } interface C : I { void I.{|Definition:Goo|}() { } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestExplicitMethod8(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I { void {|Definition:Goo|}() {} } interface C : I { void I.{|Definition:G$$oo|}() { } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestExplicitMethodAndInheritance(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; abstract class C { public abstract void {|Definition:Boo|}(); } interface A { void Boo(); } class B : C, A { void A.Boo() { } public override void {|Definition:$$Boo|}() { } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences Partial Public Class FindReferencesTests <WorkItem(538972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538972")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestExplicitMethod1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I { void {|Definition:G$$oo|}(); } class C : I { void I.{|Definition:Goo|}() { } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(538972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538972")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestExplicitMethod2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I { void {|Definition:Goo|}(); } class C : I { void I.{|Definition:G$$oo|}() { } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestExplicitMethod3(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I { void {|Definition:G$$oo|}() {} } class C : I { void I.{|Definition:Goo|}() { } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestExplicitMethod4(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I { void {|Definition:Goo|}() {} } class C : I { void I.{|Definition:G$$oo|}() { } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestExplicitMethod5(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I { void {|Definition:G$$oo|}(); } interface C : I { void I.{|Definition:Goo|}() { } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestExplicitMethod6(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I { void {|Definition:Goo|}(); } interface C : I { void I.{|Definition:G$$oo|}() { } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestExplicitMethod7(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I { void {|Definition:G$$oo|}() {} } interface C : I { void I.{|Definition:Goo|}() { } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestExplicitMethod8(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface I { void {|Definition:Goo|}() {} } interface C : I { void I.{|Definition:G$$oo|}() { } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestExplicitMethodAndInheritance(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; abstract class C { public abstract void {|Definition:Boo|}(); } interface A { void Boo(); } class B : C, A { void A.Boo() { } public override void {|Definition:$$Boo|}() { } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function End Class End Namespace
-1
dotnet/roslyn
55,364
Fix crash with convert namespace
Oopsie.
CyrusNajmabadi
2021-08-03T02:29:24Z
2021-08-03T12:57:53Z
a80a5868188242800f4615dc51ab30ed5e9eaf76
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
Fix crash with convert namespace. Oopsie.
./src/EditorFeatures/VisualBasicTest/ConvertCast/ConvertTryCastToDirectCastTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeRefactoringVerifier(Of Microsoft.CodeAnalysis.VisualBasic.ConvertConversionOperators.VisualBasicConvertTryCastToDirectCastCodeRefactoringProvider) Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ConvertCast <Trait(Traits.Feature, Traits.Features.ConvertCast)> Public Class ConvertTryCastToDirectCastTests <Fact> Public Async Function ConvertFromTryCastToDirectCast() As Task Dim markup = " Module Program Sub M() Dim x = TryCast(1[||], Object) End Sub End Module " Dim expected = " Module Program Sub M() Dim x = DirectCast(1, Object) End Sub End Module " Await New VerifyVB.Test With { .TestCode = markup, .FixedCode = expected }.RunAsync() End Function <Theory> <InlineData("TryCast(TryCast(1, [||]object), C)", "TryCast(DirectCast(1, object), C)")> <InlineData("TryCast(TryCast(1, object), [||]C)", "DirectCast(TryCast(1, object), C)")> Public Async Function ConvertFromTryCastNested(DirectCastExpression As String, converted As String) As Task Dim markup = " Public Class C End Class Module Program Sub M() Dim x = " + DirectCastExpression + " End Sub End Module " Dim fixed = " Public Class C End Class Module Program Sub M() Dim x = " + converted + " End Sub End Module " Await New VerifyVB.Test With { .TestCode = markup, .FixedCode = fixed }.RunAsync() End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeRefactoringVerifier(Of Microsoft.CodeAnalysis.VisualBasic.ConvertConversionOperators.VisualBasicConvertTryCastToDirectCastCodeRefactoringProvider) Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ConvertCast <Trait(Traits.Feature, Traits.Features.ConvertCast)> Public Class ConvertTryCastToDirectCastTests <Fact> Public Async Function ConvertFromTryCastToDirectCast() As Task Dim markup = " Module Program Sub M() Dim x = TryCast(1[||], Object) End Sub End Module " Dim expected = " Module Program Sub M() Dim x = DirectCast(1, Object) End Sub End Module " Await New VerifyVB.Test With { .TestCode = markup, .FixedCode = expected }.RunAsync() End Function <Theory> <InlineData("TryCast(TryCast(1, [||]object), C)", "TryCast(DirectCast(1, object), C)")> <InlineData("TryCast(TryCast(1, object), [||]C)", "DirectCast(TryCast(1, object), C)")> Public Async Function ConvertFromTryCastNested(DirectCastExpression As String, converted As String) As Task Dim markup = " Public Class C End Class Module Program Sub M() Dim x = " + DirectCastExpression + " End Sub End Module " Dim fixed = " Public Class C End Class Module Program Sub M() Dim x = " + converted + " End Sub End Module " Await New VerifyVB.Test With { .TestCode = markup, .FixedCode = fixed }.RunAsync() End Function End Class End Namespace
-1
dotnet/roslyn
55,364
Fix crash with convert namespace
Oopsie.
CyrusNajmabadi
2021-08-03T02:29:24Z
2021-08-03T12:57:53Z
a80a5868188242800f4615dc51ab30ed5e9eaf76
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
Fix crash with convert namespace. Oopsie.
./src/EditorFeatures/VisualBasicTest/KeywordHighlighting/XmlElementHighlighterTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting Public Class XmlElementHighlighterTests Inherits AbstractVisualBasicKeywordHighlighterTests Friend Overrides Function GetHighlighterType() As Type Return GetType(XmlElementHighlighter) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestXmlElement1() As Task Await TestAsync(<Text><![CDATA[ Class C Sub M() Dim q = {|Cursor:[|<goo>|]|} Bar [|</goo>|] End Sub End Class]]></Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestXmlElement2() As Task Await TestAsync(<Text><![CDATA[ Class C Sub M() Dim q = [|<goo>|] Bar {|Cursor:[|</goo>|]|} End Sub End Class]]></Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestXmlElement3() As Task Await TestAsync(<Text><![CDATA[ Class C Sub M() Dim q = <goo> {|Cursor:Bar|} </goo> End Sub End Class]]></Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestXmlLiteralSample2_1() As Task Await TestAsync(<Text><![CDATA[ Class C Sub M() Dim q = <?xml version="1.0"?> {|Cursor:[|<contact>|]|} <!-- who is this guy? --> <name>Bill Chiles</name> <phone type="home">555-555-5555</phone> <birthyear><%= DateTime.Today.Year - 100 %></birthyear> <![CDATA[Be wary of this guy!]]>]]<![CDATA[> [|</contact>|] End Sub End Class]]></Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestXmlLiteralSample2_2() As Task Await TestAsync(<Text><![CDATA[ Class C Sub M() Dim q = <?xml version="1.0"?> [|<contact>|] <!-- who is this guy? --> <name>Bill Chiles</name> <phone type="home">555-555-5555</phone> <birthyear><%= DateTime.Today.Year - 100 %></birthyear> <![CDATA[Be wary of this guy!]]>]]<![CDATA[> {|Cursor:[|</contact>|]|} End Sub End Class]]></Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestXmlLiteralSample4_1() As Task Await TestAsync(<Text><![CDATA[ Class C Sub M() Dim q = <?xml version="1.0"?> <contact> <!-- who is this guy? --> <name>Bill Chiles</name> {|Cursor:[|<phone|]|} type="home"[|>|]555-555-5555[|</phone>|] <birthyear><%= DateTime.Today.Year - 100 %></birthyear> <![CDATA[Be wary of this guy!]]>]]<![CDATA[> </contact> End Sub End Class]]></Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestXmlLiteralSample4_2() As Task Await TestAsync(<Text><![CDATA[ Class C Sub M() Dim q = <?xml version="1.0"?> <contact> <!-- who is this guy? --> <name>Bill Chiles</name> [|<phone|] type="home"{|Cursor:[|>|]|}555-555-5555[|</phone>|] <birthyear><%= DateTime.Today.Year - 100 %></birthyear> <![CDATA[Be wary of this guy!]]>]]<![CDATA[> </contact> End Sub End Class]]></Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestXmlLiteralSample4_3() As Task Await TestAsync(<Text><![CDATA[ Class C Sub M() Dim q = <?xml version="1.0"?> <contact> <!-- who is this guy? --> <name>Bill Chiles</name> [|<phone|] type="home"[|>|]555-555-5555{|Cursor:[|</phone>|]|} <birthyear><%= DateTime.Today.Year - 100 %></birthyear> <![CDATA[Be wary of this guy!]]>]]<![CDATA[> </contact> End Sub End Class]]></Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestXmlLiteralSample4_4() As Task Await TestAsync(<Text><![CDATA[ Class C Sub M() Dim q = <?xml version="1.0"?> <contact> <!-- who is this guy? --> <name>Bill Chiles</name> <phone {|Cursor:type="home|}">555-555-5555</phone> <birthyear><%= DateTime.Today.Year - 100 %></birthyear> <![CDATA[Be wary of this guy!]]>]]<![CDATA[> </contact> End Sub End Class]]></Text>) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting Public Class XmlElementHighlighterTests Inherits AbstractVisualBasicKeywordHighlighterTests Friend Overrides Function GetHighlighterType() As Type Return GetType(XmlElementHighlighter) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestXmlElement1() As Task Await TestAsync(<Text><![CDATA[ Class C Sub M() Dim q = {|Cursor:[|<goo>|]|} Bar [|</goo>|] End Sub End Class]]></Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestXmlElement2() As Task Await TestAsync(<Text><![CDATA[ Class C Sub M() Dim q = [|<goo>|] Bar {|Cursor:[|</goo>|]|} End Sub End Class]]></Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestXmlElement3() As Task Await TestAsync(<Text><![CDATA[ Class C Sub M() Dim q = <goo> {|Cursor:Bar|} </goo> End Sub End Class]]></Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestXmlLiteralSample2_1() As Task Await TestAsync(<Text><![CDATA[ Class C Sub M() Dim q = <?xml version="1.0"?> {|Cursor:[|<contact>|]|} <!-- who is this guy? --> <name>Bill Chiles</name> <phone type="home">555-555-5555</phone> <birthyear><%= DateTime.Today.Year - 100 %></birthyear> <![CDATA[Be wary of this guy!]]>]]<![CDATA[> [|</contact>|] End Sub End Class]]></Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestXmlLiteralSample2_2() As Task Await TestAsync(<Text><![CDATA[ Class C Sub M() Dim q = <?xml version="1.0"?> [|<contact>|] <!-- who is this guy? --> <name>Bill Chiles</name> <phone type="home">555-555-5555</phone> <birthyear><%= DateTime.Today.Year - 100 %></birthyear> <![CDATA[Be wary of this guy!]]>]]<![CDATA[> {|Cursor:[|</contact>|]|} End Sub End Class]]></Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestXmlLiteralSample4_1() As Task Await TestAsync(<Text><![CDATA[ Class C Sub M() Dim q = <?xml version="1.0"?> <contact> <!-- who is this guy? --> <name>Bill Chiles</name> {|Cursor:[|<phone|]|} type="home"[|>|]555-555-5555[|</phone>|] <birthyear><%= DateTime.Today.Year - 100 %></birthyear> <![CDATA[Be wary of this guy!]]>]]<![CDATA[> </contact> End Sub End Class]]></Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestXmlLiteralSample4_2() As Task Await TestAsync(<Text><![CDATA[ Class C Sub M() Dim q = <?xml version="1.0"?> <contact> <!-- who is this guy? --> <name>Bill Chiles</name> [|<phone|] type="home"{|Cursor:[|>|]|}555-555-5555[|</phone>|] <birthyear><%= DateTime.Today.Year - 100 %></birthyear> <![CDATA[Be wary of this guy!]]>]]<![CDATA[> </contact> End Sub End Class]]></Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestXmlLiteralSample4_3() As Task Await TestAsync(<Text><![CDATA[ Class C Sub M() Dim q = <?xml version="1.0"?> <contact> <!-- who is this guy? --> <name>Bill Chiles</name> [|<phone|] type="home"[|>|]555-555-5555{|Cursor:[|</phone>|]|} <birthyear><%= DateTime.Today.Year - 100 %></birthyear> <![CDATA[Be wary of this guy!]]>]]<![CDATA[> </contact> End Sub End Class]]></Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestXmlLiteralSample4_4() As Task Await TestAsync(<Text><![CDATA[ Class C Sub M() Dim q = <?xml version="1.0"?> <contact> <!-- who is this guy? --> <name>Bill Chiles</name> <phone {|Cursor:type="home|}">555-555-5555</phone> <birthyear><%= DateTime.Today.Year - 100 %></birthyear> <![CDATA[Be wary of this guy!]]>]]<![CDATA[> </contact> End Sub End Class]]></Text>) End Function End Class End Namespace
-1
dotnet/roslyn
55,364
Fix crash with convert namespace
Oopsie.
CyrusNajmabadi
2021-08-03T02:29:24Z
2021-08-03T12:57:53Z
a80a5868188242800f4615dc51ab30ed5e9eaf76
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
Fix crash with convert namespace. Oopsie.
./src/Workspaces/VisualBasic/Portable/Classification/SyntaxClassification/NameSyntaxClassifier.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Classification Imports Microsoft.CodeAnalysis.Classification.Classifiers Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Classification.Classifiers Friend Class NameSyntaxClassifier Inherits AbstractNameSyntaxClassifier Public Overrides ReadOnly Property SyntaxNodeTypes As ImmutableArray(Of Type) = ImmutableArray.Create( GetType(NameSyntax), GetType(ModifiedIdentifierSyntax), GetType(MethodStatementSyntax), GetType(LabelSyntax)) Public Overrides Sub AddClassifications( workspace As Workspace, syntax As SyntaxNode, semanticModel As SemanticModel, result As ArrayBuilder(Of ClassifiedSpan), cancellationToken As CancellationToken) Dim nameSyntax = TryCast(syntax, NameSyntax) If nameSyntax IsNot Nothing Then ClassifyNameSyntax(nameSyntax, semanticModel, result, cancellationToken) Return End If Dim modifiedIdentifier = TryCast(syntax, ModifiedIdentifierSyntax) If modifiedIdentifier IsNot Nothing Then ClassifyModifiedIdentifier(modifiedIdentifier, result) Return End If Dim methodStatement = TryCast(syntax, MethodStatementSyntax) If methodStatement IsNot Nothing Then ClassifyMethodStatement(methodStatement, semanticModel, result) Return End If Dim labelSyntax = TryCast(syntax, LabelSyntax) If labelSyntax IsNot Nothing Then ClassifyLabelSyntax(labelSyntax, result) Return End If End Sub Protected Overrides Function GetRightmostNameArity(node As SyntaxNode) As Integer? If TypeOf (node) Is ExpressionSyntax Then Return DirectCast(node, ExpressionSyntax).GetRightmostName()?.Arity End If Return Nothing End Function Protected Overrides Function IsParentAnAttribute(node As SyntaxNode) As Boolean Return node.IsParentKind(SyntaxKind.Attribute) End Function Private Sub ClassifyNameSyntax( node As NameSyntax, semanticModel As SemanticModel, result As ArrayBuilder(Of ClassifiedSpan), cancellationToken As CancellationToken) Dim classifiedSpan As ClassifiedSpan Dim symbolInfo = semanticModel.GetSymbolInfo(node, cancellationToken) Dim symbol = TryGetSymbol(node, symbolInfo, semanticModel) If symbol Is Nothing Then If TryClassifyIdentifier(node, semanticModel, cancellationToken, classifiedSpan) Then result.Add(classifiedSpan) End If Return End If If TryClassifyMyNamespace(node, symbol, semanticModel, classifiedSpan) Then result.Add(classifiedSpan) ElseIf TryClassifySymbol(node, symbol, classifiedSpan) Then result.Add(classifiedSpan) ' Additionally classify static symbols TryClassifyStaticSymbol(symbol, classifiedSpan.TextSpan, result) End If End Sub Private Shared Function TryClassifySymbol( node As NameSyntax, symbol As ISymbol, ByRef classifiedSpan As ClassifiedSpan) As Boolean Select Case symbol.Kind Case SymbolKind.Namespace ' Do not classify the Global namespace. It is already syntactically classified as a keyword. ' Also, we ignore QualifiedNameSyntax nodes since we want to classify individual name parts. If Not node.IsKind(SyntaxKind.GlobalName) AndAlso TypeOf node Is IdentifierNameSyntax Then classifiedSpan = New ClassifiedSpan(GetNameToken(node).Span, ClassificationTypeNames.NamespaceName) Return True End If Case SymbolKind.Method Dim classification = GetClassificationForMethod(node, DirectCast(symbol, IMethodSymbol)) If classification IsNot Nothing Then classifiedSpan = New ClassifiedSpan(GetNameToken(node).Span, classification) Return True End If Case SymbolKind.Event classifiedSpan = New ClassifiedSpan(GetNameToken(node).Span, ClassificationTypeNames.EventName) Return True Case SymbolKind.Property classifiedSpan = New ClassifiedSpan(GetNameToken(node).Span, ClassificationTypeNames.PropertyName) Return True Case SymbolKind.Field Dim classification = GetClassificationForField(DirectCast(symbol, IFieldSymbol)) If classification IsNot Nothing Then classifiedSpan = New ClassifiedSpan(GetNameToken(node).Span, classification) Return True End If Case SymbolKind.Parameter classifiedSpan = New ClassifiedSpan(GetNameToken(node).Span, ClassificationTypeNames.ParameterName) Return True Case SymbolKind.Local Dim classification = GetClassificationForLocal(DirectCast(symbol, ILocalSymbol)) If classification IsNot Nothing Then classifiedSpan = New ClassifiedSpan(GetNameToken(node).Span, classification) Return True End If End Select Dim type = TryCast(symbol, ITypeSymbol) If type IsNot Nothing Then Dim classification = GetClassificationForType(type) If classification IsNot Nothing Then Dim token = GetNameToken(node) classifiedSpan = New ClassifiedSpan(token.Span, classification) Return True End If End If Return False End Function Private Shared Function TryClassifyMyNamespace( node As NameSyntax, symbol As ISymbol, semanticModel As SemanticModel, ByRef classifiedSpan As ClassifiedSpan) As Boolean If symbol.IsMyNamespace(semanticModel.Compilation) Then classifiedSpan = New ClassifiedSpan(GetNameToken(node).Span, ClassificationTypeNames.Keyword) Return True End If Return False End Function Private Shared Function TryClassifyIdentifier( node As NameSyntax, semanticModel As SemanticModel, cancellationToken As CancellationToken, ByRef classifiedSpan As ClassifiedSpan) As Boolean ' Okay, it doesn't bind to anything. Dim identifierName = TryCast(node, IdentifierNameSyntax) If identifierName IsNot Nothing Then Dim token = identifierName.Identifier If token.HasMatchingText(SyntaxKind.FromKeyword) AndAlso semanticModel.SyntaxTree.IsExpressionContext(token.SpanStart, cancellationToken, semanticModel) Then ' Optimistically classify "From" as a keyword in expression contexts classifiedSpan = New ClassifiedSpan(token.Span, ClassificationTypeNames.Keyword) Return True ElseIf token.HasMatchingText(SyntaxKind.AsyncKeyword) OrElse token.HasMatchingText(SyntaxKind.IteratorKeyword) Then ' Optimistically classify "Async" or "Iterator" as a keyword in expression contexts If semanticModel.SyntaxTree.IsExpressionContext(token.SpanStart, cancellationToken, semanticModel) Then classifiedSpan = New ClassifiedSpan(token.Span, ClassificationTypeNames.Keyword) Return True End If End If End If Return False End Function Private Shared Function GetClassificationForField(fieldSymbol As IFieldSymbol) As String If fieldSymbol.IsConst Then Return If(fieldSymbol.ContainingType.IsEnumType(), ClassificationTypeNames.EnumMemberName, ClassificationTypeNames.ConstantName) End If Return ClassificationTypeNames.FieldName End Function Private Shared Function GetClassificationForLocal(localSymbol As ILocalSymbol) As String Return If(localSymbol.IsConst, ClassificationTypeNames.ConstantName, ClassificationTypeNames.LocalName) End Function Private Shared Function GetClassificationForMethod(node As NameSyntax, methodSymbol As IMethodSymbol) As String Select Case methodSymbol.MethodKind Case MethodKind.Constructor ' If node is member access or qualified name with explicit New on the right side, we should classify New as a keyword. If node.IsNewOnRightSideOfDotOrBang() Then Return ClassificationTypeNames.Keyword Else ' We bound to a constructor, but we weren't something like the 'New' in 'X.New'. ' This can happen when we're actually just binding the full node 'X.New'. In this ' case, don't return anything for this full node. We'll end up hitting the ' 'New' node as the worker walks down, and we'll classify it then. Return Nothing End If Case MethodKind.BuiltinOperator, MethodKind.UserDefinedOperator ' Operators are already classified syntactically. Return Nothing End Select Return If(methodSymbol.IsReducedExtension(), ClassificationTypeNames.ExtensionMethodName, ClassificationTypeNames.MethodName) End Function Private Shared Sub ClassifyModifiedIdentifier( modifiedIdentifier As ModifiedIdentifierSyntax, result As ArrayBuilder(Of ClassifiedSpan)) If modifiedIdentifier.ArrayBounds IsNot Nothing OrElse modifiedIdentifier.ArrayRankSpecifiers.Count > 0 OrElse modifiedIdentifier.Nullable.Kind <> SyntaxKind.None Then Return End If If modifiedIdentifier.IsParentKind(SyntaxKind.VariableDeclarator) AndAlso modifiedIdentifier.Parent.IsParentKind(SyntaxKind.FieldDeclaration) Then If DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax).AsClause Is Nothing AndAlso DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax).Initializer Is Nothing Then Dim token = modifiedIdentifier.Identifier If token.HasMatchingText(SyntaxKind.AsyncKeyword) OrElse token.HasMatchingText(SyntaxKind.IteratorKeyword) Then ' Optimistically classify "Async" or "Iterator" as a keyword result.Add(New ClassifiedSpan(token.Span, ClassificationTypeNames.Keyword)) Return End If End If End If End Sub Private Shared Function GetNameToken(node As NameSyntax) As SyntaxToken Select Case node.Kind Case SyntaxKind.IdentifierName Return DirectCast(node, IdentifierNameSyntax).Identifier Case SyntaxKind.GenericName Return DirectCast(node, GenericNameSyntax).Identifier Case SyntaxKind.QualifiedName Return DirectCast(node, QualifiedNameSyntax).Right.Identifier Case Else Throw New NotSupportedException() End Select End Function Private Shared Sub ClassifyMethodStatement(methodStatement As MethodStatementSyntax, semanticModel As SemanticModel, result As ArrayBuilder(Of ClassifiedSpan)) ' Ensure that extension method declarations are classified properly. ' Note that the method statement name is likely already classified as a method name ' by the syntactic classifier. However, there isn't away to determine whether a VB ' method declaration is an extension method syntactically. Dim methodSymbol = semanticModel.GetDeclaredSymbol(methodStatement) If methodSymbol IsNot Nothing AndAlso methodSymbol.IsExtensionMethod Then result.Add(New ClassifiedSpan(methodStatement.Identifier.Span, ClassificationTypeNames.ExtensionMethodName)) End If End Sub Private Shared Sub ClassifyLabelSyntax( node As LabelSyntax, result As ArrayBuilder(Of ClassifiedSpan)) result.Add(New ClassifiedSpan(node.LabelToken.Span, ClassificationTypeNames.LabelName)) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Classification Imports Microsoft.CodeAnalysis.Classification.Classifiers Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Classification.Classifiers Friend Class NameSyntaxClassifier Inherits AbstractNameSyntaxClassifier Public Overrides ReadOnly Property SyntaxNodeTypes As ImmutableArray(Of Type) = ImmutableArray.Create( GetType(NameSyntax), GetType(ModifiedIdentifierSyntax), GetType(MethodStatementSyntax), GetType(LabelSyntax)) Public Overrides Sub AddClassifications( workspace As Workspace, syntax As SyntaxNode, semanticModel As SemanticModel, result As ArrayBuilder(Of ClassifiedSpan), cancellationToken As CancellationToken) Dim nameSyntax = TryCast(syntax, NameSyntax) If nameSyntax IsNot Nothing Then ClassifyNameSyntax(nameSyntax, semanticModel, result, cancellationToken) Return End If Dim modifiedIdentifier = TryCast(syntax, ModifiedIdentifierSyntax) If modifiedIdentifier IsNot Nothing Then ClassifyModifiedIdentifier(modifiedIdentifier, result) Return End If Dim methodStatement = TryCast(syntax, MethodStatementSyntax) If methodStatement IsNot Nothing Then ClassifyMethodStatement(methodStatement, semanticModel, result) Return End If Dim labelSyntax = TryCast(syntax, LabelSyntax) If labelSyntax IsNot Nothing Then ClassifyLabelSyntax(labelSyntax, result) Return End If End Sub Protected Overrides Function GetRightmostNameArity(node As SyntaxNode) As Integer? If TypeOf (node) Is ExpressionSyntax Then Return DirectCast(node, ExpressionSyntax).GetRightmostName()?.Arity End If Return Nothing End Function Protected Overrides Function IsParentAnAttribute(node As SyntaxNode) As Boolean Return node.IsParentKind(SyntaxKind.Attribute) End Function Private Sub ClassifyNameSyntax( node As NameSyntax, semanticModel As SemanticModel, result As ArrayBuilder(Of ClassifiedSpan), cancellationToken As CancellationToken) Dim classifiedSpan As ClassifiedSpan Dim symbolInfo = semanticModel.GetSymbolInfo(node, cancellationToken) Dim symbol = TryGetSymbol(node, symbolInfo, semanticModel) If symbol Is Nothing Then If TryClassifyIdentifier(node, semanticModel, cancellationToken, classifiedSpan) Then result.Add(classifiedSpan) End If Return End If If TryClassifyMyNamespace(node, symbol, semanticModel, classifiedSpan) Then result.Add(classifiedSpan) ElseIf TryClassifySymbol(node, symbol, classifiedSpan) Then result.Add(classifiedSpan) ' Additionally classify static symbols TryClassifyStaticSymbol(symbol, classifiedSpan.TextSpan, result) End If End Sub Private Shared Function TryClassifySymbol( node As NameSyntax, symbol As ISymbol, ByRef classifiedSpan As ClassifiedSpan) As Boolean Select Case symbol.Kind Case SymbolKind.Namespace ' Do not classify the Global namespace. It is already syntactically classified as a keyword. ' Also, we ignore QualifiedNameSyntax nodes since we want to classify individual name parts. If Not node.IsKind(SyntaxKind.GlobalName) AndAlso TypeOf node Is IdentifierNameSyntax Then classifiedSpan = New ClassifiedSpan(GetNameToken(node).Span, ClassificationTypeNames.NamespaceName) Return True End If Case SymbolKind.Method Dim classification = GetClassificationForMethod(node, DirectCast(symbol, IMethodSymbol)) If classification IsNot Nothing Then classifiedSpan = New ClassifiedSpan(GetNameToken(node).Span, classification) Return True End If Case SymbolKind.Event classifiedSpan = New ClassifiedSpan(GetNameToken(node).Span, ClassificationTypeNames.EventName) Return True Case SymbolKind.Property classifiedSpan = New ClassifiedSpan(GetNameToken(node).Span, ClassificationTypeNames.PropertyName) Return True Case SymbolKind.Field Dim classification = GetClassificationForField(DirectCast(symbol, IFieldSymbol)) If classification IsNot Nothing Then classifiedSpan = New ClassifiedSpan(GetNameToken(node).Span, classification) Return True End If Case SymbolKind.Parameter classifiedSpan = New ClassifiedSpan(GetNameToken(node).Span, ClassificationTypeNames.ParameterName) Return True Case SymbolKind.Local Dim classification = GetClassificationForLocal(DirectCast(symbol, ILocalSymbol)) If classification IsNot Nothing Then classifiedSpan = New ClassifiedSpan(GetNameToken(node).Span, classification) Return True End If End Select Dim type = TryCast(symbol, ITypeSymbol) If type IsNot Nothing Then Dim classification = GetClassificationForType(type) If classification IsNot Nothing Then Dim token = GetNameToken(node) classifiedSpan = New ClassifiedSpan(token.Span, classification) Return True End If End If Return False End Function Private Shared Function TryClassifyMyNamespace( node As NameSyntax, symbol As ISymbol, semanticModel As SemanticModel, ByRef classifiedSpan As ClassifiedSpan) As Boolean If symbol.IsMyNamespace(semanticModel.Compilation) Then classifiedSpan = New ClassifiedSpan(GetNameToken(node).Span, ClassificationTypeNames.Keyword) Return True End If Return False End Function Private Shared Function TryClassifyIdentifier( node As NameSyntax, semanticModel As SemanticModel, cancellationToken As CancellationToken, ByRef classifiedSpan As ClassifiedSpan) As Boolean ' Okay, it doesn't bind to anything. Dim identifierName = TryCast(node, IdentifierNameSyntax) If identifierName IsNot Nothing Then Dim token = identifierName.Identifier If token.HasMatchingText(SyntaxKind.FromKeyword) AndAlso semanticModel.SyntaxTree.IsExpressionContext(token.SpanStart, cancellationToken, semanticModel) Then ' Optimistically classify "From" as a keyword in expression contexts classifiedSpan = New ClassifiedSpan(token.Span, ClassificationTypeNames.Keyword) Return True ElseIf token.HasMatchingText(SyntaxKind.AsyncKeyword) OrElse token.HasMatchingText(SyntaxKind.IteratorKeyword) Then ' Optimistically classify "Async" or "Iterator" as a keyword in expression contexts If semanticModel.SyntaxTree.IsExpressionContext(token.SpanStart, cancellationToken, semanticModel) Then classifiedSpan = New ClassifiedSpan(token.Span, ClassificationTypeNames.Keyword) Return True End If End If End If Return False End Function Private Shared Function GetClassificationForField(fieldSymbol As IFieldSymbol) As String If fieldSymbol.IsConst Then Return If(fieldSymbol.ContainingType.IsEnumType(), ClassificationTypeNames.EnumMemberName, ClassificationTypeNames.ConstantName) End If Return ClassificationTypeNames.FieldName End Function Private Shared Function GetClassificationForLocal(localSymbol As ILocalSymbol) As String Return If(localSymbol.IsConst, ClassificationTypeNames.ConstantName, ClassificationTypeNames.LocalName) End Function Private Shared Function GetClassificationForMethod(node As NameSyntax, methodSymbol As IMethodSymbol) As String Select Case methodSymbol.MethodKind Case MethodKind.Constructor ' If node is member access or qualified name with explicit New on the right side, we should classify New as a keyword. If node.IsNewOnRightSideOfDotOrBang() Then Return ClassificationTypeNames.Keyword Else ' We bound to a constructor, but we weren't something like the 'New' in 'X.New'. ' This can happen when we're actually just binding the full node 'X.New'. In this ' case, don't return anything for this full node. We'll end up hitting the ' 'New' node as the worker walks down, and we'll classify it then. Return Nothing End If Case MethodKind.BuiltinOperator, MethodKind.UserDefinedOperator ' Operators are already classified syntactically. Return Nothing End Select Return If(methodSymbol.IsReducedExtension(), ClassificationTypeNames.ExtensionMethodName, ClassificationTypeNames.MethodName) End Function Private Shared Sub ClassifyModifiedIdentifier( modifiedIdentifier As ModifiedIdentifierSyntax, result As ArrayBuilder(Of ClassifiedSpan)) If modifiedIdentifier.ArrayBounds IsNot Nothing OrElse modifiedIdentifier.ArrayRankSpecifiers.Count > 0 OrElse modifiedIdentifier.Nullable.Kind <> SyntaxKind.None Then Return End If If modifiedIdentifier.IsParentKind(SyntaxKind.VariableDeclarator) AndAlso modifiedIdentifier.Parent.IsParentKind(SyntaxKind.FieldDeclaration) Then If DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax).AsClause Is Nothing AndAlso DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax).Initializer Is Nothing Then Dim token = modifiedIdentifier.Identifier If token.HasMatchingText(SyntaxKind.AsyncKeyword) OrElse token.HasMatchingText(SyntaxKind.IteratorKeyword) Then ' Optimistically classify "Async" or "Iterator" as a keyword result.Add(New ClassifiedSpan(token.Span, ClassificationTypeNames.Keyword)) Return End If End If End If End Sub Private Shared Function GetNameToken(node As NameSyntax) As SyntaxToken Select Case node.Kind Case SyntaxKind.IdentifierName Return DirectCast(node, IdentifierNameSyntax).Identifier Case SyntaxKind.GenericName Return DirectCast(node, GenericNameSyntax).Identifier Case SyntaxKind.QualifiedName Return DirectCast(node, QualifiedNameSyntax).Right.Identifier Case Else Throw New NotSupportedException() End Select End Function Private Shared Sub ClassifyMethodStatement(methodStatement As MethodStatementSyntax, semanticModel As SemanticModel, result As ArrayBuilder(Of ClassifiedSpan)) ' Ensure that extension method declarations are classified properly. ' Note that the method statement name is likely already classified as a method name ' by the syntactic classifier. However, there isn't away to determine whether a VB ' method declaration is an extension method syntactically. Dim methodSymbol = semanticModel.GetDeclaredSymbol(methodStatement) If methodSymbol IsNot Nothing AndAlso methodSymbol.IsExtensionMethod Then result.Add(New ClassifiedSpan(methodStatement.Identifier.Span, ClassificationTypeNames.ExtensionMethodName)) End If End Sub Private Shared Sub ClassifyLabelSyntax( node As LabelSyntax, result As ArrayBuilder(Of ClassifiedSpan)) result.Add(New ClassifiedSpan(node.LabelToken.Span, ClassificationTypeNames.LabelName)) End Sub End Class End Namespace
-1
dotnet/roslyn
55,364
Fix crash with convert namespace
Oopsie.
CyrusNajmabadi
2021-08-03T02:29:24Z
2021-08-03T12:57:53Z
a80a5868188242800f4615dc51ab30ed5e9eaf76
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
Fix crash with convert namespace. Oopsie.
./src/Workspaces/Core/Desktop/xlf/WorkspaceDesktopResources.ru.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="ru" original="../WorkspaceDesktopResources.resx"> <body> <trans-unit id="Invalid_assembly_name"> <source>Invalid assembly name</source> <target state="translated">Недопустимое имя сборки</target> <note /> </trans-unit> <trans-unit id="Invalid_characters_in_assembly_name"> <source>Invalid characters in assembly name</source> <target state="translated">Недопустимые символы в имени сборки</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="ru" original="../WorkspaceDesktopResources.resx"> <body> <trans-unit id="Invalid_assembly_name"> <source>Invalid assembly name</source> <target state="translated">Недопустимое имя сборки</target> <note /> </trans-unit> <trans-unit id="Invalid_characters_in_assembly_name"> <source>Invalid characters in assembly name</source> <target state="translated">Недопустимые символы в имени сборки</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,364
Fix crash with convert namespace
Oopsie.
CyrusNajmabadi
2021-08-03T02:29:24Z
2021-08-03T12:57:53Z
a80a5868188242800f4615dc51ab30ed5e9eaf76
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
Fix crash with convert namespace. Oopsie.
./src/EditorFeatures/Test/CodeGeneration/ExpressionPrecedenceGenerationTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeGeneration { [Trait(Traits.Feature, Traits.Features.CodeGeneration)] public class ExpressionPrecedenceGenerationTests : AbstractCodeGenerationTests { [Fact] public void TestAddMultiplyPrecedence1() { Test( f => f.MultiplyExpression( f.AddExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) + (2)) * (3)", csSimple: "(1 + 2) * 3", vb: "((1) + (2)) * (3)", vbSimple: "(1 + 2) * 3"); } [Fact] public void TestAddMultiplyPrecedence2() { Test( f => f.AddExpression( f.MultiplyExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) * (2)) + (3)", csSimple: "1 * 2 + 3", vb: "((1) * (2)) + (3)", vbSimple: "1 * 2 + 3"); } [Fact] public void TestAddMultiplyPrecedence3() { Test( f => f.MultiplyExpression( f.LiteralExpression(1), f.AddExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) * ((2) + (3))", csSimple: "1 * (2 + 3)", vb: "(1) * ((2) + (3))", vbSimple: "1 * (2 + 3)"); } [Fact] public void TestAddMultiplyPrecedence4() { Test( f => f.AddExpression( f.LiteralExpression(1), f.MultiplyExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) + ((2) * (3))", csSimple: "1 + 2 * 3", vb: "(1) + ((2) * (3))", vbSimple: "1 + 2 * 3"); } [Fact] public void TestBitwiseAndOrPrecedence1() { Test( f => f.BitwiseAndExpression( f.BitwiseOrExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) | (2)) & (3)", csSimple: "(1 | 2) & 3", vb: "((1) Or (2)) And (3)", vbSimple: "(1 Or 2) And 3"); } [Fact] public void TestBitwiseAndOrPrecedence2() { Test( f => f.BitwiseOrExpression( f.BitwiseAndExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) & (2)) | (3)", csSimple: "1 & 2 | 3", vb: "((1) And (2)) Or (3)", vbSimple: "1 And 2 Or 3"); } [Fact] public void TestBitwiseAndOrPrecedence3() { Test( f => f.BitwiseAndExpression( f.LiteralExpression(1), f.BitwiseOrExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) & ((2) | (3))", csSimple: "1 & (2 | 3)", vb: "(1) And ((2) Or (3))", vbSimple: "1 And (2 Or 3)"); } [Fact] public void TestBitwiseAndOrPrecedence4() { Test( f => f.BitwiseOrExpression( f.LiteralExpression(1), f.BitwiseAndExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) | ((2) & (3))", csSimple: "1 | 2 & 3", vb: "(1) Or ((2) And (3))", vbSimple: "1 Or 2 And 3"); } [Fact] public void TestLogicalAndOrPrecedence1() { Test( f => f.LogicalAndExpression( f.LogicalOrExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) || (2)) && (3)", csSimple: "(1 || 2) && 3", vb: "((1) OrElse (2)) AndAlso (3)", vbSimple: "(1 OrElse 2) AndAlso 3"); } [Fact] public void TestLogicalAndOrPrecedence2() { Test( f => f.LogicalOrExpression( f.LogicalAndExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) && (2)) || (3)", csSimple: "1 && 2 || 3", vb: "((1) AndAlso (2)) OrElse (3)", vbSimple: "1 AndAlso 2 OrElse 3"); } [Fact] public void TestLogicalAndOrPrecedence3() { Test( f => f.LogicalAndExpression( f.LiteralExpression(1), f.LogicalOrExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) && ((2) || (3))", csSimple: "1 && (2 || 3)", vb: "(1) AndAlso ((2) OrElse (3))", vbSimple: "1 AndAlso (2 OrElse 3)"); } [Fact] public void TestLogicalAndOrPrecedence4() { Test( f => f.LogicalOrExpression( f.LiteralExpression(1), f.LogicalAndExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) || ((2) && (3))", csSimple: "1 || 2 && 3", vb: "(1) OrElse ((2) AndAlso (3))", vbSimple: "1 OrElse 2 AndAlso 3"); } [Fact] public void TestMemberAccessOffOfAdd1() { Test( f => f.MemberAccessExpression( f.AddExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.IdentifierName("M")), cs: "((1) + (2)).M", csSimple: "(1 + 2).M", vb: "((1) + (2)).M", vbSimple: "(1 + 2).M"); } [Fact] public void TestConditionalExpression1() { Test( f => f.ConditionalExpression( f.AssignmentStatement( f.IdentifierName("E1"), f.IdentifierName("E2")), f.IdentifierName("T"), f.IdentifierName("F")), cs: "(E1 = (E2)) ? (T) : (F)", csSimple: "(E1 = E2) ? T : F", vb: null, vbSimple: null); } [Fact] public void TestConditionalExpression2() { Test( f => f.AddExpression( f.ConditionalExpression( f.IdentifierName("E1"), f.IdentifierName("T1"), f.IdentifierName("F1")), f.ConditionalExpression( f.IdentifierName("E2"), f.IdentifierName("T2"), f.IdentifierName("F2"))), cs: "((E1) ? (T1) : (F1)) + ((E2) ? (T2) : (F2))", csSimple: "(E1 ? T1 : F1) + (E2 ? T2 : F2)", vb: null, vbSimple: null); } [Fact] public void TestMemberAccessOffOfElementAccess() { Test( f => f.ElementAccessExpression( f.AddExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.Argument(f.IdentifierName("M"))), cs: "((1) + (2))[M]", csSimple: "(1 + 2)[M]", vb: "((1) + (2))(M)", vbSimple: "(1 + 2)(M)"); } [Fact] public void TestMemberAccessOffOfIsExpression() { Test( f => f.MemberAccessExpression( f.IsTypeExpression( f.IdentifierName("a"), CreateClass("SomeType")), f.IdentifierName("M")), cs: "((a) is SomeType).M", csSimple: "(a is SomeType).M", vb: "(TypeOf (a) Is SomeType).M", vbSimple: "(TypeOf a Is SomeType).M"); } [Fact] public void TestIsOfMemberAccessExpression() { Test( f => f.IsTypeExpression( f.MemberAccessExpression( f.IdentifierName("a"), f.IdentifierName("M")), CreateClass("SomeType")), cs: "(a.M) is SomeType", csSimple: "a.M is SomeType", vb: "TypeOf (a.M) Is SomeType", vbSimple: "TypeOf a.M Is SomeType"); } [Fact] public void TestMemberAccessOffOfAsExpression() { Test( f => f.MemberAccessExpression( f.TryCastExpression( f.IdentifierName("a"), CreateClass("SomeType")), f.IdentifierName("M")), cs: "((a) as SomeType).M", csSimple: "(a as SomeType).M", vb: "(TryCast(a, SomeType)).M", vbSimple: "TryCast(a, SomeType).M"); } [Fact] public void TestAsOfMemberAccessExpression() { Test( f => f.TryCastExpression( f.MemberAccessExpression( f.IdentifierName("a"), f.IdentifierName("M")), CreateClass("SomeType")), cs: "(a.M) as SomeType", csSimple: "a.M as SomeType", vb: "TryCast(a.M, SomeType)", vbSimple: "TryCast(a.M, SomeType)"); } [Fact] public void TestMemberAccessOffOfNotExpression() { Test( f => f.MemberAccessExpression( f.LogicalNotExpression( f.IdentifierName("a")), f.IdentifierName("M")), cs: "(!(a)).M", csSimple: "(!a).M", vb: "(Not (a)).M", vbSimple: "(Not a).M"); } [Fact] public void TestNotOfMemberAccessExpression() { Test( f => f.LogicalNotExpression( f.MemberAccessExpression( f.IdentifierName("a"), f.IdentifierName("M"))), cs: "!(a.M)", csSimple: "!a.M", vb: "Not (a.M)", vbSimple: "Not a.M"); } [Fact] public void TestMemberAccessOffOfCastExpression() { Test( f => f.MemberAccessExpression( f.CastExpression( CreateClass("SomeType"), f.IdentifierName("a")), f.IdentifierName("M")), cs: "((SomeType)(a)).M", csSimple: "((SomeType)a).M", vb: "(DirectCast(a, SomeType)).M", vbSimple: "DirectCast(a, SomeType).M"); } [Fact] public void TestCastOfAddExpression() { Test( f => f.CastExpression( CreateClass("SomeType"), f.AddExpression( f.IdentifierName("a"), f.IdentifierName("b"))), cs: "(SomeType)((a) + (b))", csSimple: "(SomeType)(a + b)", vb: "DirectCast((a) + (b), SomeType)", vbSimple: "DirectCast(a + b, SomeType)"); } [Fact] public void TestNegateOfAddExpression() { Test( f => f.NegateExpression( f.AddExpression( f.IdentifierName("a"), f.IdentifierName("b"))), cs: "-((a) + (b))", csSimple: "-(a + b)", vb: "-((a) + (b))", vbSimple: "-(a + b)"); } [Fact] public void TestMemberAccessOffOfNegate() { Test( f => f.MemberAccessExpression( f.NegateExpression( f.IdentifierName("a")), f.IdentifierName("M")), cs: "(-(a)).M", csSimple: "(-a).M", vb: "(-(a)).M", vbSimple: "(-a).M"); } [Fact] public void TestNegateOfMemberAccess() { Test(f => f.NegateExpression( f.MemberAccessExpression( f.IdentifierName("a"), f.IdentifierName("M"))), cs: "-(a.M)", csSimple: "-a.M", vb: "-(a.M)", vbSimple: "-a.M"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeGeneration { [Trait(Traits.Feature, Traits.Features.CodeGeneration)] public class ExpressionPrecedenceGenerationTests : AbstractCodeGenerationTests { [Fact] public void TestAddMultiplyPrecedence1() { Test( f => f.MultiplyExpression( f.AddExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) + (2)) * (3)", csSimple: "(1 + 2) * 3", vb: "((1) + (2)) * (3)", vbSimple: "(1 + 2) * 3"); } [Fact] public void TestAddMultiplyPrecedence2() { Test( f => f.AddExpression( f.MultiplyExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) * (2)) + (3)", csSimple: "1 * 2 + 3", vb: "((1) * (2)) + (3)", vbSimple: "1 * 2 + 3"); } [Fact] public void TestAddMultiplyPrecedence3() { Test( f => f.MultiplyExpression( f.LiteralExpression(1), f.AddExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) * ((2) + (3))", csSimple: "1 * (2 + 3)", vb: "(1) * ((2) + (3))", vbSimple: "1 * (2 + 3)"); } [Fact] public void TestAddMultiplyPrecedence4() { Test( f => f.AddExpression( f.LiteralExpression(1), f.MultiplyExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) + ((2) * (3))", csSimple: "1 + 2 * 3", vb: "(1) + ((2) * (3))", vbSimple: "1 + 2 * 3"); } [Fact] public void TestBitwiseAndOrPrecedence1() { Test( f => f.BitwiseAndExpression( f.BitwiseOrExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) | (2)) & (3)", csSimple: "(1 | 2) & 3", vb: "((1) Or (2)) And (3)", vbSimple: "(1 Or 2) And 3"); } [Fact] public void TestBitwiseAndOrPrecedence2() { Test( f => f.BitwiseOrExpression( f.BitwiseAndExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) & (2)) | (3)", csSimple: "1 & 2 | 3", vb: "((1) And (2)) Or (3)", vbSimple: "1 And 2 Or 3"); } [Fact] public void TestBitwiseAndOrPrecedence3() { Test( f => f.BitwiseAndExpression( f.LiteralExpression(1), f.BitwiseOrExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) & ((2) | (3))", csSimple: "1 & (2 | 3)", vb: "(1) And ((2) Or (3))", vbSimple: "1 And (2 Or 3)"); } [Fact] public void TestBitwiseAndOrPrecedence4() { Test( f => f.BitwiseOrExpression( f.LiteralExpression(1), f.BitwiseAndExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) | ((2) & (3))", csSimple: "1 | 2 & 3", vb: "(1) Or ((2) And (3))", vbSimple: "1 Or 2 And 3"); } [Fact] public void TestLogicalAndOrPrecedence1() { Test( f => f.LogicalAndExpression( f.LogicalOrExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) || (2)) && (3)", csSimple: "(1 || 2) && 3", vb: "((1) OrElse (2)) AndAlso (3)", vbSimple: "(1 OrElse 2) AndAlso 3"); } [Fact] public void TestLogicalAndOrPrecedence2() { Test( f => f.LogicalOrExpression( f.LogicalAndExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) && (2)) || (3)", csSimple: "1 && 2 || 3", vb: "((1) AndAlso (2)) OrElse (3)", vbSimple: "1 AndAlso 2 OrElse 3"); } [Fact] public void TestLogicalAndOrPrecedence3() { Test( f => f.LogicalAndExpression( f.LiteralExpression(1), f.LogicalOrExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) && ((2) || (3))", csSimple: "1 && (2 || 3)", vb: "(1) AndAlso ((2) OrElse (3))", vbSimple: "1 AndAlso (2 OrElse 3)"); } [Fact] public void TestLogicalAndOrPrecedence4() { Test( f => f.LogicalOrExpression( f.LiteralExpression(1), f.LogicalAndExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) || ((2) && (3))", csSimple: "1 || 2 && 3", vb: "(1) OrElse ((2) AndAlso (3))", vbSimple: "1 OrElse 2 AndAlso 3"); } [Fact] public void TestMemberAccessOffOfAdd1() { Test( f => f.MemberAccessExpression( f.AddExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.IdentifierName("M")), cs: "((1) + (2)).M", csSimple: "(1 + 2).M", vb: "((1) + (2)).M", vbSimple: "(1 + 2).M"); } [Fact] public void TestConditionalExpression1() { Test( f => f.ConditionalExpression( f.AssignmentStatement( f.IdentifierName("E1"), f.IdentifierName("E2")), f.IdentifierName("T"), f.IdentifierName("F")), cs: "(E1 = (E2)) ? (T) : (F)", csSimple: "(E1 = E2) ? T : F", vb: null, vbSimple: null); } [Fact] public void TestConditionalExpression2() { Test( f => f.AddExpression( f.ConditionalExpression( f.IdentifierName("E1"), f.IdentifierName("T1"), f.IdentifierName("F1")), f.ConditionalExpression( f.IdentifierName("E2"), f.IdentifierName("T2"), f.IdentifierName("F2"))), cs: "((E1) ? (T1) : (F1)) + ((E2) ? (T2) : (F2))", csSimple: "(E1 ? T1 : F1) + (E2 ? T2 : F2)", vb: null, vbSimple: null); } [Fact] public void TestMemberAccessOffOfElementAccess() { Test( f => f.ElementAccessExpression( f.AddExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.Argument(f.IdentifierName("M"))), cs: "((1) + (2))[M]", csSimple: "(1 + 2)[M]", vb: "((1) + (2))(M)", vbSimple: "(1 + 2)(M)"); } [Fact] public void TestMemberAccessOffOfIsExpression() { Test( f => f.MemberAccessExpression( f.IsTypeExpression( f.IdentifierName("a"), CreateClass("SomeType")), f.IdentifierName("M")), cs: "((a) is SomeType).M", csSimple: "(a is SomeType).M", vb: "(TypeOf (a) Is SomeType).M", vbSimple: "(TypeOf a Is SomeType).M"); } [Fact] public void TestIsOfMemberAccessExpression() { Test( f => f.IsTypeExpression( f.MemberAccessExpression( f.IdentifierName("a"), f.IdentifierName("M")), CreateClass("SomeType")), cs: "(a.M) is SomeType", csSimple: "a.M is SomeType", vb: "TypeOf (a.M) Is SomeType", vbSimple: "TypeOf a.M Is SomeType"); } [Fact] public void TestMemberAccessOffOfAsExpression() { Test( f => f.MemberAccessExpression( f.TryCastExpression( f.IdentifierName("a"), CreateClass("SomeType")), f.IdentifierName("M")), cs: "((a) as SomeType).M", csSimple: "(a as SomeType).M", vb: "(TryCast(a, SomeType)).M", vbSimple: "TryCast(a, SomeType).M"); } [Fact] public void TestAsOfMemberAccessExpression() { Test( f => f.TryCastExpression( f.MemberAccessExpression( f.IdentifierName("a"), f.IdentifierName("M")), CreateClass("SomeType")), cs: "(a.M) as SomeType", csSimple: "a.M as SomeType", vb: "TryCast(a.M, SomeType)", vbSimple: "TryCast(a.M, SomeType)"); } [Fact] public void TestMemberAccessOffOfNotExpression() { Test( f => f.MemberAccessExpression( f.LogicalNotExpression( f.IdentifierName("a")), f.IdentifierName("M")), cs: "(!(a)).M", csSimple: "(!a).M", vb: "(Not (a)).M", vbSimple: "(Not a).M"); } [Fact] public void TestNotOfMemberAccessExpression() { Test( f => f.LogicalNotExpression( f.MemberAccessExpression( f.IdentifierName("a"), f.IdentifierName("M"))), cs: "!(a.M)", csSimple: "!a.M", vb: "Not (a.M)", vbSimple: "Not a.M"); } [Fact] public void TestMemberAccessOffOfCastExpression() { Test( f => f.MemberAccessExpression( f.CastExpression( CreateClass("SomeType"), f.IdentifierName("a")), f.IdentifierName("M")), cs: "((SomeType)(a)).M", csSimple: "((SomeType)a).M", vb: "(DirectCast(a, SomeType)).M", vbSimple: "DirectCast(a, SomeType).M"); } [Fact] public void TestCastOfAddExpression() { Test( f => f.CastExpression( CreateClass("SomeType"), f.AddExpression( f.IdentifierName("a"), f.IdentifierName("b"))), cs: "(SomeType)((a) + (b))", csSimple: "(SomeType)(a + b)", vb: "DirectCast((a) + (b), SomeType)", vbSimple: "DirectCast(a + b, SomeType)"); } [Fact] public void TestNegateOfAddExpression() { Test( f => f.NegateExpression( f.AddExpression( f.IdentifierName("a"), f.IdentifierName("b"))), cs: "-((a) + (b))", csSimple: "-(a + b)", vb: "-((a) + (b))", vbSimple: "-(a + b)"); } [Fact] public void TestMemberAccessOffOfNegate() { Test( f => f.MemberAccessExpression( f.NegateExpression( f.IdentifierName("a")), f.IdentifierName("M")), cs: "(-(a)).M", csSimple: "(-a).M", vb: "(-(a)).M", vbSimple: "(-a).M"); } [Fact] public void TestNegateOfMemberAccess() { Test(f => f.NegateExpression( f.MemberAccessExpression( f.IdentifierName("a"), f.IdentifierName("M"))), cs: "-(a.M)", csSimple: "-a.M", vb: "-(a.M)", vbSimple: "-a.M"); } } }
-1
dotnet/roslyn
55,364
Fix crash with convert namespace
Oopsie.
CyrusNajmabadi
2021-08-03T02:29:24Z
2021-08-03T12:57:53Z
a80a5868188242800f4615dc51ab30ed5e9eaf76
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
Fix crash with convert namespace. Oopsie.
./docs/compilers/Design/Closure Conversion.md
Closure Conversion in C# ======================== This document describes the how the C# compiler turns closures (anonymous and local functions) into top-level functions (methods). If you aren't familiar with closure conversion, the introduction contains a walkthrough describing the transformations. Otherwise, you can skip to the Internals section to see how the actual transformations are done in Roslyn. # Introduction In the simplest case, this is trivial -- all closures are simply given new, unmentionable names and are lifted to the top level as static methods. The complexity comes when a closure captures a variable from its surrounding scope. At that point, we must not only move the closure to a method, we also have to create an "environment" to hold its captured variables and somehow deliver that environment into the context of the rewritten method. There are two possible strategies that are both employed in different situations in the compiler. The first strategy is to pass the environment as an extra parameter to all method calls to the closure. For example, ```csharp void M() { int x = 0; int Local() => x + 1; } ``` becomes ```csharp void M() { var env = new Environment(); env.x = 0; <>__Local(env); } static int <>__Local(Environment env) { return env.x + 1; } struct Environment { int x; } ``` Instead of referring to local variables, the rewritten closure now references fields on the environment. A `struct` environment is used to prevent extra allocations, since `struct`s are normally allocated on the stack. However, the astute reader may notice a problem with this conversion -- `struct`s are always copied when passed as arguments to a function call! This means that writes to the environment field will not always propagate back to the local variable in the method `M`. To work around this flaw, all Environment variables are passed as `ref` arguments to the rewritten closures. The second strategy for rewriting closures is necessary when the closure interacts with external code. Consider the following program: ```csharp void M(IEnumerable<int> e) { int x = 0; var positive = e.Where(n => n > 0); ... } ``` In this case we're passing a closure to the `IEnumerable<int>.Where` function, which is expecting a delegate of type `Func<int, bool>`. Note that that delegate type is immutable -- it is defined in external code and cannot be changed. Therefore, rewriting external callsites to take an extra `Environment` argument is impossible. We have to choose a different strategy for acquiring the environment. What we do is use a `class` Environment for cases like this. With a `class` Environment, the previous environment can be rewritten as follows: ```csharp void M(IEnumerable<int> e) { var env = new Environment(); env.x = 0; var positive = e.Where(env.<>__Local); } class Environment { int x; bool <>__Local(int n) => n > 0; } ``` Since the local variables are now fields in a class instance we can keep the same delegate signature and rely on field access to read and write the free variables. This covers the transformations C# performs at a high level. The following section covers how these transformations are performed in detail. # Internals There are two phases at the top level of closure conversion. The first phase, Analysis, is responsible for building an AnalysisResult data structure which contains all information necessary to rewrite all closures. The second phase, Rewriting, actually performs the aforementioned rewriting by replacing and adding BoundNodes to the Bound Tree. The most important contract between these two phases is that the Analysis phase performs no modifications to the Bound Tree and the Rewriting phase performs no computation and contains no logic aside from a simple mechanical modification of the Bound Tree based on the AnalysisResult. ## Analysis In this phase we build an AnalysisResult, which is a tree structure that exactly represents the state mapping from the original program to the closure-converted form. For example, the following program ```csharp void M() { int x = 0; int Local() => x + 1; { int y = 0; int z = 0; int Local2() => Local() + y; z++; Local2(); } Local(); } ``` Would produce a tree similar to ``` +-------------------------------------+ |Captured: Closures: | |int x int Local() | |int Local() | | | | +--------------------------------+ | | | Captured: Closures: | | | | int y int Local2() | | | | | | | +--------------------------------+ | +-------------------------------------+ ``` To create this AnalysisResult there are multiple passes. The first pass gathers information by constructing a naive tree of scopes, closures, and captured variables. The result is a tree of nested scopes, where each scope lists the captured variables declared in the scope and the closures in that scope. The first pass must first gather information since most rewriting decisions, like what Environment type to use for the closures or what the rewritten closure signature will be, are dependent on context from the entire method. Information about captured variables are stored on instances of the `CapturedVariable` class, which holds information about the Symbol that was captured and rewriting information like the `SynthesizedLocal` that will replace the variable post-rewriting. Similarly, closures will be stored in instances of the `Closure` class, which contain both the original Symbol and the synthesized type or method created for the closure. All of these classes are mutable since it's expected that later passes will fill in more rewriting information using the structure gathered from the earlier passes. For instance, in the previous example we need to walk the tree to generate an Environment for the closures `Closure`, resulting in something like the following: ``` Closure ------- Name: Local Generated Sig: int <>_Local(ref <>_Env1) Environment: - Captures: 'int x' - Name: <>_Env1 - Type: Struct Name: Local2 Generated Sig: int <>_Local(ref <>_Env2, ref <>_Env1) Environment: - Captures: 'int y', 'ref <>_Env1' - Name: <>_Env2 - Type: Struct ``` This result would be generated by each piece filling in required info: first filling in all the capture lists, then deciding the Environment type based on the capture list, then generating the end signature based on the environment type and final capture list. Some further details of analysis calculations can be found below: **TODO** _Add details for each analysis phase as implementation is fleshed out_ * Deciding what environment type is necessary for each closure. An environment can be a struct unless one of the following things is true: 1. The closure is converted to delegate. 2. The closure captures a variable which is captured by a closure that cannot have a `struct` Environment. 3. A reference to the closure is captured by a closure that cannot have a `struct` Environment. * Creating `SynthesizedLocal`s for hoisted captured variables and captured Environment references * Assigning rewritten names, signatures, and type parameters to each closure ## Optimization The final passes are optimization passes. They attempt to simplify the tree by removing intermediate scopes with no captured variables and otherwise correcting the tree to create the most efficient rewritten form. Optimization opportunities could include running escape analysis to determine if capture hoisting could be done via copy or done in a narrower scope. ## Rewriting The rewriting phase simply walks the bound tree and, at each new scope, checks to see if the AnalysisResult contains a scope with rewriting information to process. If so, locals and closures are replaced with the substitutions provided by the tree. Practically, this means that the tree contains: 1. A list of synthesized locals to add to each scope. 2. A set of proxies to replace existing symbols. 3. A list of synthesized methods and types to add to the enclosing type.
Closure Conversion in C# ======================== This document describes the how the C# compiler turns closures (anonymous and local functions) into top-level functions (methods). If you aren't familiar with closure conversion, the introduction contains a walkthrough describing the transformations. Otherwise, you can skip to the Internals section to see how the actual transformations are done in Roslyn. # Introduction In the simplest case, this is trivial -- all closures are simply given new, unmentionable names and are lifted to the top level as static methods. The complexity comes when a closure captures a variable from its surrounding scope. At that point, we must not only move the closure to a method, we also have to create an "environment" to hold its captured variables and somehow deliver that environment into the context of the rewritten method. There are two possible strategies that are both employed in different situations in the compiler. The first strategy is to pass the environment as an extra parameter to all method calls to the closure. For example, ```csharp void M() { int x = 0; int Local() => x + 1; } ``` becomes ```csharp void M() { var env = new Environment(); env.x = 0; <>__Local(env); } static int <>__Local(Environment env) { return env.x + 1; } struct Environment { int x; } ``` Instead of referring to local variables, the rewritten closure now references fields on the environment. A `struct` environment is used to prevent extra allocations, since `struct`s are normally allocated on the stack. However, the astute reader may notice a problem with this conversion -- `struct`s are always copied when passed as arguments to a function call! This means that writes to the environment field will not always propagate back to the local variable in the method `M`. To work around this flaw, all Environment variables are passed as `ref` arguments to the rewritten closures. The second strategy for rewriting closures is necessary when the closure interacts with external code. Consider the following program: ```csharp void M(IEnumerable<int> e) { int x = 0; var positive = e.Where(n => n > 0); ... } ``` In this case we're passing a closure to the `IEnumerable<int>.Where` function, which is expecting a delegate of type `Func<int, bool>`. Note that that delegate type is immutable -- it is defined in external code and cannot be changed. Therefore, rewriting external callsites to take an extra `Environment` argument is impossible. We have to choose a different strategy for acquiring the environment. What we do is use a `class` Environment for cases like this. With a `class` Environment, the previous environment can be rewritten as follows: ```csharp void M(IEnumerable<int> e) { var env = new Environment(); env.x = 0; var positive = e.Where(env.<>__Local); } class Environment { int x; bool <>__Local(int n) => n > 0; } ``` Since the local variables are now fields in a class instance we can keep the same delegate signature and rely on field access to read and write the free variables. This covers the transformations C# performs at a high level. The following section covers how these transformations are performed in detail. # Internals There are two phases at the top level of closure conversion. The first phase, Analysis, is responsible for building an AnalysisResult data structure which contains all information necessary to rewrite all closures. The second phase, Rewriting, actually performs the aforementioned rewriting by replacing and adding BoundNodes to the Bound Tree. The most important contract between these two phases is that the Analysis phase performs no modifications to the Bound Tree and the Rewriting phase performs no computation and contains no logic aside from a simple mechanical modification of the Bound Tree based on the AnalysisResult. ## Analysis In this phase we build an AnalysisResult, which is a tree structure that exactly represents the state mapping from the original program to the closure-converted form. For example, the following program ```csharp void M() { int x = 0; int Local() => x + 1; { int y = 0; int z = 0; int Local2() => Local() + y; z++; Local2(); } Local(); } ``` Would produce a tree similar to ``` +-------------------------------------+ |Captured: Closures: | |int x int Local() | |int Local() | | | | +--------------------------------+ | | | Captured: Closures: | | | | int y int Local2() | | | | | | | +--------------------------------+ | +-------------------------------------+ ``` To create this AnalysisResult there are multiple passes. The first pass gathers information by constructing a naive tree of scopes, closures, and captured variables. The result is a tree of nested scopes, where each scope lists the captured variables declared in the scope and the closures in that scope. The first pass must first gather information since most rewriting decisions, like what Environment type to use for the closures or what the rewritten closure signature will be, are dependent on context from the entire method. Information about captured variables are stored on instances of the `CapturedVariable` class, which holds information about the Symbol that was captured and rewriting information like the `SynthesizedLocal` that will replace the variable post-rewriting. Similarly, closures will be stored in instances of the `Closure` class, which contain both the original Symbol and the synthesized type or method created for the closure. All of these classes are mutable since it's expected that later passes will fill in more rewriting information using the structure gathered from the earlier passes. For instance, in the previous example we need to walk the tree to generate an Environment for the closures `Closure`, resulting in something like the following: ``` Closure ------- Name: Local Generated Sig: int <>_Local(ref <>_Env1) Environment: - Captures: 'int x' - Name: <>_Env1 - Type: Struct Name: Local2 Generated Sig: int <>_Local(ref <>_Env2, ref <>_Env1) Environment: - Captures: 'int y', 'ref <>_Env1' - Name: <>_Env2 - Type: Struct ``` This result would be generated by each piece filling in required info: first filling in all the capture lists, then deciding the Environment type based on the capture list, then generating the end signature based on the environment type and final capture list. Some further details of analysis calculations can be found below: **TODO** _Add details for each analysis phase as implementation is fleshed out_ * Deciding what environment type is necessary for each closure. An environment can be a struct unless one of the following things is true: 1. The closure is converted to delegate. 2. The closure captures a variable which is captured by a closure that cannot have a `struct` Environment. 3. A reference to the closure is captured by a closure that cannot have a `struct` Environment. * Creating `SynthesizedLocal`s for hoisted captured variables and captured Environment references * Assigning rewritten names, signatures, and type parameters to each closure ## Optimization The final passes are optimization passes. They attempt to simplify the tree by removing intermediate scopes with no captured variables and otherwise correcting the tree to create the most efficient rewritten form. Optimization opportunities could include running escape analysis to determine if capture hoisting could be done via copy or done in a narrower scope. ## Rewriting The rewriting phase simply walks the bound tree and, at each new scope, checks to see if the AnalysisResult contains a scope with rewriting information to process. If so, locals and closures are replaced with the substitutions provided by the tree. Practically, this means that the tree contains: 1. A list of synthesized locals to add to each scope. 2. A set of proxies to replace existing symbols. 3. A list of synthesized methods and types to add to the enclosing type.
-1
dotnet/roslyn
55,364
Fix crash with convert namespace
Oopsie.
CyrusNajmabadi
2021-08-03T02:29:24Z
2021-08-03T12:57:53Z
a80a5868188242800f4615dc51ab30ed5e9eaf76
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
Fix crash with convert namespace. Oopsie.
./docs/wiki/Diagnosing-Project-System-Build-Errors.md
When you open a C# or VB.NET project in Visual Studio, Visual Studio needs to interpret your project file to understand the compiler settings and references you have. In most cases, this is easy, but if you've manually customized your project files, or are consuming additional SDKs or NuGet packages, things can sometimes go wrong. This will help you debug the cause of what went wrong. ## How do I tell if this guide is for me? There are a few ways to tell: 1. A Microsoft engineer asked you to follow these steps. 2. In any version of Visual Studio, look to see if the first project drop down above a text file says "Miscellaneous Files" instead of the name of the project you expected to see: ![Miscellaneous Files show in the navigation bars](images/design-time-build-errors/miscellaneous-files.png) 3. If you're using Visual Studio 2015 Update 2 or later, look for warning IDE0006 in the error list: ![IDE0006 error example](images/design-time-build-errors/ide0006.png) ## How do I get log files to diagnose what is happening in Visual Studio 2022? 1. Install the [Project System Tools 2022 Extension from the Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=VisualStudioProductTeam.ProjectSystemTools2022) 2. Restart Visual Studio as a part of installing the extension. 3. Close Visual Studio again, find your solution file on disk, and delete the .vs hidden folder that is alongside your solution. You'll have to show hidden files if you don't see it. 4. Open Visual Studio. Don't open your Solution yet. 5. Go View > Other Windows > Build Logging. 6. In the Build Logging window, click the start button. 7. Open your solution, and open the file you're having troubles with. You should see various entries appearing in the Build Logging window. 8. Take a screenshot of Visual Studio after you've opened the file you're having troubles with. Save this screenshot and attach it to your feedback item. 9. Click the stop button in the Build Logging window. 10. Select all the logs by clicking on one and then pressing Ctrl+A to Select All. 11. Right click, choose Save Logs. Save them, and attach them to your feedback item. 12. Go under the Tools menu, and choose Log Roslyn Workspace Structure. This will prompt to save an XML file, and the process may take some time. Attach this item to your feedback item. If the file is large, you may wish to zip it into a .zip file if the extension didn't make a .zip file for you. ## How do I get log files to diagnose what is happening in Visual Studio 2015? 1. Close Visual Studio. 2. Find your solution file on disk, and delete the .vs hidden folder that is alongside your solution. 3. Run a "developer command prompt". The easiest way to find it is just to search in the start menu: ![Running the developer command prompt](images/design-time-build-errors/run-developer-command-prompt.png) 4. Type `set TRACEDESIGNTIME=true` in this prompt. 5. Type `devenv` to run Visual Studio again from this prompt. 6. Open your solution. Now, open your `%TEMP%` directory, which should be at a path like `C:\Users\<username>\AppData\Local\Temp`. In this you'll see a bunch of files that end in `.designtime.log`. - If you are running Visual Studio 2015 Update 2 or later, the files start with the name of a project in your solution, then an underscore, and then the name of the underlying build target being invoked by Visual Studio. Look for the files named `YourProject_Compile_#####.designtime.log`, where ##### is just a random identifier generated to keep the log files unique. Look for log files with "Compile" in the name. - If you're running Visual Studio 2015 Update 1 or sooner, it's a bit trickier. The files are just named with random GUIDs, but still end in .designtime.log. If you open a log file, you'll see first a section showing variables, and then a line like this: `Project "c:\Projects\ConsoleApplication53\ConsoleApplication53\ConsoleApplication53.csproj" (Compile target(s)):` This shows the full name of the project, along with the target (Compile) being ran. Once again, look for the "Compile" target. There are files with other targets being invoked, you'll want to ignore those. You might want to consider using Visual Studio's "find in files" feature to find the right file. Once you've found the right log file for your project, scroll to the very end and verify there was an error. You should see something like this: Build FAILED. c:\ConsoleApplication53\ConsoleApplication53\ConsoleApplication53.csproj(17,5): error : An error occured! 0 Warning(s) 1 Error(s) Notably, you should see `Build FAILED` and then one or more errors. This is summary of the errors in the log, so if you do see an error, you should now search this log file for that error and find out where it is. Hopefully, the error will give some sort of a hint; it's looking for some file or SDK that's not installed, or some permissions were denied, etc. In that case, you can follow up with the owner of that to figure out what went wrong. If it seems to be a problem with Visual Studio itself, you might want to file a bug on [the Roslyn GitHub project](https://github.com/dotnet/roslyn) have a Visual Studio engineer take a look. Make sure you provide the full log and if possible your project file, since we may need both to diagnose the problem.
When you open a C# or VB.NET project in Visual Studio, Visual Studio needs to interpret your project file to understand the compiler settings and references you have. In most cases, this is easy, but if you've manually customized your project files, or are consuming additional SDKs or NuGet packages, things can sometimes go wrong. This will help you debug the cause of what went wrong. ## How do I tell if this guide is for me? There are a few ways to tell: 1. A Microsoft engineer asked you to follow these steps. 2. In any version of Visual Studio, look to see if the first project drop down above a text file says "Miscellaneous Files" instead of the name of the project you expected to see: ![Miscellaneous Files show in the navigation bars](images/design-time-build-errors/miscellaneous-files.png) 3. If you're using Visual Studio 2015 Update 2 or later, look for warning IDE0006 in the error list: ![IDE0006 error example](images/design-time-build-errors/ide0006.png) ## How do I get log files to diagnose what is happening in Visual Studio 2022? 1. Install the [Project System Tools 2022 Extension from the Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=VisualStudioProductTeam.ProjectSystemTools2022) 2. Restart Visual Studio as a part of installing the extension. 3. Close Visual Studio again, find your solution file on disk, and delete the .vs hidden folder that is alongside your solution. You'll have to show hidden files if you don't see it. 4. Open Visual Studio. Don't open your Solution yet. 5. Go View > Other Windows > Build Logging. 6. In the Build Logging window, click the start button. 7. Open your solution, and open the file you're having troubles with. You should see various entries appearing in the Build Logging window. 8. Take a screenshot of Visual Studio after you've opened the file you're having troubles with. Save this screenshot and attach it to your feedback item. 9. Click the stop button in the Build Logging window. 10. Select all the logs by clicking on one and then pressing Ctrl+A to Select All. 11. Right click, choose Save Logs. Save them, and attach them to your feedback item. 12. Go under the Tools menu, and choose Log Roslyn Workspace Structure. This will prompt to save an XML file, and the process may take some time. Attach this item to your feedback item. If the file is large, you may wish to zip it into a .zip file if the extension didn't make a .zip file for you. ## How do I get log files to diagnose what is happening in Visual Studio 2015? 1. Close Visual Studio. 2. Find your solution file on disk, and delete the .vs hidden folder that is alongside your solution. 3. Run a "developer command prompt". The easiest way to find it is just to search in the start menu: ![Running the developer command prompt](images/design-time-build-errors/run-developer-command-prompt.png) 4. Type `set TRACEDESIGNTIME=true` in this prompt. 5. Type `devenv` to run Visual Studio again from this prompt. 6. Open your solution. Now, open your `%TEMP%` directory, which should be at a path like `C:\Users\<username>\AppData\Local\Temp`. In this you'll see a bunch of files that end in `.designtime.log`. - If you are running Visual Studio 2015 Update 2 or later, the files start with the name of a project in your solution, then an underscore, and then the name of the underlying build target being invoked by Visual Studio. Look for the files named `YourProject_Compile_#####.designtime.log`, where ##### is just a random identifier generated to keep the log files unique. Look for log files with "Compile" in the name. - If you're running Visual Studio 2015 Update 1 or sooner, it's a bit trickier. The files are just named with random GUIDs, but still end in .designtime.log. If you open a log file, you'll see first a section showing variables, and then a line like this: `Project "c:\Projects\ConsoleApplication53\ConsoleApplication53\ConsoleApplication53.csproj" (Compile target(s)):` This shows the full name of the project, along with the target (Compile) being ran. Once again, look for the "Compile" target. There are files with other targets being invoked, you'll want to ignore those. You might want to consider using Visual Studio's "find in files" feature to find the right file. Once you've found the right log file for your project, scroll to the very end and verify there was an error. You should see something like this: Build FAILED. c:\ConsoleApplication53\ConsoleApplication53\ConsoleApplication53.csproj(17,5): error : An error occured! 0 Warning(s) 1 Error(s) Notably, you should see `Build FAILED` and then one or more errors. This is summary of the errors in the log, so if you do see an error, you should now search this log file for that error and find out where it is. Hopefully, the error will give some sort of a hint; it's looking for some file or SDK that's not installed, or some permissions were denied, etc. In that case, you can follow up with the owner of that to figure out what went wrong. If it seems to be a problem with Visual Studio itself, you might want to file a bug on [the Roslyn GitHub project](https://github.com/dotnet/roslyn) have a Visual Studio engineer take a look. Make sure you provide the full log and if possible your project file, since we may need both to diagnose the problem.
-1
dotnet/roslyn
55,364
Fix crash with convert namespace
Oopsie.
CyrusNajmabadi
2021-08-03T02:29:24Z
2021-08-03T12:57:53Z
a80a5868188242800f4615dc51ab30ed5e9eaf76
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
Fix crash with convert namespace. Oopsie.
./src/Tools/ExternalAccess/FSharp/ExternalAccessFSharpResources.Designer.cs
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ #nullable disable namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class ExternalAccessFSharpResources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal ExternalAccessFSharpResources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.CodeAnalysis.ExternalAccess.FSharp.ExternalAccessFSharpResources", typeof(ExternalAccessFSharpResources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Add an assembly reference to &apos;{0}&apos;. /// </summary> internal static string AddAssemblyReference { get { return ResourceManager.GetString("AddAssemblyReference", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Add &apos;new&apos; keyword. /// </summary> internal static string AddNewKeyword { get { return ResourceManager.GetString("AddNewKeyword", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Add a project reference to &apos;{0}&apos;. /// </summary> internal static string AddProjectReference { get { return ResourceManager.GetString("AddProjectReference", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Cannot determine the symbol under the caret. /// </summary> internal static string CannotDetermineSymbol { get { return ResourceManager.GetString("CannotDetermineSymbol", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Cannot navigate to the requested location. /// </summary> internal static string CannotNavigateUnknown { get { return ResourceManager.GetString("CannotNavigateUnknown", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Exceptions:. /// </summary> internal static string ExceptionsHeader { get { return ResourceManager.GetString("ExceptionsHeader", resourceCulture); } } /// <summary> /// Looks up a localized string similar to F# Disposable Types. /// </summary> internal static string FSharpDisposablesClassificationType { get { return ResourceManager.GetString("FSharpDisposablesClassificationType", resourceCulture); } } /// <summary> /// Looks up a localized string similar to F# Functions / Methods. /// </summary> internal static string FSharpFunctionsOrMethodsClassificationType { get { return ResourceManager.GetString("FSharpFunctionsOrMethodsClassificationType", resourceCulture); } } /// <summary> /// Looks up a localized string similar to F# Mutable Variables / Reference Cells. /// </summary> internal static string FSharpMutableVarsClassificationType { get { return ResourceManager.GetString("FSharpMutableVarsClassificationType", resourceCulture); } } /// <summary> /// Looks up a localized string similar to F# Printf Format. /// </summary> internal static string FSharpPrintfFormatClassificationType { get { return ResourceManager.GetString("FSharpPrintfFormatClassificationType", resourceCulture); } } /// <summary> /// Looks up a localized string similar to F# Properties. /// </summary> internal static string FSharpPropertiesClassificationType { get { return ResourceManager.GetString("FSharpPropertiesClassificationType", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Generic parameters:. /// </summary> internal static string GenericParametersHeader { get { return ResourceManager.GetString("GenericParametersHeader", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Implement interface. /// </summary> internal static string ImplementInterface { get { return ResourceManager.GetString("ImplementInterface", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Implement interface without type annotation. /// </summary> internal static string ImplementInterfaceWithoutTypeAnnotation { get { return ResourceManager.GetString("ImplementInterfaceWithoutTypeAnnotation", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Locating the symbol under the caret.... /// </summary> internal static string LocatingSymbol { get { return ResourceManager.GetString("LocatingSymbol", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Name can be simplified.. /// </summary> internal static string NameCanBeSimplified { get { return ResourceManager.GetString("NameCanBeSimplified", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Navigate to symbol failed: {0}. /// </summary> internal static string NavigateToFailed { get { return ResourceManager.GetString("NavigateToFailed", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Navigating to symbol.... /// </summary> internal static string NavigatingTo { get { return ResourceManager.GetString("NavigatingTo", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Prefix &apos;{0}&apos; with underscore. /// </summary> internal static string PrefixValueNameWithUnderscore { get { return ResourceManager.GetString("PrefixValueNameWithUnderscore", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Remove unused open declarations. /// </summary> internal static string RemoveUnusedOpens { get { return ResourceManager.GetString("RemoveUnusedOpens", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Rename &apos;{0}&apos; to &apos;__&apos;. /// </summary> internal static string RenameValueToDoubleUnderscore { get { return ResourceManager.GetString("RenameValueToDoubleUnderscore", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Rename &apos;{0}&apos; to &apos;_&apos;. /// </summary> internal static string RenameValueToUnderscore { get { return ResourceManager.GetString("RenameValueToUnderscore", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Simplify name. /// </summary> internal static string SimplifyName { get { return ResourceManager.GetString("SimplifyName", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The value is unused. /// </summary> internal static string TheValueIsUnused { get { return ResourceManager.GetString("TheValueIsUnused", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Open declaration can be removed.. /// </summary> internal static string UnusedOpens { get { return ResourceManager.GetString("UnusedOpens", resourceCulture); } } } }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ #nullable disable namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class ExternalAccessFSharpResources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal ExternalAccessFSharpResources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.CodeAnalysis.ExternalAccess.FSharp.ExternalAccessFSharpResources", typeof(ExternalAccessFSharpResources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Add an assembly reference to &apos;{0}&apos;. /// </summary> internal static string AddAssemblyReference { get { return ResourceManager.GetString("AddAssemblyReference", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Add &apos;new&apos; keyword. /// </summary> internal static string AddNewKeyword { get { return ResourceManager.GetString("AddNewKeyword", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Add a project reference to &apos;{0}&apos;. /// </summary> internal static string AddProjectReference { get { return ResourceManager.GetString("AddProjectReference", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Cannot determine the symbol under the caret. /// </summary> internal static string CannotDetermineSymbol { get { return ResourceManager.GetString("CannotDetermineSymbol", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Cannot navigate to the requested location. /// </summary> internal static string CannotNavigateUnknown { get { return ResourceManager.GetString("CannotNavigateUnknown", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Exceptions:. /// </summary> internal static string ExceptionsHeader { get { return ResourceManager.GetString("ExceptionsHeader", resourceCulture); } } /// <summary> /// Looks up a localized string similar to F# Disposable Types. /// </summary> internal static string FSharpDisposablesClassificationType { get { return ResourceManager.GetString("FSharpDisposablesClassificationType", resourceCulture); } } /// <summary> /// Looks up a localized string similar to F# Functions / Methods. /// </summary> internal static string FSharpFunctionsOrMethodsClassificationType { get { return ResourceManager.GetString("FSharpFunctionsOrMethodsClassificationType", resourceCulture); } } /// <summary> /// Looks up a localized string similar to F# Mutable Variables / Reference Cells. /// </summary> internal static string FSharpMutableVarsClassificationType { get { return ResourceManager.GetString("FSharpMutableVarsClassificationType", resourceCulture); } } /// <summary> /// Looks up a localized string similar to F# Printf Format. /// </summary> internal static string FSharpPrintfFormatClassificationType { get { return ResourceManager.GetString("FSharpPrintfFormatClassificationType", resourceCulture); } } /// <summary> /// Looks up a localized string similar to F# Properties. /// </summary> internal static string FSharpPropertiesClassificationType { get { return ResourceManager.GetString("FSharpPropertiesClassificationType", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Generic parameters:. /// </summary> internal static string GenericParametersHeader { get { return ResourceManager.GetString("GenericParametersHeader", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Implement interface. /// </summary> internal static string ImplementInterface { get { return ResourceManager.GetString("ImplementInterface", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Implement interface without type annotation. /// </summary> internal static string ImplementInterfaceWithoutTypeAnnotation { get { return ResourceManager.GetString("ImplementInterfaceWithoutTypeAnnotation", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Locating the symbol under the caret.... /// </summary> internal static string LocatingSymbol { get { return ResourceManager.GetString("LocatingSymbol", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Name can be simplified.. /// </summary> internal static string NameCanBeSimplified { get { return ResourceManager.GetString("NameCanBeSimplified", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Navigate to symbol failed: {0}. /// </summary> internal static string NavigateToFailed { get { return ResourceManager.GetString("NavigateToFailed", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Navigating to symbol.... /// </summary> internal static string NavigatingTo { get { return ResourceManager.GetString("NavigatingTo", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Prefix &apos;{0}&apos; with underscore. /// </summary> internal static string PrefixValueNameWithUnderscore { get { return ResourceManager.GetString("PrefixValueNameWithUnderscore", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Remove unused open declarations. /// </summary> internal static string RemoveUnusedOpens { get { return ResourceManager.GetString("RemoveUnusedOpens", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Rename &apos;{0}&apos; to &apos;__&apos;. /// </summary> internal static string RenameValueToDoubleUnderscore { get { return ResourceManager.GetString("RenameValueToDoubleUnderscore", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Rename &apos;{0}&apos; to &apos;_&apos;. /// </summary> internal static string RenameValueToUnderscore { get { return ResourceManager.GetString("RenameValueToUnderscore", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Simplify name. /// </summary> internal static string SimplifyName { get { return ResourceManager.GetString("SimplifyName", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The value is unused. /// </summary> internal static string TheValueIsUnused { get { return ResourceManager.GetString("TheValueIsUnused", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Open declaration can be removed.. /// </summary> internal static string UnusedOpens { get { return ResourceManager.GetString("UnusedOpens", resourceCulture); } } } }
-1
dotnet/roslyn
55,364
Fix crash with convert namespace
Oopsie.
CyrusNajmabadi
2021-08-03T02:29:24Z
2021-08-03T12:57:53Z
a80a5868188242800f4615dc51ab30ed5e9eaf76
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
Fix crash with convert namespace. Oopsie.
./src/Tools/ExternalAccess/FSharp/FSharpGlyphTags.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp { internal static class FSharpGlyphTags { public static ImmutableArray<string> GetTags(FSharpGlyph glyph) { return GlyphTags.GetTags(FSharpGlyphHelpers.ConvertTo(glyph)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp { internal static class FSharpGlyphTags { public static ImmutableArray<string> GetTags(FSharpGlyph glyph) { return GlyphTags.GetTags(FSharpGlyphHelpers.ConvertTo(glyph)); } } }
-1
dotnet/roslyn
55,364
Fix crash with convert namespace
Oopsie.
CyrusNajmabadi
2021-08-03T02:29:24Z
2021-08-03T12:57:53Z
a80a5868188242800f4615dc51ab30ed5e9eaf76
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
Fix crash with convert namespace. Oopsie.
./src/ExpressionEvaluator/Core/Source/ExpressionCompiler/NotImplementedMetadataException.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal sealed class NotImplementedMetadataException : Exception { internal NotImplementedMetadataException(NotImplementedException inner) : base(string.Empty, inner) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal sealed class NotImplementedMetadataException : Exception { internal NotImplementedMetadataException(NotImplementedException inner) : base(string.Empty, inner) { } } }
-1
dotnet/roslyn
55,364
Fix crash with convert namespace
Oopsie.
CyrusNajmabadi
2021-08-03T02:29:24Z
2021-08-03T12:57:53Z
a80a5868188242800f4615dc51ab30ed5e9eaf76
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
Fix crash with convert namespace. Oopsie.
./src/Compilers/CSharp/Portable/Emitter/EditAndContinue/CSharpDefinitionMap.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Reflection.Metadata; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Symbols; namespace Microsoft.CodeAnalysis.CSharp.Emit { /// <summary> /// Matches symbols from an assembly in one compilation to /// the corresponding assembly in another. Assumes that only /// one assembly has changed between the two compilations. /// </summary> internal sealed partial class CSharpDefinitionMap : DefinitionMap { private readonly MetadataDecoder _metadataDecoder; private readonly CSharpSymbolMatcher _mapToMetadata; private readonly CSharpSymbolMatcher _mapToPrevious; public CSharpDefinitionMap( IEnumerable<SemanticEdit> edits, MetadataDecoder metadataDecoder, CSharpSymbolMatcher mapToMetadata, CSharpSymbolMatcher? mapToPrevious) : base(edits) { _metadataDecoder = metadataDecoder; _mapToMetadata = mapToMetadata; _mapToPrevious = mapToPrevious ?? mapToMetadata; } protected override SymbolMatcher MapToMetadataSymbolMatcher => _mapToMetadata; protected override SymbolMatcher MapToPreviousSymbolMatcher => _mapToPrevious; protected override ISymbolInternal? GetISymbolInternalOrNull(ISymbol symbol) { return (symbol as Symbols.PublicModel.Symbol)?.UnderlyingSymbol; } internal override CommonMessageProvider MessageProvider => CSharp.MessageProvider.Instance; protected override LambdaSyntaxFacts GetLambdaSyntaxFacts() => CSharpLambdaSyntaxFacts.Instance; internal bool TryGetAnonymousTypeName(AnonymousTypeManager.AnonymousTypeTemplateSymbol template, [NotNullWhen(true)] out string? name, out int index) => _mapToPrevious.TryGetAnonymousTypeName(template, out name, out index); internal override bool TryGetTypeHandle(Cci.ITypeDefinition def, out TypeDefinitionHandle handle) { if (_mapToMetadata.MapDefinition(def)?.GetInternalSymbol() is PENamedTypeSymbol other) { handle = other.Handle; return true; } handle = default; return false; } internal override bool TryGetEventHandle(Cci.IEventDefinition def, out EventDefinitionHandle handle) { if (_mapToMetadata.MapDefinition(def)?.GetInternalSymbol() is PEEventSymbol other) { handle = other.Handle; return true; } handle = default; return false; } internal override bool TryGetFieldHandle(Cci.IFieldDefinition def, out FieldDefinitionHandle handle) { if (_mapToMetadata.MapDefinition(def)?.GetInternalSymbol() is PEFieldSymbol other) { handle = other.Handle; return true; } handle = default; return false; } internal override bool TryGetMethodHandle(Cci.IMethodDefinition def, out MethodDefinitionHandle handle) { if (_mapToMetadata.MapDefinition(def)?.GetInternalSymbol() is PEMethodSymbol other) { handle = other.Handle; return true; } handle = default; return false; } internal override bool TryGetPropertyHandle(Cci.IPropertyDefinition def, out PropertyDefinitionHandle handle) { if (_mapToMetadata.MapDefinition(def)?.GetInternalSymbol() is PEPropertySymbol other) { handle = other.Handle; return true; } handle = default; return false; } protected override void GetStateMachineFieldMapFromMetadata( ITypeSymbolInternal stateMachineType, ImmutableArray<LocalSlotDebugInfo> localSlotDebugInfo, out IReadOnlyDictionary<EncHoistedLocalInfo, int> hoistedLocalMap, out IReadOnlyDictionary<Cci.ITypeReference, int> awaiterMap, out int awaiterSlotCount) { // we are working with PE symbols Debug.Assert(stateMachineType.ContainingAssembly is PEAssemblySymbol); var hoistedLocals = new Dictionary<EncHoistedLocalInfo, int>(); var awaiters = new Dictionary<Cci.ITypeReference, int>(Cci.SymbolEquivalentEqualityComparer.Instance); int maxAwaiterSlotIndex = -1; foreach (var member in ((TypeSymbol)stateMachineType).GetMembers()) { if (member.Kind == SymbolKind.Field) { string name = member.Name; int slotIndex; switch (GeneratedNames.GetKind(name)) { case GeneratedNameKind.AwaiterField: if (GeneratedNames.TryParseSlotIndex(name, out slotIndex)) { var field = (FieldSymbol)member; // correct metadata won't contain duplicates, but malformed might, ignore the duplicate: awaiters[(Cci.ITypeReference)field.Type.GetCciAdapter()] = slotIndex; if (slotIndex > maxAwaiterSlotIndex) { maxAwaiterSlotIndex = slotIndex; } } break; case GeneratedNameKind.HoistedLocalField: case GeneratedNameKind.HoistedSynthesizedLocalField: if (GeneratedNames.TryParseSlotIndex(name, out slotIndex)) { var field = (FieldSymbol)member; if (slotIndex >= localSlotDebugInfo.Length) { // invalid or missing metadata continue; } var key = new EncHoistedLocalInfo(localSlotDebugInfo[slotIndex], (Cci.ITypeReference)field.Type.GetCciAdapter()); // correct metadata won't contain duplicate ids, but malformed might, ignore the duplicate: hoistedLocals[key] = slotIndex; } break; } } } hoistedLocalMap = hoistedLocals; awaiterMap = awaiters; awaiterSlotCount = maxAwaiterSlotIndex + 1; } protected override ImmutableArray<EncLocalInfo> GetLocalSlotMapFromMetadata(StandaloneSignatureHandle handle, EditAndContinueMethodDebugInformation debugInfo) { Debug.Assert(!handle.IsNil); var localInfos = _metadataDecoder.GetLocalsOrThrow(handle); var result = CreateLocalSlotMap(debugInfo, localInfos); Debug.Assert(result.Length == localInfos.Length); return result; } protected override ITypeSymbolInternal? TryGetStateMachineType(EntityHandle methodHandle) { string typeName; if (_metadataDecoder.Module.HasStringValuedAttribute(methodHandle, AttributeDescription.AsyncStateMachineAttribute, out typeName) || _metadataDecoder.Module.HasStringValuedAttribute(methodHandle, AttributeDescription.IteratorStateMachineAttribute, out typeName)) { return _metadataDecoder.GetTypeSymbolForSerializedType(typeName); } return null; } /// <summary> /// Match local declarations to names to generate a map from /// declaration to local slot. The names are indexed by slot and the /// assumption is that declarations are in the same order as slots. /// </summary> private static ImmutableArray<EncLocalInfo> CreateLocalSlotMap( EditAndContinueMethodDebugInformation methodEncInfo, ImmutableArray<LocalInfo<TypeSymbol>> slotMetadata) { var result = new EncLocalInfo[slotMetadata.Length]; var localSlots = methodEncInfo.LocalSlots; if (!localSlots.IsDefault) { // In case of corrupted PDB or metadata, these lengths might not match. // Let's guard against such case. int slotCount = Math.Min(localSlots.Length, slotMetadata.Length); var map = new Dictionary<EncLocalInfo, int>(); for (int slotIndex = 0; slotIndex < slotCount; slotIndex++) { var slot = localSlots[slotIndex]; if (slot.SynthesizedKind.IsLongLived()) { var metadata = slotMetadata[slotIndex]; // We do not emit custom modifiers on locals so ignore the // previous version of the local if it had custom modifiers. if (metadata.CustomModifiers.IsDefaultOrEmpty) { var local = new EncLocalInfo(slot, (Cci.ITypeReference)metadata.Type.GetCciAdapter(), metadata.Constraints, metadata.SignatureOpt); map.Add(local, slotIndex); } } } foreach (var pair in map) { result[pair.Value] = pair.Key; } } // Populate any remaining locals that were not matched to source. for (int i = 0; i < result.Length; i++) { if (result[i].IsDefault) { result[i] = new EncLocalInfo(slotMetadata[i].SignatureOpt); } } return ImmutableArray.Create(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. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection.Metadata; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Symbols; namespace Microsoft.CodeAnalysis.CSharp.Emit { /// <summary> /// Matches symbols from an assembly in one compilation to /// the corresponding assembly in another. Assumes that only /// one assembly has changed between the two compilations. /// </summary> internal sealed partial class CSharpDefinitionMap : DefinitionMap { private readonly MetadataDecoder _metadataDecoder; private readonly CSharpSymbolMatcher _mapToMetadata; private readonly CSharpSymbolMatcher _mapToPrevious; public CSharpDefinitionMap( IEnumerable<SemanticEdit> edits, MetadataDecoder metadataDecoder, CSharpSymbolMatcher mapToMetadata, CSharpSymbolMatcher? mapToPrevious) : base(edits) { _metadataDecoder = metadataDecoder; _mapToMetadata = mapToMetadata; _mapToPrevious = mapToPrevious ?? mapToMetadata; } protected override SymbolMatcher MapToMetadataSymbolMatcher => _mapToMetadata; protected override SymbolMatcher MapToPreviousSymbolMatcher => _mapToPrevious; protected override ISymbolInternal? GetISymbolInternalOrNull(ISymbol symbol) { return (symbol as Symbols.PublicModel.Symbol)?.UnderlyingSymbol; } internal override CommonMessageProvider MessageProvider => CSharp.MessageProvider.Instance; protected override LambdaSyntaxFacts GetLambdaSyntaxFacts() => CSharpLambdaSyntaxFacts.Instance; internal bool TryGetAnonymousTypeName(AnonymousTypeManager.AnonymousTypeTemplateSymbol template, [NotNullWhen(true)] out string? name, out int index) => _mapToPrevious.TryGetAnonymousTypeName(template, out name, out index); internal override bool TryGetTypeHandle(Cci.ITypeDefinition def, out TypeDefinitionHandle handle) { if (_mapToMetadata.MapDefinition(def)?.GetInternalSymbol() is PENamedTypeSymbol other) { handle = other.Handle; return true; } handle = default; return false; } internal override bool TryGetEventHandle(Cci.IEventDefinition def, out EventDefinitionHandle handle) { if (_mapToMetadata.MapDefinition(def)?.GetInternalSymbol() is PEEventSymbol other) { handle = other.Handle; return true; } handle = default; return false; } internal override bool TryGetFieldHandle(Cci.IFieldDefinition def, out FieldDefinitionHandle handle) { if (_mapToMetadata.MapDefinition(def)?.GetInternalSymbol() is PEFieldSymbol other) { handle = other.Handle; return true; } handle = default; return false; } internal override bool TryGetMethodHandle(Cci.IMethodDefinition def, out MethodDefinitionHandle handle) { if (_mapToMetadata.MapDefinition(def)?.GetInternalSymbol() is PEMethodSymbol other) { handle = other.Handle; return true; } handle = default; return false; } internal override bool TryGetPropertyHandle(Cci.IPropertyDefinition def, out PropertyDefinitionHandle handle) { if (_mapToMetadata.MapDefinition(def)?.GetInternalSymbol() is PEPropertySymbol other) { handle = other.Handle; return true; } handle = default; return false; } protected override void GetStateMachineFieldMapFromMetadata( ITypeSymbolInternal stateMachineType, ImmutableArray<LocalSlotDebugInfo> localSlotDebugInfo, out IReadOnlyDictionary<EncHoistedLocalInfo, int> hoistedLocalMap, out IReadOnlyDictionary<Cci.ITypeReference, int> awaiterMap, out int awaiterSlotCount) { // we are working with PE symbols Debug.Assert(stateMachineType.ContainingAssembly is PEAssemblySymbol); var hoistedLocals = new Dictionary<EncHoistedLocalInfo, int>(); var awaiters = new Dictionary<Cci.ITypeReference, int>(Cci.SymbolEquivalentEqualityComparer.Instance); int maxAwaiterSlotIndex = -1; foreach (var member in ((TypeSymbol)stateMachineType).GetMembers()) { if (member.Kind == SymbolKind.Field) { string name = member.Name; int slotIndex; switch (GeneratedNames.GetKind(name)) { case GeneratedNameKind.AwaiterField: if (GeneratedNames.TryParseSlotIndex(name, out slotIndex)) { var field = (FieldSymbol)member; // correct metadata won't contain duplicates, but malformed might, ignore the duplicate: awaiters[(Cci.ITypeReference)field.Type.GetCciAdapter()] = slotIndex; if (slotIndex > maxAwaiterSlotIndex) { maxAwaiterSlotIndex = slotIndex; } } break; case GeneratedNameKind.HoistedLocalField: case GeneratedNameKind.HoistedSynthesizedLocalField: if (GeneratedNames.TryParseSlotIndex(name, out slotIndex)) { var field = (FieldSymbol)member; if (slotIndex >= localSlotDebugInfo.Length) { // invalid or missing metadata continue; } var key = new EncHoistedLocalInfo(localSlotDebugInfo[slotIndex], (Cci.ITypeReference)field.Type.GetCciAdapter()); // correct metadata won't contain duplicate ids, but malformed might, ignore the duplicate: hoistedLocals[key] = slotIndex; } break; } } } hoistedLocalMap = hoistedLocals; awaiterMap = awaiters; awaiterSlotCount = maxAwaiterSlotIndex + 1; } protected override ImmutableArray<EncLocalInfo> GetLocalSlotMapFromMetadata(StandaloneSignatureHandle handle, EditAndContinueMethodDebugInformation debugInfo) { Debug.Assert(!handle.IsNil); var localInfos = _metadataDecoder.GetLocalsOrThrow(handle); var result = CreateLocalSlotMap(debugInfo, localInfos); Debug.Assert(result.Length == localInfos.Length); return result; } protected override ITypeSymbolInternal? TryGetStateMachineType(EntityHandle methodHandle) { string typeName; if (_metadataDecoder.Module.HasStringValuedAttribute(methodHandle, AttributeDescription.AsyncStateMachineAttribute, out typeName) || _metadataDecoder.Module.HasStringValuedAttribute(methodHandle, AttributeDescription.IteratorStateMachineAttribute, out typeName)) { return _metadataDecoder.GetTypeSymbolForSerializedType(typeName); } return null; } /// <summary> /// Match local declarations to names to generate a map from /// declaration to local slot. The names are indexed by slot and the /// assumption is that declarations are in the same order as slots. /// </summary> private static ImmutableArray<EncLocalInfo> CreateLocalSlotMap( EditAndContinueMethodDebugInformation methodEncInfo, ImmutableArray<LocalInfo<TypeSymbol>> slotMetadata) { var result = new EncLocalInfo[slotMetadata.Length]; var localSlots = methodEncInfo.LocalSlots; if (!localSlots.IsDefault) { // In case of corrupted PDB or metadata, these lengths might not match. // Let's guard against such case. int slotCount = Math.Min(localSlots.Length, slotMetadata.Length); var map = new Dictionary<EncLocalInfo, int>(); for (int slotIndex = 0; slotIndex < slotCount; slotIndex++) { var slot = localSlots[slotIndex]; if (slot.SynthesizedKind.IsLongLived()) { var metadata = slotMetadata[slotIndex]; // We do not emit custom modifiers on locals so ignore the // previous version of the local if it had custom modifiers. if (metadata.CustomModifiers.IsDefaultOrEmpty) { var local = new EncLocalInfo(slot, (Cci.ITypeReference)metadata.Type.GetCciAdapter(), metadata.Constraints, metadata.SignatureOpt); map.Add(local, slotIndex); } } } foreach (var pair in map) { result[pair.Value] = pair.Key; } } // Populate any remaining locals that were not matched to source. for (int i = 0; i < result.Length; i++) { if (result[i].IsDefault) { result[i] = new EncLocalInfo(slotMetadata[i].SignatureOpt); } } return ImmutableArray.Create(result); } } }
-1
dotnet/roslyn
55,364
Fix crash with convert namespace
Oopsie.
CyrusNajmabadi
2021-08-03T02:29:24Z
2021-08-03T12:57:53Z
a80a5868188242800f4615dc51ab30ed5e9eaf76
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
Fix crash with convert namespace. Oopsie.
./src/VisualStudio/Core/Impl/SolutionExplorer/AnalyzersFolderItem/AnalyzersFolderItemSourceProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.Internal.VisualStudio.PlatformUI; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { using Workspace = Microsoft.CodeAnalysis.Workspace; [Export(typeof(IAttachedCollectionSourceProvider))] [Name(nameof(AnalyzersFolderItemSourceProvider))] [Order(Before = HierarchyItemsProviderNames.Contains)] [AppliesToProject("(CSharp | VB) & !CPS")] // in the CPS case, the Analyzers folder is created by the project system internal class AnalyzersFolderItemSourceProvider : AttachedCollectionSourceProvider<IVsHierarchyItem> { private readonly IAnalyzersCommandHandler _commandHandler; private IHierarchyItemToProjectIdMap? _projectMap; private readonly Workspace _workspace; [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] [ImportingConstructor] public AnalyzersFolderItemSourceProvider( VisualStudioWorkspace workspace, [Import(typeof(AnalyzersCommandHandler))] IAnalyzersCommandHandler commandHandler) { _workspace = workspace; _commandHandler = commandHandler; } protected override IAttachedCollectionSource? CreateCollectionSource(IVsHierarchyItem item, string relationshipName) { if (item != null && item.HierarchyIdentity != null && item.HierarchyIdentity.NestedHierarchy != null && relationshipName == KnownRelationships.Contains) { var hierarchy = item.HierarchyIdentity.NestedHierarchy; var itemId = item.HierarchyIdentity.NestedItemID; var projectTreeCapabilities = GetProjectTreeCapabilities(hierarchy, itemId); if (projectTreeCapabilities.Any(c => c.Equals("References"))) { var hierarchyMapper = TryGetProjectMap(); if (hierarchyMapper != null && hierarchyMapper.TryGetProjectId(item.Parent, targetFrameworkMoniker: null, projectId: out var projectId)) { return new AnalyzersFolderItemSource(_workspace, projectId, item, _commandHandler); } return null; } } return null; } private static ImmutableArray<string> GetProjectTreeCapabilities(IVsHierarchy hierarchy, uint itemId) { if (hierarchy.GetProperty(itemId, (int)__VSHPROPID7.VSHPROPID_ProjectTreeCapabilities, out var capabilitiesObj) == VSConstants.S_OK) { var capabilitiesString = (string)capabilitiesObj; return ImmutableArray.Create(capabilitiesString.Split(' ')); } else { return ImmutableArray<string>.Empty; } } private IHierarchyItemToProjectIdMap? TryGetProjectMap() { if (_projectMap == null) { _projectMap = _workspace.Services.GetService<IHierarchyItemToProjectIdMap>(); } return _projectMap; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.Internal.VisualStudio.PlatformUI; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { using Workspace = Microsoft.CodeAnalysis.Workspace; [Export(typeof(IAttachedCollectionSourceProvider))] [Name(nameof(AnalyzersFolderItemSourceProvider))] [Order(Before = HierarchyItemsProviderNames.Contains)] [AppliesToProject("(CSharp | VB) & !CPS")] // in the CPS case, the Analyzers folder is created by the project system internal class AnalyzersFolderItemSourceProvider : AttachedCollectionSourceProvider<IVsHierarchyItem> { private readonly IAnalyzersCommandHandler _commandHandler; private IHierarchyItemToProjectIdMap? _projectMap; private readonly Workspace _workspace; [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] [ImportingConstructor] public AnalyzersFolderItemSourceProvider( VisualStudioWorkspace workspace, [Import(typeof(AnalyzersCommandHandler))] IAnalyzersCommandHandler commandHandler) { _workspace = workspace; _commandHandler = commandHandler; } protected override IAttachedCollectionSource? CreateCollectionSource(IVsHierarchyItem item, string relationshipName) { if (item != null && item.HierarchyIdentity != null && item.HierarchyIdentity.NestedHierarchy != null && relationshipName == KnownRelationships.Contains) { var hierarchy = item.HierarchyIdentity.NestedHierarchy; var itemId = item.HierarchyIdentity.NestedItemID; var projectTreeCapabilities = GetProjectTreeCapabilities(hierarchy, itemId); if (projectTreeCapabilities.Any(c => c.Equals("References"))) { var hierarchyMapper = TryGetProjectMap(); if (hierarchyMapper != null && hierarchyMapper.TryGetProjectId(item.Parent, targetFrameworkMoniker: null, projectId: out var projectId)) { return new AnalyzersFolderItemSource(_workspace, projectId, item, _commandHandler); } return null; } } return null; } private static ImmutableArray<string> GetProjectTreeCapabilities(IVsHierarchy hierarchy, uint itemId) { if (hierarchy.GetProperty(itemId, (int)__VSHPROPID7.VSHPROPID_ProjectTreeCapabilities, out var capabilitiesObj) == VSConstants.S_OK) { var capabilitiesString = (string)capabilitiesObj; return ImmutableArray.Create(capabilitiesString.Split(' ')); } else { return ImmutableArray<string>.Empty; } } private IHierarchyItemToProjectIdMap? TryGetProjectMap() { if (_projectMap == null) { _projectMap = _workspace.Services.GetService<IHierarchyItemToProjectIdMap>(); } return _projectMap; } } }
-1
dotnet/roslyn
55,364
Fix crash with convert namespace
Oopsie.
CyrusNajmabadi
2021-08-03T02:29:24Z
2021-08-03T12:57:53Z
a80a5868188242800f4615dc51ab30ed5e9eaf76
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
Fix crash with convert namespace. Oopsie.
./src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/LocalFunctionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.CodeGen; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class LocalFunctionTests : ExpressionCompilerTestBase { [Fact] public void NoLocals() { var source = @"class C { void F(int x) { int y = x + 1; int G() { return 0; }; int z = G(); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>g__G|0_0"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.NotNull(assembly); Assert.Equal(0, assembly.Count); Assert.Equal(0, locals.Count); locals.Free(); }); } [Fact] public void Locals() { var source = @"class C { void F(int x) { int G(int y) { int z = y + 1; return z; }; G(x + 1); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>g__G|0_0"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyLocal(testData, typeName, locals[0], "<>m0", "y", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (int V_0, //z int V_1) IL_0000: ldarg.0 IL_0001: ret }"); VerifyLocal(testData, typeName, locals[1], "<>m1", "z", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (int V_0, //z int V_1) IL_0000: ldloc.0 IL_0001: ret }"); locals.Free(); string error; context.CompileExpression("this.F(1)", out error, testData); Assert.Equal("error CS0027: Keyword 'this' is not available in the current context", error); }); } [Fact] public void CapturedVariable() { var source = @"class C { int x; void F(int y) { int G() { return x + y; }; int z = G(); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>g__G|1_0"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyLocal(testData, typeName, locals[0], "<>m0", "this", expectedILOpt: @"{ // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldfld ""C C.<>c__DisplayClass1_0.<>4__this"" IL_0006: ret }"); VerifyLocal(testData, typeName, locals[1], "<>m1", "y", expectedILOpt: @"{ // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldfld ""int C.<>c__DisplayClass1_0.y"" IL_0006: ret }"); locals.Free(); testData = new CompilationTestData(); string error; context.CompileExpression("this.F(1)", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 13 (0xd) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldfld ""C C.<>c__DisplayClass1_0.<>4__this"" IL_0006: ldc.i4.1 IL_0007: callvirt ""void C.F(int)"" IL_000c: ret }"); }); } [Fact] public void MultipleDisplayClasses() { var source = @"class C { void F1(int x) { int F2(int y) { int F3() => x + y; return F3(); }; F2(1); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F1>g__F3|0_1"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyLocal(testData, typeName, locals[0], "<>m0", "x", expectedILOpt: @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ret }"); VerifyLocal(testData, typeName, locals[1], "<>m1", "y", expectedILOpt: @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: ldfld ""int C.<>c__DisplayClass0_1.y"" IL_0006: ret }"); locals.Free(); testData = new CompilationTestData(); string error; context.CompileExpression("x + y", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldarg.1 IL_0007: ldfld ""int C.<>c__DisplayClass0_1.y"" IL_000c: add IL_000d: ret }"); }); } // Should not bind to unnamed display class parameters // (unnamed parameters are treated as named "value"). [Fact] public void CapturedVariableNamedValue() { var source = @"class C { void F(int value) { int G() { return value + 1; }; G(); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>g__G|0_0"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); VerifyLocal(testData, typeName, locals[0], "<>m0", "value", expectedILOpt: @"{ // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.value"" IL_0006: ret }"); locals.Free(); testData = new CompilationTestData(); string error; context.CompileExpression("value", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.value"" IL_0006: ret }"); }); } // Should not bind to unnamed display class parameters // (unnamed parameters are treated as named "value"). [WorkItem(18426, "https://github.com/dotnet/roslyn/issues/18426")] [Fact(Skip = "18426")] public void DisplayClassParameter() { var source = @"class C { void F(int x) { int G() { return x + 1; }; G(); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>g__G|0_0"); var testData = new CompilationTestData(); string error; context.CompileExpression("value", out error, testData); Assert.Equal("error CS0103: The name 'value' does not exist in the current context", error); }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.CodeGen; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class LocalFunctionTests : ExpressionCompilerTestBase { [Fact] public void NoLocals() { var source = @"class C { void F(int x) { int y = x + 1; int G() { return 0; }; int z = G(); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>g__G|0_0"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.NotNull(assembly); Assert.Equal(0, assembly.Count); Assert.Equal(0, locals.Count); locals.Free(); }); } [Fact] public void Locals() { var source = @"class C { void F(int x) { int G(int y) { int z = y + 1; return z; }; G(x + 1); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>g__G|0_0"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyLocal(testData, typeName, locals[0], "<>m0", "y", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (int V_0, //z int V_1) IL_0000: ldarg.0 IL_0001: ret }"); VerifyLocal(testData, typeName, locals[1], "<>m1", "z", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (int V_0, //z int V_1) IL_0000: ldloc.0 IL_0001: ret }"); locals.Free(); string error; context.CompileExpression("this.F(1)", out error, testData); Assert.Equal("error CS0027: Keyword 'this' is not available in the current context", error); }); } [Fact] public void CapturedVariable() { var source = @"class C { int x; void F(int y) { int G() { return x + y; }; int z = G(); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>g__G|1_0"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyLocal(testData, typeName, locals[0], "<>m0", "this", expectedILOpt: @"{ // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldfld ""C C.<>c__DisplayClass1_0.<>4__this"" IL_0006: ret }"); VerifyLocal(testData, typeName, locals[1], "<>m1", "y", expectedILOpt: @"{ // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldfld ""int C.<>c__DisplayClass1_0.y"" IL_0006: ret }"); locals.Free(); testData = new CompilationTestData(); string error; context.CompileExpression("this.F(1)", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 13 (0xd) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldfld ""C C.<>c__DisplayClass1_0.<>4__this"" IL_0006: ldc.i4.1 IL_0007: callvirt ""void C.F(int)"" IL_000c: ret }"); }); } [Fact] public void MultipleDisplayClasses() { var source = @"class C { void F1(int x) { int F2(int y) { int F3() => x + y; return F3(); }; F2(1); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F1>g__F3|0_1"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyLocal(testData, typeName, locals[0], "<>m0", "x", expectedILOpt: @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ret }"); VerifyLocal(testData, typeName, locals[1], "<>m1", "y", expectedILOpt: @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: ldfld ""int C.<>c__DisplayClass0_1.y"" IL_0006: ret }"); locals.Free(); testData = new CompilationTestData(); string error; context.CompileExpression("x + y", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldarg.1 IL_0007: ldfld ""int C.<>c__DisplayClass0_1.y"" IL_000c: add IL_000d: ret }"); }); } // Should not bind to unnamed display class parameters // (unnamed parameters are treated as named "value"). [Fact] public void CapturedVariableNamedValue() { var source = @"class C { void F(int value) { int G() { return value + 1; }; G(); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>g__G|0_0"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); VerifyLocal(testData, typeName, locals[0], "<>m0", "value", expectedILOpt: @"{ // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.value"" IL_0006: ret }"); locals.Free(); testData = new CompilationTestData(); string error; context.CompileExpression("value", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.value"" IL_0006: ret }"); }); } // Should not bind to unnamed display class parameters // (unnamed parameters are treated as named "value"). [WorkItem(18426, "https://github.com/dotnet/roslyn/issues/18426")] [Fact(Skip = "18426")] public void DisplayClassParameter() { var source = @"class C { void F(int x) { int G() { return x + 1; }; G(); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>g__G|0_0"); var testData = new CompilationTestData(); string error; context.CompileExpression("value", out error, testData); Assert.Equal("error CS0103: The name 'value' does not exist in the current context", error); }); } } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Portable/Binder/Binder_Statements.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This portion of the binder converts StatementSyntax nodes into BoundStatements /// </summary> internal partial class Binder { /// <summary> /// This is the set of parameters and local variables that were used as arguments to /// lock or using statements in enclosing scopes. /// </summary> /// <remarks> /// using (x) { } // x counts /// using (IDisposable y = null) { } // y does not count /// </remarks> internal virtual ImmutableHashSet<Symbol> LockedOrDisposedVariables { get { return Next.LockedOrDisposedVariables; } } /// <remarks> /// Noteworthy override is in MemberSemanticModel.IncrementalBinder (used for caching). /// </remarks> public virtual BoundStatement BindStatement(StatementSyntax node, BindingDiagnosticBag diagnostics) { if (node.AttributeLists.Count > 0) { var attributeList = node.AttributeLists[0]; // Currently, attributes are only allowed on local-functions. if (node.Kind() == SyntaxKind.LocalFunctionStatement) { CheckFeatureAvailability(attributeList, MessageID.IDS_FeatureLocalFunctionAttributes, diagnostics); } else if (node.Kind() != SyntaxKind.Block) { // Don't explicitly error here for blocks. Some codepaths bypass BindStatement // to directly call BindBlock. Error(diagnostics, ErrorCode.ERR_AttributesNotAllowed, attributeList); } } Debug.Assert(node != null); BoundStatement result; switch (node.Kind()) { case SyntaxKind.Block: result = BindBlock((BlockSyntax)node, diagnostics); break; case SyntaxKind.LocalDeclarationStatement: result = BindLocalDeclarationStatement((LocalDeclarationStatementSyntax)node, diagnostics); break; case SyntaxKind.LocalFunctionStatement: result = BindLocalFunctionStatement((LocalFunctionStatementSyntax)node, diagnostics); break; case SyntaxKind.ExpressionStatement: result = BindExpressionStatement((ExpressionStatementSyntax)node, diagnostics); break; case SyntaxKind.IfStatement: result = BindIfStatement((IfStatementSyntax)node, diagnostics); break; case SyntaxKind.SwitchStatement: result = BindSwitchStatement((SwitchStatementSyntax)node, diagnostics); break; case SyntaxKind.DoStatement: result = BindDo((DoStatementSyntax)node, diagnostics); break; case SyntaxKind.WhileStatement: result = BindWhile((WhileStatementSyntax)node, diagnostics); break; case SyntaxKind.ForStatement: result = BindFor((ForStatementSyntax)node, diagnostics); break; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: result = BindForEach((CommonForEachStatementSyntax)node, diagnostics); break; case SyntaxKind.BreakStatement: result = BindBreak((BreakStatementSyntax)node, diagnostics); break; case SyntaxKind.ContinueStatement: result = BindContinue((ContinueStatementSyntax)node, diagnostics); break; case SyntaxKind.ReturnStatement: result = BindReturn((ReturnStatementSyntax)node, diagnostics); break; case SyntaxKind.FixedStatement: result = BindFixedStatement((FixedStatementSyntax)node, diagnostics); break; case SyntaxKind.LabeledStatement: result = BindLabeled((LabeledStatementSyntax)node, diagnostics); break; case SyntaxKind.GotoStatement: case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoDefaultStatement: result = BindGoto((GotoStatementSyntax)node, diagnostics); break; case SyntaxKind.TryStatement: result = BindTryStatement((TryStatementSyntax)node, diagnostics); break; case SyntaxKind.EmptyStatement: result = BindEmpty((EmptyStatementSyntax)node); break; case SyntaxKind.ThrowStatement: result = BindThrow((ThrowStatementSyntax)node, diagnostics); break; case SyntaxKind.UnsafeStatement: result = BindUnsafeStatement((UnsafeStatementSyntax)node, diagnostics); break; case SyntaxKind.UncheckedStatement: case SyntaxKind.CheckedStatement: result = BindCheckedStatement((CheckedStatementSyntax)node, diagnostics); break; case SyntaxKind.UsingStatement: result = BindUsingStatement((UsingStatementSyntax)node, diagnostics); break; case SyntaxKind.YieldBreakStatement: result = BindYieldBreakStatement((YieldStatementSyntax)node, diagnostics); break; case SyntaxKind.YieldReturnStatement: result = BindYieldReturnStatement((YieldStatementSyntax)node, diagnostics); break; case SyntaxKind.LockStatement: result = BindLockStatement((LockStatementSyntax)node, diagnostics); break; default: // NOTE: We could probably throw an exception here, but it's conceivable // that a non-parser syntax tree could reach this point with an unexpected // SyntaxKind and we don't want to throw if that occurs. result = new BoundBadStatement(node, ImmutableArray<BoundNode>.Empty, hasErrors: true); break; } BoundBlock block; Debug.Assert(result.WasCompilerGenerated == false || (result.Kind == BoundKind.Block && (block = (BoundBlock)result).Statements.Length == 1 && block.Statements.Single().WasCompilerGenerated == false), "Synthetic node would not get cached"); Debug.Assert(result.Syntax is StatementSyntax, "BoundStatement should be associated with a statement syntax."); Debug.Assert(System.Linq.Enumerable.Contains(result.Syntax.AncestorsAndSelf(), node), @"Bound statement (or one of its parents) should have same syntax as the given syntax node. Otherwise it may be confusing to the binder cache that uses syntax node as keys."); return result; } private BoundStatement BindCheckedStatement(CheckedStatementSyntax node, BindingDiagnosticBag diagnostics) { return BindEmbeddedBlock(node.Block, diagnostics); } private BoundStatement BindUnsafeStatement(UnsafeStatementSyntax node, BindingDiagnosticBag diagnostics) { var unsafeBinder = this.GetBinder(node); if (!this.Compilation.Options.AllowUnsafe) { Error(diagnostics, ErrorCode.ERR_IllegalUnsafe, node.UnsafeKeyword); } else if (this.IsIndirectlyInIterator) // called *after* we know the binder map has been created. { // Spec 8.2: "An iterator block always defines a safe context, even when its declaration // is nested in an unsafe context." Error(diagnostics, ErrorCode.ERR_IllegalInnerUnsafe, node.UnsafeKeyword); } return BindEmbeddedBlock(node.Block, diagnostics); } private BoundStatement BindFixedStatement(FixedStatementSyntax node, BindingDiagnosticBag diagnostics) { var fixedBinder = this.GetBinder(node); Debug.Assert(fixedBinder != null); fixedBinder.ReportUnsafeIfNotAllowed(node, diagnostics); return fixedBinder.BindFixedStatementParts(node, diagnostics); } private BoundStatement BindFixedStatementParts(FixedStatementSyntax node, BindingDiagnosticBag diagnostics) { VariableDeclarationSyntax declarationSyntax = node.Declaration; ImmutableArray<BoundLocalDeclaration> declarations; BindForOrUsingOrFixedDeclarations(declarationSyntax, LocalDeclarationKind.FixedVariable, diagnostics, out declarations); Debug.Assert(!declarations.IsEmpty); BoundMultipleLocalDeclarations boundMultipleDeclarations = new BoundMultipleLocalDeclarations(declarationSyntax, declarations); BoundStatement boundBody = BindPossibleEmbeddedStatement(node.Statement, diagnostics); return new BoundFixedStatement(node, GetDeclaredLocalsForScope(node), boundMultipleDeclarations, boundBody); } private void CheckRequiredLangVersionForAsyncIteratorMethods(BindingDiagnosticBag diagnostics) { var method = (MethodSymbol)this.ContainingMemberOrLambda; if (method.IsAsync) { MessageID.IDS_FeatureAsyncStreams.CheckFeatureAvailability( diagnostics, method.DeclaringCompilation, method.Locations[0]); } } protected virtual void ValidateYield(YieldStatementSyntax node, BindingDiagnosticBag diagnostics) { Next?.ValidateYield(node, diagnostics); } private BoundStatement BindYieldReturnStatement(YieldStatementSyntax node, BindingDiagnosticBag diagnostics) { ValidateYield(node, diagnostics); TypeSymbol elementType = GetIteratorElementType().Type; BoundExpression argument = (node.Expression == null) ? BadExpression(node).MakeCompilerGenerated() : BindValue(node.Expression, diagnostics, BindValueKind.RValue); argument = ValidateEscape(argument, ExternalScope, isByRef: false, diagnostics: diagnostics); if (!argument.HasAnyErrors) { argument = GenerateConversionForAssignment(elementType, argument, diagnostics); } else { argument = BindToTypeForErrorRecovery(argument); } // NOTE: it's possible that more than one of these conditions is satisfied and that // we won't report the syntactically innermost. However, dev11 appears to check // them in this order, regardless of syntactic nesting (StatementBinder::bindYield). if (this.Flags.Includes(BinderFlags.InFinallyBlock)) { Error(diagnostics, ErrorCode.ERR_BadYieldInFinally, node.YieldKeyword); } else if (this.Flags.Includes(BinderFlags.InTryBlockOfTryCatch)) { Error(diagnostics, ErrorCode.ERR_BadYieldInTryOfCatch, node.YieldKeyword); } else if (this.Flags.Includes(BinderFlags.InCatchBlock)) { Error(diagnostics, ErrorCode.ERR_BadYieldInCatch, node.YieldKeyword); } else if (BindingTopLevelScriptCode) { Error(diagnostics, ErrorCode.ERR_YieldNotAllowedInScript, node.YieldKeyword); } CheckRequiredLangVersionForAsyncIteratorMethods(diagnostics); return new BoundYieldReturnStatement(node, argument); } private BoundStatement BindYieldBreakStatement(YieldStatementSyntax node, BindingDiagnosticBag diagnostics) { if (this.Flags.Includes(BinderFlags.InFinallyBlock)) { Error(diagnostics, ErrorCode.ERR_BadYieldInFinally, node.YieldKeyword); } else if (BindingTopLevelScriptCode) { Error(diagnostics, ErrorCode.ERR_YieldNotAllowedInScript, node.YieldKeyword); } ValidateYield(node, diagnostics); CheckRequiredLangVersionForAsyncIteratorMethods(diagnostics); return new BoundYieldBreakStatement(node); } private BoundStatement BindLockStatement(LockStatementSyntax node, BindingDiagnosticBag diagnostics) { var lockBinder = this.GetBinder(node); Debug.Assert(lockBinder != null); return lockBinder.BindLockStatementParts(diagnostics, lockBinder); } internal virtual BoundStatement BindLockStatementParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindLockStatementParts(diagnostics, originalBinder); } private BoundStatement BindUsingStatement(UsingStatementSyntax node, BindingDiagnosticBag diagnostics) { var usingBinder = this.GetBinder(node); Debug.Assert(usingBinder != null); return usingBinder.BindUsingStatementParts(diagnostics, usingBinder); } internal virtual BoundStatement BindUsingStatementParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindUsingStatementParts(diagnostics, originalBinder); } internal BoundStatement BindPossibleEmbeddedStatement(StatementSyntax node, BindingDiagnosticBag diagnostics) { Binder binder; switch (node.Kind()) { case SyntaxKind.LocalDeclarationStatement: // Local declarations are not legal in contexts where we need embedded statements. diagnostics.Add(ErrorCode.ERR_BadEmbeddedStmt, node.GetLocation()); // fall through goto case SyntaxKind.ExpressionStatement; case SyntaxKind.ExpressionStatement: case SyntaxKind.LockStatement: case SyntaxKind.IfStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.ThrowStatement: binder = this.GetBinder(node); Debug.Assert(binder != null); return binder.WrapWithVariablesIfAny(node, binder.BindStatement(node, diagnostics)); case SyntaxKind.LabeledStatement: case SyntaxKind.LocalFunctionStatement: // Labeled statements and local function statements are not legal in contexts where we need embedded statements. diagnostics.Add(ErrorCode.ERR_BadEmbeddedStmt, node.GetLocation()); binder = this.GetBinder(node); Debug.Assert(binder != null); return binder.WrapWithVariablesAndLocalFunctionsIfAny(node, binder.BindStatement(node, diagnostics)); case SyntaxKind.SwitchStatement: var switchStatement = (SwitchStatementSyntax)node; binder = this.GetBinder(switchStatement.Expression); Debug.Assert(binder != null); return binder.WrapWithVariablesIfAny(switchStatement.Expression, binder.BindStatement(node, diagnostics)); case SyntaxKind.EmptyStatement: var emptyStatement = (EmptyStatementSyntax)node; if (!emptyStatement.SemicolonToken.IsMissing) { switch (node.Parent.Kind()) { case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: case SyntaxKind.WhileStatement: // For loop constructs, only warn if we see a block following the statement. // That indicates code like: "while (x) ; { }" // which is most likely a bug. if (emptyStatement.SemicolonToken.GetNextToken().Kind() != SyntaxKind.OpenBraceToken) { break; } goto default; default: // For non-loop constructs, always warn. This is for code like: // "if (x) ;" which is almost certainly a bug. diagnostics.Add(ErrorCode.WRN_PossibleMistakenNullStatement, node.GetLocation()); break; } } // fall through goto default; default: return BindStatement(node, diagnostics); } } private BoundExpression BindThrownExpression(ExpressionSyntax exprSyntax, BindingDiagnosticBag diagnostics, ref bool hasErrors) { var boundExpr = BindValue(exprSyntax, diagnostics, BindValueKind.RValue); if (Compilation.LanguageVersion < MessageID.IDS_FeatureSwitchExpression.RequiredVersion()) { // This is the pre-C# 8 algorithm for binding a thrown expression. // SPEC VIOLATION: The spec requires the thrown exception to have a type, and that the type // be System.Exception or derived from System.Exception. (Or, if a type parameter, to have // an effective base class that meets that criterion.) However, we allow the literal null // to be thrown, even though it does not meet that criterion and will at runtime always // produce a null reference exception. if (!boundExpr.IsLiteralNull()) { boundExpr = BindToNaturalType(boundExpr, diagnostics); var type = boundExpr.Type; // If the expression is a lambda, anonymous method, or method group then it will // have no compile-time type; give the same error as if the type was wrong. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if ((object)type == null || !type.IsErrorType() && !Compilation.IsExceptionType(type.EffectiveType(ref useSiteInfo), ref useSiteInfo)) { diagnostics.Add(ErrorCode.ERR_BadExceptionType, exprSyntax.Location); hasErrors = true; diagnostics.Add(exprSyntax, useSiteInfo); } else { diagnostics.AddDependencies(useSiteInfo); } } } else { // In C# 8 and later we follow the ECMA specification, which neatly handles null and expressions of exception type. boundExpr = GenerateConversionForAssignment(GetWellKnownType(WellKnownType.System_Exception, diagnostics, exprSyntax), boundExpr, diagnostics); } return boundExpr; } private BoundStatement BindThrow(ThrowStatementSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression boundExpr = null; bool hasErrors = false; ExpressionSyntax exprSyntax = node.Expression; if (exprSyntax != null) { boundExpr = BindThrownExpression(exprSyntax, diagnostics, ref hasErrors); } else if (!this.Flags.Includes(BinderFlags.InCatchBlock)) { diagnostics.Add(ErrorCode.ERR_BadEmptyThrow, node.ThrowKeyword.GetLocation()); hasErrors = true; } else if (this.Flags.Includes(BinderFlags.InNestedFinallyBlock)) { // There's a special error code for a rethrow in a finally clause in a catch clause. // Best guess interpretation: if an exception occurs within the nested try block // (i.e. the one in the catch clause, to which the finally clause is attached), // then it's not clear whether the runtime will try to rethrow the "inner" exception // or the "outer" exception. For this reason, the case is disallowed. diagnostics.Add(ErrorCode.ERR_BadEmptyThrowInFinally, node.ThrowKeyword.GetLocation()); hasErrors = true; } return new BoundThrowStatement(node, boundExpr, hasErrors); } private static BoundStatement BindEmpty(EmptyStatementSyntax node) { return new BoundNoOpStatement(node, NoOpStatementFlavor.Default); } private BoundLabeledStatement BindLabeled(LabeledStatementSyntax node, BindingDiagnosticBag diagnostics) { // TODO: verify that goto label lookup was valid (e.g. error checking of symbol resolution for labels) bool hasError = false; var result = LookupResult.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var binder = this.LookupSymbolsWithFallback(result, node.Identifier.ValueText, arity: 0, useSiteInfo: ref useSiteInfo, options: LookupOptions.LabelsOnly); // result.Symbols can be empty in some malformed code, e.g. when a labeled statement is used an embedded statement in an if or foreach statement // In this case we create new label symbol on the fly, and an error is reported by parser var symbol = result.Symbols.Count > 0 && result.IsMultiViable ? (LabelSymbol)result.Symbols.First() : new SourceLabelSymbol((MethodSymbol)ContainingMemberOrLambda, node.Identifier); if (!symbol.IdentifierNodeOrToken.IsToken || symbol.IdentifierNodeOrToken.AsToken() != node.Identifier) { Error(diagnostics, ErrorCode.ERR_DuplicateLabel, node.Identifier, node.Identifier.ValueText); hasError = true; } // check to see if this label (illegally) hides a label from an enclosing scope if (binder != null) { result.Clear(); binder.Next.LookupSymbolsWithFallback(result, node.Identifier.ValueText, arity: 0, useSiteInfo: ref useSiteInfo, options: LookupOptions.LabelsOnly); if (result.IsMultiViable) { // The label '{0}' shadows another label by the same name in a contained scope Error(diagnostics, ErrorCode.ERR_LabelShadow, node.Identifier, node.Identifier.ValueText); hasError = true; } } diagnostics.Add(node, useSiteInfo); result.Free(); var body = BindStatement(node.Statement, diagnostics); return new BoundLabeledStatement(node, symbol, body, hasError); } private BoundStatement BindGoto(GotoStatementSyntax node, BindingDiagnosticBag diagnostics) { switch (node.Kind()) { case SyntaxKind.GotoStatement: var expression = BindLabel(node.Expression, diagnostics); var boundLabel = expression as BoundLabel; if (boundLabel == null) { // diagnostics already reported return new BoundBadStatement(node, ImmutableArray.Create<BoundNode>(expression), true); } var symbol = boundLabel.Label; return new BoundGotoStatement(node, symbol, null, boundLabel); case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoDefaultStatement: // SPEC: If the goto case statement is not enclosed by a switch statement, a compile-time error occurs. // SPEC: If the goto default statement is not enclosed by a switch statement, a compile-time error occurs. SwitchBinder binder = GetSwitchBinder(this); if (binder == null) { Error(diagnostics, ErrorCode.ERR_InvalidGotoCase, node); ImmutableArray<BoundNode> childNodes; if (node.Expression != null) { var value = BindRValueWithoutTargetType(node.Expression, BindingDiagnosticBag.Discarded); childNodes = ImmutableArray.Create<BoundNode>(value); } else { childNodes = ImmutableArray<BoundNode>.Empty; } return new BoundBadStatement(node, childNodes, true); } return binder.BindGotoCaseOrDefault(node, this, diagnostics); default: throw ExceptionUtilities.UnexpectedValue(node.Kind()); } } private BoundStatement BindLocalFunctionStatement(LocalFunctionStatementSyntax node, BindingDiagnosticBag diagnostics) { // already defined symbol in containing block var localSymbol = this.LookupLocalFunction(node.Identifier); var hasErrors = localSymbol.ScopeBinder .ValidateDeclarationNameConflictsInScope(localSymbol, diagnostics); BoundBlock blockBody = null; BoundBlock expressionBody = null; if (node.Body != null) { blockBody = runAnalysis(BindEmbeddedBlock(node.Body, diagnostics), diagnostics); if (node.ExpressionBody != null) { expressionBody = runAnalysis(BindExpressionBodyAsBlock(node.ExpressionBody, BindingDiagnosticBag.Discarded), BindingDiagnosticBag.Discarded); } } else if (node.ExpressionBody != null) { expressionBody = runAnalysis(BindExpressionBodyAsBlock(node.ExpressionBody, diagnostics), diagnostics); } else if (!hasErrors && (!localSymbol.IsExtern || !localSymbol.IsStatic)) { hasErrors = true; diagnostics.Add(ErrorCode.ERR_LocalFunctionMissingBody, localSymbol.Locations[0], localSymbol); } if (!hasErrors && (blockBody != null || expressionBody != null) && localSymbol.IsExtern) { hasErrors = true; diagnostics.Add(ErrorCode.ERR_ExternHasBody, localSymbol.Locations[0], localSymbol); } Debug.Assert(blockBody != null || expressionBody != null || (localSymbol.IsExtern && localSymbol.IsStatic) || hasErrors); localSymbol.GetDeclarationDiagnostics(diagnostics); Symbol.CheckForBlockAndExpressionBody( node.Body, node.ExpressionBody, node, diagnostics); return new BoundLocalFunctionStatement(node, localSymbol, blockBody, expressionBody, hasErrors); BoundBlock runAnalysis(BoundBlock block, BindingDiagnosticBag blockDiagnostics) { if (block != null) { // Have to do ControlFlowPass here because in MethodCompiler, we don't call this for synthed methods // rather we go directly to LowerBodyOrInitializer, which skips over flow analysis (which is in CompileMethod) // (the same thing - calling ControlFlowPass.Analyze in the lowering - is done for lambdas) // It's a bit of code duplication, but refactoring would make things worse. // However, we don't need to report diagnostics here. They will be reported when analyzing the parent method. var ignored = DiagnosticBag.GetInstance(); var endIsReachable = ControlFlowPass.Analyze(localSymbol.DeclaringCompilation, localSymbol, block, ignored); ignored.Free(); if (endIsReachable) { if (ImplicitReturnIsOkay(localSymbol)) { block = FlowAnalysisPass.AppendImplicitReturn(block, localSymbol); } else { blockDiagnostics.Add(ErrorCode.ERR_ReturnExpected, localSymbol.Locations[0], localSymbol); } } } return block; } } private bool ImplicitReturnIsOkay(MethodSymbol method) { return method.ReturnsVoid || method.IsIterator || method.IsAsyncEffectivelyReturningTask(this.Compilation); } public BoundStatement BindExpressionStatement(ExpressionStatementSyntax node, BindingDiagnosticBag diagnostics) { return BindExpressionStatement(node, node.Expression, node.AllowsAnyExpression, diagnostics); } private BoundExpressionStatement BindExpressionStatement(CSharpSyntaxNode node, ExpressionSyntax syntax, bool allowsAnyExpression, BindingDiagnosticBag diagnostics) { BoundExpressionStatement expressionStatement; var expression = BindRValueWithoutTargetType(syntax, diagnostics); ReportSuppressionIfNeeded(expression, diagnostics); if (!allowsAnyExpression && !IsValidStatementExpression(syntax, expression)) { if (!node.HasErrors) { Error(diagnostics, ErrorCode.ERR_IllegalStatement, syntax); } expressionStatement = new BoundExpressionStatement(node, expression, hasErrors: true); } else { expressionStatement = new BoundExpressionStatement(node, expression); } CheckForUnobservedAwaitable(expression, diagnostics); return expressionStatement; } /// <summary> /// Report an error if this is an awaitable async method invocation that is not being awaited. /// </summary> /// <remarks> /// The checks here are equivalent to StatementBinder::CheckForUnobservedAwaitable() in the native compiler. /// </remarks> private void CheckForUnobservedAwaitable(BoundExpression expression, BindingDiagnosticBag diagnostics) { if (CouldBeAwaited(expression)) { Error(diagnostics, ErrorCode.WRN_UnobservedAwaitableExpression, expression.Syntax); } } internal BoundStatement BindLocalDeclarationStatement(LocalDeclarationStatementSyntax node, BindingDiagnosticBag diagnostics) { if (node.UsingKeyword != default) { return BindUsingDeclarationStatementParts(node, diagnostics); } else { return BindDeclarationStatementParts(node, diagnostics); } } private BoundStatement BindUsingDeclarationStatementParts(LocalDeclarationStatementSyntax node, BindingDiagnosticBag diagnostics) { var usingDeclaration = UsingStatementBinder.BindUsingStatementOrDeclarationFromParts(node, node.UsingKeyword, node.AwaitKeyword, originalBinder: this, usingBinderOpt: null, diagnostics); Debug.Assert(usingDeclaration is BoundUsingLocalDeclarations); return usingDeclaration; } private BoundStatement BindDeclarationStatementParts(LocalDeclarationStatementSyntax node, BindingDiagnosticBag diagnostics) { var typeSyntax = node.Declaration.Type.SkipRef(out _); bool isConst = node.IsConst; bool isVar; AliasSymbol alias; TypeWithAnnotations declType = BindVariableTypeWithAnnotations(node.Declaration, diagnostics, typeSyntax, ref isConst, isVar: out isVar, alias: out alias); var kind = isConst ? LocalDeclarationKind.Constant : LocalDeclarationKind.RegularVariable; var variableList = node.Declaration.Variables; int variableCount = variableList.Count; if (variableCount == 1) { return BindVariableDeclaration(kind, isVar, variableList[0], typeSyntax, declType, alias, diagnostics, includeBoundType: true, associatedSyntaxNode: node); } else { BoundLocalDeclaration[] boundDeclarations = new BoundLocalDeclaration[variableCount]; int i = 0; foreach (var variableDeclarationSyntax in variableList) { bool includeBoundType = i == 0; //To avoid duplicated expressions, only the first declaration should contain the bound type. boundDeclarations[i++] = BindVariableDeclaration(kind, isVar, variableDeclarationSyntax, typeSyntax, declType, alias, diagnostics, includeBoundType); } return new BoundMultipleLocalDeclarations(node, boundDeclarations.AsImmutableOrNull()); } } /// <summary> /// Checks for a Dispose method on <paramref name="expr"/> and returns its <see cref="MethodSymbol"/> if found. /// </summary> /// <param name="expr">Expression on which to perform lookup</param> /// <param name="syntaxNode">The syntax node to perform lookup on</param> /// <param name="diagnostics">Populated with invocation errors, and warnings of near misses</param> /// <returns>The <see cref="MethodSymbol"/> of the Dispose method if one is found, otherwise null.</returns> internal MethodSymbol TryFindDisposePatternMethod(BoundExpression expr, SyntaxNode syntaxNode, bool hasAwait, BindingDiagnosticBag diagnostics) { Debug.Assert(expr is object); Debug.Assert(expr.Type is object); Debug.Assert(expr.Type.IsRefLikeType || hasAwait); // pattern dispose lookup is only valid on ref structs or asynchronous usings var result = PerformPatternMethodLookup(expr, hasAwait ? WellKnownMemberNames.DisposeAsyncMethodName : WellKnownMemberNames.DisposeMethodName, syntaxNode, diagnostics, out var disposeMethod); if (disposeMethod?.IsExtensionMethod == true) { // Extension methods should just be ignored, rather than rejected after-the-fact // Tracked by https://github.com/dotnet/roslyn/issues/32767 // extension methods do not contribute to pattern-based disposal disposeMethod = null; } else if ((!hasAwait && disposeMethod?.ReturnsVoid == false) || result == PatternLookupResult.NotAMethod) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (this.IsAccessible(disposeMethod, ref useSiteInfo)) { diagnostics.Add(ErrorCode.WRN_PatternBadSignature, syntaxNode.Location, expr.Type, MessageID.IDS_Disposable.Localize(), disposeMethod); } diagnostics.Add(syntaxNode, useSiteInfo); disposeMethod = null; } return disposeMethod; } private TypeWithAnnotations BindVariableTypeWithAnnotations(CSharpSyntaxNode declarationNode, BindingDiagnosticBag diagnostics, TypeSyntax typeSyntax, ref bool isConst, out bool isVar, out AliasSymbol alias) { Debug.Assert( declarationNode is VariableDesignationSyntax || declarationNode.Kind() == SyntaxKind.VariableDeclaration || declarationNode.Kind() == SyntaxKind.DeclarationExpression || declarationNode.Kind() == SyntaxKind.DiscardDesignation); // If the type is "var" then suppress errors when binding it. "var" might be a legal type // or it might not; if it is not then we do not want to report an error. If it is, then // we want to treat the declaration as an explicitly typed declaration. TypeWithAnnotations declType = BindTypeOrVarKeyword(typeSyntax.SkipRef(out _), diagnostics, out isVar, out alias); Debug.Assert(declType.HasType || isVar); if (isVar) { // There are a number of ways in which a var decl can be illegal, but in these // cases we should report an error and then keep right on going with the inference. if (isConst) { Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableCannotBeConst, declarationNode); // Keep processing it as a non-const local. isConst = false; } // In the dev10 compiler the error recovery semantics for the illegal case // "var x = 10, y = 123.4;" are somewhat undesirable. // // First off, this is an error because a straw poll of language designers and // users showed that there was no consensus on whether the above should mean // "double x = 10, y = 123.4;", taking the best type available and substituting // that for "var", or treating it as "var x = 10; var y = 123.4;" -- since there // was no consensus we decided to simply make it illegal. // // In dev10 for error recovery in the IDE we do an odd thing -- we simply take // the type of the first variable and use it. So that is "int x = 10, y = 123.4;". // // This seems less than ideal. In the error recovery scenario it probably makes // more sense to treat that as "var x = 10; var y = 123.4;" and do each inference // separately. if (declarationNode.Parent.Kind() == SyntaxKind.LocalDeclarationStatement && ((VariableDeclarationSyntax)declarationNode).Variables.Count > 1 && !declarationNode.HasErrors) { Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, declarationNode); } } else { // In the native compiler when given a situation like // // D[] x; // // where D is a static type we report both that D cannot be an element type // of an array, and that D[] is not a valid type for a local variable. // This seems silly; the first error is entirely sufficient. We no longer // produce additional errors for local variables of arrays of static types. if (declType.IsStatic) { Error(diagnostics, ErrorCode.ERR_VarDeclIsStaticClass, typeSyntax, declType.Type); } if (isConst && !declType.Type.CanBeConst()) { Error(diagnostics, ErrorCode.ERR_BadConstType, typeSyntax, declType.Type); // Keep processing it as a non-const local. isConst = false; } } return declType; } internal BoundExpression BindInferredVariableInitializer(BindingDiagnosticBag diagnostics, RefKind refKind, EqualsValueClauseSyntax initializer, CSharpSyntaxNode errorSyntax) { BindValueKind valueKind; ExpressionSyntax value; IsInitializerRefKindValid(initializer, initializer, refKind, diagnostics, out valueKind, out value); // The return value isn't important here; we just want the diagnostics and the BindValueKind return BindInferredVariableInitializer(diagnostics, value, valueKind, errorSyntax); } // The location where the error is reported might not be the initializer. protected BoundExpression BindInferredVariableInitializer(BindingDiagnosticBag diagnostics, ExpressionSyntax initializer, BindValueKind valueKind, CSharpSyntaxNode errorSyntax) { if (initializer == null) { if (!errorSyntax.HasErrors) { Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, errorSyntax); } return null; } if (initializer.Kind() == SyntaxKind.ArrayInitializerExpression) { var result = BindUnexpectedArrayInitializer((InitializerExpressionSyntax)initializer, diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableAssignedArrayInitializer, errorSyntax); return CheckValue(result, valueKind, diagnostics); } BoundExpression value = BindValue(initializer, diagnostics, valueKind); BoundExpression expression = value.Kind is BoundKind.UnboundLambda or BoundKind.MethodGroup ? BindToInferredDelegateType(value, diagnostics) : BindToNaturalType(value, diagnostics); // Certain expressions (null literals, method groups and anonymous functions) have no type of // their own and therefore cannot be the initializer of an implicitly typed local. if (!expression.HasAnyErrors && !expression.HasExpressionType()) { // Cannot assign {0} to an implicitly-typed local variable Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, errorSyntax, expression.Display); } return expression; } private static bool IsInitializerRefKindValid( EqualsValueClauseSyntax initializer, CSharpSyntaxNode node, RefKind variableRefKind, BindingDiagnosticBag diagnostics, out BindValueKind valueKind, out ExpressionSyntax value) { RefKind expressionRefKind = RefKind.None; value = initializer?.Value.CheckAndUnwrapRefExpression(diagnostics, out expressionRefKind); if (variableRefKind == RefKind.None) { valueKind = BindValueKind.RValue; if (expressionRefKind == RefKind.Ref) { Error(diagnostics, ErrorCode.ERR_InitializeByValueVariableWithReference, node); return false; } } else { valueKind = variableRefKind == RefKind.RefReadOnly ? BindValueKind.ReadonlyRef : BindValueKind.RefOrOut; if (initializer == null) { Error(diagnostics, ErrorCode.ERR_ByReferenceVariableMustBeInitialized, node); return false; } else if (expressionRefKind != RefKind.Ref) { Error(diagnostics, ErrorCode.ERR_InitializeByReferenceVariableWithValue, node); return false; } } return true; } protected BoundLocalDeclaration BindVariableDeclaration( LocalDeclarationKind kind, bool isVar, VariableDeclaratorSyntax declarator, TypeSyntax typeSyntax, TypeWithAnnotations declTypeOpt, AliasSymbol aliasOpt, BindingDiagnosticBag diagnostics, bool includeBoundType, CSharpSyntaxNode associatedSyntaxNode = null) { Debug.Assert(declarator != null); return BindVariableDeclaration(LocateDeclaredVariableSymbol(declarator, typeSyntax, kind), kind, isVar, declarator, typeSyntax, declTypeOpt, aliasOpt, diagnostics, includeBoundType, associatedSyntaxNode); } protected BoundLocalDeclaration BindVariableDeclaration( SourceLocalSymbol localSymbol, LocalDeclarationKind kind, bool isVar, VariableDeclaratorSyntax declarator, TypeSyntax typeSyntax, TypeWithAnnotations declTypeOpt, AliasSymbol aliasOpt, BindingDiagnosticBag diagnostics, bool includeBoundType, CSharpSyntaxNode associatedSyntaxNode = null) { Debug.Assert(declarator != null); Debug.Assert(declTypeOpt.HasType || isVar); Debug.Assert(typeSyntax != null); var localDiagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, diagnostics.AccumulatesDependencies); // if we are not given desired syntax, we use declarator associatedSyntaxNode = associatedSyntaxNode ?? declarator; // Check for variable declaration errors. // Use the binder that owns the scope for the local because this (the current) binder // might own nested scope. bool nameConflict = localSymbol.ScopeBinder.ValidateDeclarationNameConflictsInScope(localSymbol, diagnostics); bool hasErrors = false; if (localSymbol.RefKind != RefKind.None) { CheckRefLocalInAsyncOrIteratorMethod(localSymbol.IdentifierToken, diagnostics); } EqualsValueClauseSyntax equalsClauseSyntax = declarator.Initializer; BindValueKind valueKind; ExpressionSyntax value; if (!IsInitializerRefKindValid(equalsClauseSyntax, declarator, localSymbol.RefKind, diagnostics, out valueKind, out value)) { hasErrors = true; } BoundExpression initializerOpt; if (isVar) { aliasOpt = null; initializerOpt = BindInferredVariableInitializer(diagnostics, value, valueKind, declarator); // If we got a good result then swap the inferred type for the "var" TypeSymbol initializerType = initializerOpt?.Type; if ((object)initializerType != null) { declTypeOpt = TypeWithAnnotations.Create(initializerType); if (declTypeOpt.IsVoidType()) { Error(localDiagnostics, ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, declarator, declTypeOpt.Type); declTypeOpt = TypeWithAnnotations.Create(CreateErrorType("var")); hasErrors = true; } if (!declTypeOpt.Type.IsErrorType()) { if (declTypeOpt.IsStatic) { Error(localDiagnostics, ErrorCode.ERR_VarDeclIsStaticClass, typeSyntax, initializerType); hasErrors = true; } } } else { declTypeOpt = TypeWithAnnotations.Create(CreateErrorType("var")); hasErrors = true; } } else { if (ReferenceEquals(equalsClauseSyntax, null)) { initializerOpt = null; } else { // Basically inlined BindVariableInitializer, but with conversion optional. initializerOpt = BindPossibleArrayInitializer(value, declTypeOpt.Type, valueKind, diagnostics); if (kind != LocalDeclarationKind.FixedVariable) { // If this is for a fixed statement, we'll do our own conversion since there are some special cases. initializerOpt = GenerateConversionForAssignment( declTypeOpt.Type, initializerOpt, localDiagnostics, isRefAssignment: localSymbol.RefKind != RefKind.None); } } } Debug.Assert(declTypeOpt.HasType); if (kind == LocalDeclarationKind.FixedVariable) { // NOTE: this is an error, but it won't prevent further binding. if (isVar) { if (!hasErrors) { Error(localDiagnostics, ErrorCode.ERR_ImplicitlyTypedLocalCannotBeFixed, declarator); hasErrors = true; } } if (!declTypeOpt.Type.IsPointerType()) { if (!hasErrors) { Error(localDiagnostics, declTypeOpt.Type.IsFunctionPointer() ? ErrorCode.ERR_CannotUseFunctionPointerAsFixedLocal : ErrorCode.ERR_BadFixedInitType, declarator); hasErrors = true; } } else if (!IsValidFixedVariableInitializer(declTypeOpt.Type, localSymbol, ref initializerOpt, localDiagnostics)) { hasErrors = true; } } if (CheckRestrictedTypeInAsyncMethod(this.ContainingMemberOrLambda, declTypeOpt.Type, localDiagnostics, typeSyntax)) { hasErrors = true; } localSymbol.SetTypeWithAnnotations(declTypeOpt); if (initializerOpt != null) { var currentScope = LocalScopeDepth; localSymbol.SetValEscape(GetValEscape(initializerOpt, currentScope)); if (localSymbol.RefKind != RefKind.None) { localSymbol.SetRefEscape(GetRefEscape(initializerOpt, currentScope)); } } ImmutableArray<BoundExpression> arguments = BindDeclaratorArguments(declarator, localDiagnostics); if (kind == LocalDeclarationKind.FixedVariable || kind == LocalDeclarationKind.UsingVariable) { // CONSIDER: The error message is "you must provide an initializer in a fixed // CONSIDER: or using declaration". The error message could be targeted to // CONSIDER: the actual situation. "you must provide an initializer in a // CONSIDER: 'fixed' declaration." if (initializerOpt == null) { Error(localDiagnostics, ErrorCode.ERR_FixedMustInit, declarator); hasErrors = true; } } else if (kind == LocalDeclarationKind.Constant && initializerOpt != null && !localDiagnostics.HasAnyResolvedErrors()) { var constantValueDiagnostics = localSymbol.GetConstantValueDiagnostics(initializerOpt); diagnostics.AddRange(constantValueDiagnostics, allowMismatchInDependencyAccumulation: true); hasErrors = constantValueDiagnostics.Diagnostics.HasAnyErrors(); } diagnostics.AddRangeAndFree(localDiagnostics); BoundTypeExpression boundDeclType = null; if (includeBoundType) { var invalidDimensions = ArrayBuilder<BoundExpression>.GetInstance(); typeSyntax.VisitRankSpecifiers((rankSpecifier, args) => { bool _ = false; foreach (var expressionSyntax in rankSpecifier.Sizes) { var size = args.binder.BindArrayDimension(expressionSyntax, args.diagnostics, ref _); if (size != null) { args.invalidDimensions.Add(size); } } }, (binder: this, invalidDimensions: invalidDimensions, diagnostics: diagnostics)); boundDeclType = new BoundTypeExpression(typeSyntax, aliasOpt, dimensionsOpt: invalidDimensions.ToImmutableAndFree(), typeWithAnnotations: declTypeOpt); } return new BoundLocalDeclaration( syntax: associatedSyntaxNode, localSymbol: localSymbol, declaredTypeOpt: boundDeclType, initializerOpt: hasErrors ? BindToTypeForErrorRecovery(initializerOpt)?.WithHasErrors() : initializerOpt, argumentsOpt: arguments, inferredType: isVar, hasErrors: hasErrors | nameConflict); } protected bool CheckRefLocalInAsyncOrIteratorMethod(SyntaxToken identifierToken, BindingDiagnosticBag diagnostics) { if (IsInAsyncMethod()) { Error(diagnostics, ErrorCode.ERR_BadAsyncLocalType, identifierToken); return true; } else if (IsDirectlyInIterator) { Error(diagnostics, ErrorCode.ERR_BadIteratorLocalType, identifierToken); return true; } return false; } internal ImmutableArray<BoundExpression> BindDeclaratorArguments(VariableDeclaratorSyntax declarator, BindingDiagnosticBag diagnostics) { // It is possible that we have a bracketed argument list, like "int x[];" or "int x[123];" // in a non-fixed-size-array declaration . This is a common error made by C++ programmers. // We have already given a good error at parse time telling the user to either make it "fixed" // or to move the brackets to the type. However, we should still do semantic analysis of // the arguments, so that errors in them are discovered, hovering over them in the IDE // gives good results, and so on. var arguments = default(ImmutableArray<BoundExpression>); if (declarator.ArgumentList != null) { AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); BindArgumentsAndNames(declarator.ArgumentList, diagnostics, analyzedArguments); arguments = BuildArgumentsForErrorRecovery(analyzedArguments); analyzedArguments.Free(); } return arguments; } private SourceLocalSymbol LocateDeclaredVariableSymbol(VariableDeclaratorSyntax declarator, TypeSyntax typeSyntax, LocalDeclarationKind outerKind) { LocalDeclarationKind kind = outerKind == LocalDeclarationKind.UsingVariable ? LocalDeclarationKind.UsingVariable : LocalDeclarationKind.RegularVariable; return LocateDeclaredVariableSymbol(declarator.Identifier, typeSyntax, declarator.Initializer, kind); } private SourceLocalSymbol LocateDeclaredVariableSymbol(SyntaxToken identifier, TypeSyntax typeSyntax, EqualsValueClauseSyntax equalsValue, LocalDeclarationKind kind) { SourceLocalSymbol localSymbol = this.LookupLocal(identifier); // In error scenarios with misplaced code, it is possible we can't bind the local declaration. // This occurs through the semantic model. In that case concoct a plausible result. if ((object)localSymbol == null) { localSymbol = SourceLocalSymbol.MakeLocal( ContainingMemberOrLambda, this, false, // do not allow ref typeSyntax, identifier, kind, equalsValue); } return localSymbol; } private bool IsValidFixedVariableInitializer(TypeSymbol declType, SourceLocalSymbol localSymbol, ref BoundExpression initializerOpt, BindingDiagnosticBag diagnostics) { Debug.Assert(!ReferenceEquals(declType, null)); Debug.Assert(declType.IsPointerType()); if (initializerOpt?.HasAnyErrors != false) { return false; } TypeSymbol initializerType = initializerOpt.Type; SyntaxNode initializerSyntax = initializerOpt.Syntax; if ((object)initializerType == null) { Error(diagnostics, ErrorCode.ERR_ExprCannotBeFixed, initializerSyntax); return false; } TypeSymbol elementType; bool hasErrors = false; MethodSymbol fixedPatternMethod = null; switch (initializerOpt.Kind) { case BoundKind.AddressOfOperator: elementType = ((BoundAddressOfOperator)initializerOpt).Operand.Type; break; case BoundKind.FieldAccess: var fa = (BoundFieldAccess)initializerOpt; if (fa.FieldSymbol.IsFixedSizeBuffer) { elementType = ((PointerTypeSymbol)fa.Type).PointedAtType; break; } goto default; default: // fixed (T* variable = <expr>) ... // check for arrays if (initializerType.IsArray()) { // See ExpressionBinder::BindPtrToArray (though most of that functionality is now in LocalRewriter). elementType = ((ArrayTypeSymbol)initializerType).ElementType; break; } // check for a special ref-returning method var additionalDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); fixedPatternMethod = GetFixedPatternMethodOpt(initializerOpt, additionalDiagnostics); // check for String // NOTE: We will allow the pattern method to take precedence, but only if it is an instance member of System.String if (initializerType.SpecialType == SpecialType.System_String && ((object)fixedPatternMethod == null || fixedPatternMethod.ContainingType.SpecialType != SpecialType.System_String)) { fixedPatternMethod = null; elementType = this.GetSpecialType(SpecialType.System_Char, diagnostics, initializerSyntax); additionalDiagnostics.Free(); break; } // if the feature was enabled, but something went wrong with the method, report that, otherwise don't. // If feature is not enabled, additional errors would be just noise. bool extensibleFixedEnabled = ((CSharpParseOptions)initializerOpt.SyntaxTree.Options)?.IsFeatureEnabled(MessageID.IDS_FeatureExtensibleFixedStatement) != false; if (extensibleFixedEnabled) { diagnostics.AddRange(additionalDiagnostics); } additionalDiagnostics.Free(); if ((object)fixedPatternMethod != null) { elementType = fixedPatternMethod.ReturnType; CheckFeatureAvailability(initializerOpt.Syntax, MessageID.IDS_FeatureExtensibleFixedStatement, diagnostics); break; } else { Error(diagnostics, ErrorCode.ERR_ExprCannotBeFixed, initializerSyntax); return false; } } if (CheckManagedAddr(Compilation, elementType, initializerSyntax.Location, diagnostics)) { hasErrors = true; } initializerOpt = BindToNaturalType(initializerOpt, diagnostics, reportNoTargetType: false); initializerOpt = GetFixedLocalCollectionInitializer(initializerOpt, elementType, declType, fixedPatternMethod, hasErrors, diagnostics); return true; } private MethodSymbol GetFixedPatternMethodOpt(BoundExpression initializer, BindingDiagnosticBag additionalDiagnostics) { if (initializer.Type.IsVoidType()) { return null; } const string methodName = "GetPinnableReference"; var result = PerformPatternMethodLookup(initializer, methodName, initializer.Syntax, additionalDiagnostics, out var patternMethodSymbol); if (patternMethodSymbol is null) { return null; } if (HasOptionalOrVariableParameters(patternMethodSymbol) || patternMethodSymbol.ReturnsVoid || !patternMethodSymbol.RefKind.IsManagedReference() || !(patternMethodSymbol.ParameterCount == 0 || patternMethodSymbol.IsStatic && patternMethodSymbol.ParameterCount == 1)) { // the method does not fit the pattern additionalDiagnostics.Add(ErrorCode.WRN_PatternBadSignature, initializer.Syntax.Location, initializer.Type, "fixed", patternMethodSymbol); return null; } return patternMethodSymbol; } /// <summary> /// Wrap the initializer in a BoundFixedLocalCollectionInitializer so that the rewriter will have the /// information it needs (e.g. conversions, helper methods). /// </summary> private BoundExpression GetFixedLocalCollectionInitializer( BoundExpression initializer, TypeSymbol elementType, TypeSymbol declType, MethodSymbol patternMethodOpt, bool hasErrors, BindingDiagnosticBag diagnostics) { Debug.Assert(initializer != null); SyntaxNode initializerSyntax = initializer.Syntax; TypeSymbol pointerType = new PointerTypeSymbol(TypeWithAnnotations.Create(elementType)); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion elementConversion = this.Conversions.ClassifyConversionFromType(pointerType, declType, ref useSiteInfo); diagnostics.Add(initializerSyntax, useSiteInfo); if (!elementConversion.IsValid || !elementConversion.IsImplicit) { GenerateImplicitConversionError(diagnostics, this.Compilation, initializerSyntax, elementConversion, pointerType, declType); hasErrors = true; } return new BoundFixedLocalCollectionInitializer( initializerSyntax, pointerType, elementConversion, initializer, patternMethodOpt, declType, hasErrors); } private BoundExpression BindAssignment(AssignmentExpressionSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Debug.Assert(node.Left != null); Debug.Assert(node.Right != null); node.Left.CheckDeconstructionCompatibleArgument(diagnostics); if (node.Left.Kind() == SyntaxKind.TupleExpression || node.Left.Kind() == SyntaxKind.DeclarationExpression) { return BindDeconstruction(node, diagnostics); } BindValueKind lhsKind; BindValueKind rhsKind; ExpressionSyntax rhsExpr; bool isRef = false; if (node.Right.Kind() == SyntaxKind.RefExpression) { isRef = true; lhsKind = BindValueKind.RefAssignable; rhsKind = BindValueKind.RefersToLocation; rhsExpr = ((RefExpressionSyntax)node.Right).Expression; } else { lhsKind = BindValueKind.Assignable; rhsKind = BindValueKind.RValue; rhsExpr = node.Right; } var op1 = BindValue(node.Left, diagnostics, lhsKind); ReportSuppressionIfNeeded(op1, diagnostics); var lhsRefKind = RefKind.None; // If the LHS is a ref (not ref-readonly), the rhs // must also be value-assignable if (lhsKind == BindValueKind.RefAssignable && !op1.HasErrors) { // We should now know that op1 is a valid lvalue lhsRefKind = op1.GetRefKind(); if (lhsRefKind == RefKind.Ref || lhsRefKind == RefKind.Out) { rhsKind |= BindValueKind.Assignable; } } var op2 = BindValue(rhsExpr, diagnostics, rhsKind); if (op1.Kind == BoundKind.DiscardExpression) { op2 = BindToNaturalType(op2, diagnostics); op1 = InferTypeForDiscardAssignment((BoundDiscardExpression)op1, op2, diagnostics); } return BindAssignment(node, op1, op2, isRef, diagnostics); } private BoundExpression InferTypeForDiscardAssignment(BoundDiscardExpression op1, BoundExpression op2, BindingDiagnosticBag diagnostics) { var inferredType = op2.Type; if ((object)inferredType == null) { return op1.FailInference(this, diagnostics); } if (inferredType.IsVoidType()) { diagnostics.Add(ErrorCode.ERR_VoidAssignment, op1.Syntax.Location); } return op1.SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(inferredType)); } private BoundAssignmentOperator BindAssignment( SyntaxNode node, BoundExpression op1, BoundExpression op2, bool isRef, BindingDiagnosticBag diagnostics) { Debug.Assert(op1 != null); Debug.Assert(op2 != null); bool hasErrors = op1.HasAnyErrors || op2.HasAnyErrors; if (!op1.HasAnyErrors) { // Build bound conversion. The node might not be used if this is a dynamic conversion // but diagnostics should be reported anyways. var conversion = GenerateConversionForAssignment(op1.Type, op2, diagnostics, isRefAssignment: isRef); // If the result is a dynamic assignment operation (SetMember or SetIndex), // don't generate the boxing conversion to the dynamic type. // Leave the values as they are, and deal with the conversions at runtime. if (op1.Kind != BoundKind.DynamicIndexerAccess && op1.Kind != BoundKind.DynamicMemberAccess && op1.Kind != BoundKind.DynamicObjectInitializerMember) { op2 = conversion; } else { op2 = BindToNaturalType(op2, diagnostics); } if (isRef) { var leftEscape = GetRefEscape(op1, LocalScopeDepth); var rightEscape = GetRefEscape(op2, LocalScopeDepth); if (leftEscape < rightEscape) { Error(diagnostics, ErrorCode.ERR_RefAssignNarrower, node, op1.ExpressionSymbol.Name, op2.Syntax); op2 = ToBadExpression(op2); } } if (op1.Type.IsRefLikeType) { var leftEscape = GetValEscape(op1, LocalScopeDepth); op2 = ValidateEscape(op2, leftEscape, isByRef: false, diagnostics); } } else { op2 = BindToTypeForErrorRecovery(op2); } TypeSymbol type; if ((op1.Kind == BoundKind.EventAccess) && ((BoundEventAccess)op1).EventSymbol.IsWindowsRuntimeEvent) { // Event assignment is a call to void WindowsRuntimeMarshal.AddEventHandler<T>(). type = this.GetSpecialType(SpecialType.System_Void, diagnostics, node); } else { type = op1.Type; } return new BoundAssignmentOperator(node, op1, op2, isRef, type, hasErrors); } private static PropertySymbol GetPropertySymbol(BoundExpression expr, out BoundExpression receiver, out SyntaxNode propertySyntax) { PropertySymbol propertySymbol; switch (expr.Kind) { case BoundKind.PropertyAccess: { var propertyAccess = (BoundPropertyAccess)expr; receiver = propertyAccess.ReceiverOpt; propertySymbol = propertyAccess.PropertySymbol; } break; case BoundKind.IndexerAccess: { var indexerAccess = (BoundIndexerAccess)expr; receiver = indexerAccess.ReceiverOpt; propertySymbol = indexerAccess.Indexer; } break; case BoundKind.IndexOrRangePatternIndexerAccess: { var patternIndexer = (BoundIndexOrRangePatternIndexerAccess)expr; receiver = patternIndexer.Receiver; propertySymbol = (PropertySymbol)patternIndexer.PatternSymbol; } break; default: receiver = null; propertySymbol = null; propertySyntax = null; return null; } var syntax = expr.Syntax; switch (syntax.Kind()) { case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: propertySyntax = ((MemberAccessExpressionSyntax)syntax).Name; break; case SyntaxKind.IdentifierName: propertySyntax = syntax; break; case SyntaxKind.ElementAccessExpression: propertySyntax = ((ElementAccessExpressionSyntax)syntax).ArgumentList; break; default: // Other syntax types, such as QualifiedName, // might occur in invalid code. propertySyntax = syntax; break; } return propertySymbol; } private static SyntaxNode GetEventName(BoundEventAccess expr) { SyntaxNode syntax = expr.Syntax; switch (syntax.Kind()) { case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: return ((MemberAccessExpressionSyntax)syntax).Name; case SyntaxKind.QualifiedName: // This case is reachable only through SemanticModel return ((QualifiedNameSyntax)syntax).Right; case SyntaxKind.IdentifierName: return syntax; case SyntaxKind.MemberBindingExpression: return ((MemberBindingExpressionSyntax)syntax).Name; default: throw ExceptionUtilities.UnexpectedValue(syntax.Kind()); } } /// <summary> /// There are two BadEventUsage error codes and this method decides which one should /// be used for a given event. /// </summary> private DiagnosticInfo GetBadEventUsageDiagnosticInfo(EventSymbol eventSymbol) { var leastOverridden = (EventSymbol)eventSymbol.GetLeastOverriddenMember(this.ContainingType); return leastOverridden.HasAssociatedField ? new CSDiagnosticInfo(ErrorCode.ERR_BadEventUsage, leastOverridden, leastOverridden.ContainingType) : new CSDiagnosticInfo(ErrorCode.ERR_BadEventUsageNoField, leastOverridden); } internal static bool AccessingAutoPropertyFromConstructor(BoundPropertyAccess propertyAccess, Symbol fromMember) { return AccessingAutoPropertyFromConstructor(propertyAccess.ReceiverOpt, propertyAccess.PropertySymbol, fromMember); } private static bool AccessingAutoPropertyFromConstructor(BoundExpression receiver, PropertySymbol propertySymbol, Symbol fromMember) { if (!propertySymbol.IsDefinition && propertySymbol.ContainingType.Equals(propertySymbol.ContainingType.OriginalDefinition, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { propertySymbol = propertySymbol.OriginalDefinition; } var sourceProperty = propertySymbol as SourcePropertySymbolBase; var propertyIsStatic = propertySymbol.IsStatic; return (object)sourceProperty != null && sourceProperty.IsAutoPropertyWithGetAccessor && TypeSymbol.Equals(sourceProperty.ContainingType, fromMember.ContainingType, TypeCompareKind.ConsiderEverything2) && IsConstructorOrField(fromMember, isStatic: propertyIsStatic) && (propertyIsStatic || receiver.Kind == BoundKind.ThisReference); } private static bool IsConstructorOrField(Symbol member, bool isStatic) { return (member as MethodSymbol)?.MethodKind == (isStatic ? MethodKind.StaticConstructor : MethodKind.Constructor) || (member as FieldSymbol)?.IsStatic == isStatic; } private TypeSymbol GetAccessThroughType(BoundExpression receiver) { if (receiver == null) { return this.ContainingType; } else if (receiver.Kind == BoundKind.BaseReference) { // Allow protected access to members defined // in base classes. See spec section 3.5.3. return null; } else { Debug.Assert((object)receiver.Type != null); return receiver.Type; } } private BoundExpression BindPossibleArrayInitializer( ExpressionSyntax node, TypeSymbol destinationType, BindValueKind valueKind, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); if (node.Kind() != SyntaxKind.ArrayInitializerExpression) { return BindValue(node, diagnostics, valueKind); } BoundExpression result; if (destinationType.Kind == SymbolKind.ArrayType) { result = BindArrayCreationWithInitializer(diagnostics, null, (InitializerExpressionSyntax)node, (ArrayTypeSymbol)destinationType, ImmutableArray<BoundExpression>.Empty); } else { result = BindUnexpectedArrayInitializer((InitializerExpressionSyntax)node, diagnostics, ErrorCode.ERR_ArrayInitToNonArrayType); } return CheckValue(result, valueKind, diagnostics); } protected virtual SourceLocalSymbol LookupLocal(SyntaxToken nameToken) { return Next.LookupLocal(nameToken); } protected virtual LocalFunctionSymbol LookupLocalFunction(SyntaxToken nameToken) { return Next.LookupLocalFunction(nameToken); } /// <summary> /// Returns a value that tells how many local scopes are visible, including the current. /// I.E. outside of any method will be 0 /// immediately inside a method - 1 /// </summary> internal virtual uint LocalScopeDepth => Next.LocalScopeDepth; internal virtual BoundBlock BindEmbeddedBlock(BlockSyntax node, BindingDiagnosticBag diagnostics) { return BindBlock(node, diagnostics); } private BoundBlock BindBlock(BlockSyntax node, BindingDiagnosticBag diagnostics) { if (node.AttributeLists.Count > 0) { Error(diagnostics, ErrorCode.ERR_AttributesNotAllowed, node.AttributeLists[0]); } var binder = GetBinder(node); Debug.Assert(binder != null); return binder.BindBlockParts(node, diagnostics); } private BoundBlock BindBlockParts(BlockSyntax node, BindingDiagnosticBag diagnostics) { var syntaxStatements = node.Statements; int nStatements = syntaxStatements.Count; ArrayBuilder<BoundStatement> boundStatements = ArrayBuilder<BoundStatement>.GetInstance(nStatements); for (int i = 0; i < nStatements; i++) { var boundStatement = BindStatement(syntaxStatements[i], diagnostics); boundStatements.Add(boundStatement); } return FinishBindBlockParts(node, boundStatements.ToImmutableAndFree(), diagnostics); } private BoundBlock FinishBindBlockParts(CSharpSyntaxNode node, ImmutableArray<BoundStatement> boundStatements, BindingDiagnosticBag diagnostics) { ImmutableArray<LocalSymbol> locals = GetDeclaredLocalsForScope(node); if (IsDirectlyInIterator) { var method = ContainingMemberOrLambda as MethodSymbol; if ((object)method != null) { method.IteratorElementTypeWithAnnotations = GetIteratorElementType(); } else { Debug.Assert(diagnostics.DiagnosticBag is null || !diagnostics.DiagnosticBag.IsEmptyWithoutResolution); } } return new BoundBlock( node, locals, GetDeclaredLocalFunctionsForScope(node), boundStatements); } internal BoundExpression GenerateConversionForAssignment(TypeSymbol targetType, BoundExpression expression, BindingDiagnosticBag diagnostics, bool isDefaultParameter = false, bool isRefAssignment = false) { Debug.Assert((object)targetType != null); Debug.Assert(expression != null); // We wish to avoid "cascading" errors, so if the expression we are // attempting to convert to a type had errors, suppress additional // diagnostics. However, if the expression // with errors is an unbound lambda then the errors are almost certainly // syntax errors. For error recovery analysis purposes we wish to bind // error lambdas like "Action<int> f = x=>{ x. };" because IntelliSense // needs to know that x is of type int. if (expression.HasAnyErrors && expression.Kind != BoundKind.UnboundLambda) { diagnostics = BindingDiagnosticBag.Discarded; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var conversion = this.Conversions.ClassifyConversionFromExpression(expression, targetType, ref useSiteInfo); diagnostics.Add(expression.Syntax, useSiteInfo); if (isRefAssignment) { if (conversion.Kind != ConversionKind.Identity) { Error(diagnostics, ErrorCode.ERR_RefAssignmentMustHaveIdentityConversion, expression.Syntax, targetType); } else { return expression; } } else if (!conversion.IsImplicit || !conversion.IsValid) { // We suppress conversion errors on default parameters; eg, // if someone says "void M(string s = 123) {}". We will report // a special error in the default parameter binder. if (!isDefaultParameter) { GenerateImplicitConversionError(diagnostics, expression.Syntax, conversion, expression, targetType); } // Suppress any additional diagnostics diagnostics = BindingDiagnosticBag.Discarded; } return CreateConversion(expression.Syntax, expression, conversion, isCast: false, conversionGroupOpt: null, targetType, diagnostics); } #nullable enable internal void GenerateAnonymousFunctionConversionError(BindingDiagnosticBag diagnostics, SyntaxNode syntax, UnboundLambda anonymousFunction, TypeSymbol targetType) { Debug.Assert((object)targetType != null); Debug.Assert(anonymousFunction != null); // Is the target type simply bad? // If the target type is an error then we've already reported a diagnostic. Don't bother // reporting the conversion error. if (targetType.IsErrorType()) { return; } // CONSIDER: Instead of computing this again, cache the reason why the conversion failed in // CONSIDER: the Conversion result, and simply report that. var reason = Conversions.IsAnonymousFunctionCompatibleWithType(anonymousFunction, targetType); // It is possible that the conversion from lambda to delegate is just fine, and // that we ended up here because the target type, though itself is not an error // type, contains a type argument which is an error type. For example, converting // (Goo goo)=>{} to Action<Goo> is a perfectly legal conversion even if Goo is undefined! // In that case we have already reported an error that Goo is undefined, so just bail out. if (reason == LambdaConversionResult.Success) { return; } var id = anonymousFunction.MessageID.Localize(); if (reason == LambdaConversionResult.BadTargetType) { if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, targetType, node: syntax)) { return; } // Cannot convert {0} to type '{1}' because it is not a delegate type Error(diagnostics, ErrorCode.ERR_AnonMethToNonDel, syntax, id, targetType); return; } if (reason == LambdaConversionResult.ExpressionTreeMustHaveDelegateTypeArgument) { Debug.Assert(targetType.IsExpressionTree()); Error(diagnostics, ErrorCode.ERR_ExpressionTreeMustHaveDelegate, syntax, ((NamedTypeSymbol)targetType).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type); return; } if (reason == LambdaConversionResult.ExpressionTreeFromAnonymousMethod) { Debug.Assert(targetType.IsGenericOrNonGenericExpressionType(out _)); Error(diagnostics, ErrorCode.ERR_AnonymousMethodToExpressionTree, syntax); return; } if (reason == LambdaConversionResult.MismatchedReturnType) { Error(diagnostics, ErrorCode.ERR_CantConvAnonMethReturnType, syntax, id, targetType); return; } // At this point we know that we have either a delegate type or an expression type for the target. // The target type is a valid delegate or expression tree type. Is there something wrong with the // parameter list? // First off, is there a parameter list at all? if (reason == LambdaConversionResult.MissingSignatureWithOutParameter) { // COMPATIBILITY: The C# 4 compiler produces two errors for: // // delegate void D (out int x); // ... // D d = delegate {}; // // error CS1676: Parameter 1 must be declared with the 'out' keyword // error CS1688: Cannot convert anonymous method block without a parameter list // to delegate type 'D' because it has one or more out parameters // // This seems redundant, (because there is no "parameter 1" in the source code) // and unnecessary. I propose that we eliminate the first error. Error(diagnostics, ErrorCode.ERR_CantConvAnonMethNoParams, syntax, targetType); return; } var delegateType = targetType.GetDelegateType(); Debug.Assert(delegateType is not null); // There is a parameter list. Does it have the right number of elements? if (reason == LambdaConversionResult.BadParameterCount) { // Delegate '{0}' does not take {1} arguments Error(diagnostics, ErrorCode.ERR_BadDelArgCount, syntax, delegateType, anonymousFunction.ParameterCount); return; } // The parameter list exists and had the right number of parameters. Were any of its types bad? // If any parameter type of the lambda is an error type then suppress // further errors. We've already reported errors on the bad type. if (anonymousFunction.HasExplicitlyTypedParameterList) { for (int i = 0; i < anonymousFunction.ParameterCount; ++i) { if (anonymousFunction.ParameterType(i).IsErrorType()) { return; } } } // The parameter list exists and had the right number of parameters. Were any of its types // mismatched with the delegate parameter types? // The simplest possible case is (x, y, z)=>whatever where the target type has a ref or out parameter. var delegateParameters = delegateType.DelegateParameters(); if (reason == LambdaConversionResult.RefInImplicitlyTypedLambda) { for (int i = 0; i < anonymousFunction.ParameterCount; ++i) { var delegateRefKind = delegateParameters[i].RefKind; if (delegateRefKind != RefKind.None) { // Parameter {0} must be declared with the '{1}' keyword Error(diagnostics, ErrorCode.ERR_BadParamRef, anonymousFunction.ParameterLocation(i), i + 1, delegateRefKind.ToParameterDisplayString()); } } return; } // See the comments in IsAnonymousFunctionCompatibleWithDelegate for an explanation of this one. if (reason == LambdaConversionResult.StaticTypeInImplicitlyTypedLambda) { for (int i = 0; i < anonymousFunction.ParameterCount; ++i) { if (delegateParameters[i].TypeWithAnnotations.IsStatic) { // {0}: Static types cannot be used as parameter Error(diagnostics, ErrorFacts.GetStaticClassParameterCode(useWarning: false), anonymousFunction.ParameterLocation(i), delegateParameters[i].Type); } } return; } // Otherwise, there might be a more complex reason why the parameter types are mismatched. if (reason == LambdaConversionResult.MismatchedParameterType) { // Cannot convert {0} to type '{1}' because the parameter types do not match the delegate parameter types Error(diagnostics, ErrorCode.ERR_CantConvAnonMethParams, syntax, id, targetType); Debug.Assert(anonymousFunction.ParameterCount == delegateParameters.Length); for (int i = 0; i < anonymousFunction.ParameterCount; ++i) { var lambdaParameterType = anonymousFunction.ParameterType(i); if (lambdaParameterType.IsErrorType()) { continue; } var lambdaParameterLocation = anonymousFunction.ParameterLocation(i); var lambdaRefKind = anonymousFunction.RefKind(i); var delegateParameterType = delegateParameters[i].Type; var delegateRefKind = delegateParameters[i].RefKind; if (!lambdaParameterType.Equals(delegateParameterType, TypeCompareKind.AllIgnoreOptions)) { SymbolDistinguisher distinguisher = new SymbolDistinguisher(this.Compilation, lambdaParameterType, delegateParameterType); // Parameter {0} is declared as type '{1}{2}' but should be '{3}{4}' Error(diagnostics, ErrorCode.ERR_BadParamType, lambdaParameterLocation, i + 1, lambdaRefKind.ToParameterPrefix(), distinguisher.First, delegateRefKind.ToParameterPrefix(), distinguisher.Second); } else if (lambdaRefKind != delegateRefKind) { if (delegateRefKind == RefKind.None) { // Parameter {0} should not be declared with the '{1}' keyword Error(diagnostics, ErrorCode.ERR_BadParamExtraRef, lambdaParameterLocation, i + 1, lambdaRefKind.ToParameterDisplayString()); } else { // Parameter {0} must be declared with the '{1}' keyword Error(diagnostics, ErrorCode.ERR_BadParamRef, lambdaParameterLocation, i + 1, delegateRefKind.ToParameterDisplayString()); } } } return; } if (reason == LambdaConversionResult.BindingFailed) { var bindingResult = anonymousFunction.Bind(delegateType, isExpressionTree: false); Debug.Assert(ErrorFacts.PreventsSuccessfulDelegateConversion(bindingResult.Diagnostics.Diagnostics)); diagnostics.AddRange(bindingResult.Diagnostics); return; } // UNDONE: LambdaConversionResult.VoidExpressionLambdaMustBeStatementExpression: Debug.Assert(false, "Missing case in lambda conversion error reporting"); diagnostics.Add(ErrorCode.ERR_InternalError, syntax.Location); } #nullable disable protected static void GenerateImplicitConversionError(BindingDiagnosticBag diagnostics, CSharpCompilation compilation, SyntaxNode syntax, Conversion conversion, TypeSymbol sourceType, TypeSymbol targetType, ConstantValue sourceConstantValueOpt = null) { Debug.Assert(!conversion.IsImplicit || !conversion.IsValid); // If the either type is an error then an error has already been reported // for some aspect of the analysis of this expression. (For example, something like // "garbage g = null; short s = g;" -- we don't want to report that g is not // convertible to short because we've already reported that g does not have a good type. if (!sourceType.IsErrorType() && !targetType.IsErrorType()) { if (conversion.IsExplicit) { if (sourceType.SpecialType == SpecialType.System_Double && syntax.Kind() == SyntaxKind.NumericLiteralExpression && (targetType.SpecialType == SpecialType.System_Single || targetType.SpecialType == SpecialType.System_Decimal)) { Error(diagnostics, ErrorCode.ERR_LiteralDoubleCast, syntax, (targetType.SpecialType == SpecialType.System_Single) ? "F" : "M", targetType); } else if (conversion.Kind == ConversionKind.ExplicitNumeric && sourceConstantValueOpt != null && sourceConstantValueOpt != ConstantValue.Bad && ConversionsBase.HasImplicitConstantExpressionConversion(new BoundLiteral(syntax, ConstantValue.Bad, sourceType), targetType)) { // CLEVERNESS: By passing ConstantValue.Bad, we tell HasImplicitConstantExpressionConversion to ignore the constant // value and only consider the types. // If there would be an implicit constant conversion for a different constant of the same type // (i.e. one that's not out of range), then it's more helpful to report the range check failure // than to suggest inserting a cast. Error(diagnostics, ErrorCode.ERR_ConstOutOfRange, syntax, sourceConstantValueOpt.Value, targetType); } else { SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, sourceType, targetType); Error(diagnostics, ErrorCode.ERR_NoImplicitConvCast, syntax, distinguisher.First, distinguisher.Second); } } else if (conversion.ResultKind == LookupResultKind.OverloadResolutionFailure) { Debug.Assert(conversion.IsUserDefined); ImmutableArray<MethodSymbol> originalUserDefinedConversions = conversion.OriginalUserDefinedConversions; if (originalUserDefinedConversions.Length > 1) { Error(diagnostics, ErrorCode.ERR_AmbigUDConv, syntax, originalUserDefinedConversions[0], originalUserDefinedConversions[1], sourceType, targetType); } else { Debug.Assert(originalUserDefinedConversions.Length == 0, "How can there be exactly one applicable user-defined conversion if the conversion doesn't exist?"); SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, sourceType, targetType); Error(diagnostics, ErrorCode.ERR_NoImplicitConv, syntax, distinguisher.First, distinguisher.Second); } } else if (TypeSymbol.Equals(sourceType, targetType, TypeCompareKind.ConsiderEverything2)) { // This occurs for `void`, which cannot even convert to itself. Since SymbolDistinguisher // requires two distinct types, we preempt its use here. The diagnostic is strange, but correct. // Though this diagnostic tends to be a cascaded one, we cannot suppress it until // we have proven that it is always so. Error(diagnostics, ErrorCode.ERR_NoImplicitConv, syntax, sourceType, targetType); } else { SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, sourceType, targetType); Error(diagnostics, ErrorCode.ERR_NoImplicitConv, syntax, distinguisher.First, distinguisher.Second); } } } protected void GenerateImplicitConversionError( BindingDiagnosticBag diagnostics, SyntaxNode syntax, Conversion conversion, BoundExpression operand, TypeSymbol targetType) { Debug.Assert(operand != null); Debug.Assert((object)targetType != null); if (targetType.TypeKind == TypeKind.Error) { return; } if (targetType.IsVoidType()) { Error(diagnostics, ErrorCode.ERR_NoImplicitConv, syntax, operand.Display, targetType); return; } switch (operand.Kind) { case BoundKind.BadExpression: { return; } case BoundKind.UnboundLambda: { GenerateAnonymousFunctionConversionError(diagnostics, syntax, (UnboundLambda)operand, targetType); return; } case BoundKind.TupleLiteral: { var tuple = (BoundTupleLiteral)operand; var targetElementTypes = default(ImmutableArray<TypeWithAnnotations>); // If target is a tuple or compatible type with the same number of elements, // report errors for tuple arguments that failed to convert, which would be more useful. if (targetType.TryGetElementTypesWithAnnotationsIfTupleType(out targetElementTypes) && targetElementTypes.Length == tuple.Arguments.Length) { GenerateImplicitConversionErrorsForTupleLiteralArguments(diagnostics, tuple.Arguments, targetElementTypes); return; } // target is not compatible with source and source does not have a type if ((object)tuple.Type == null) { Error(diagnostics, ErrorCode.ERR_ConversionNotTupleCompatible, syntax, tuple.Arguments.Length, targetType); return; } // Otherwise it is just a regular conversion failure from T1 to T2. break; } case BoundKind.MethodGroup: { reportMethodGroupErrors((BoundMethodGroup)operand, fromAddressOf: false); return; } case BoundKind.UnconvertedAddressOfOperator: { reportMethodGroupErrors(((BoundUnconvertedAddressOfOperator)operand).Operand, fromAddressOf: true); return; } case BoundKind.Literal: { if (operand.IsLiteralNull()) { if (targetType.TypeKind == TypeKind.TypeParameter) { Error(diagnostics, ErrorCode.ERR_TypeVarCantBeNull, syntax, targetType); return; } if (targetType.IsValueType) { Error(diagnostics, ErrorCode.ERR_ValueCantBeNull, syntax, targetType); return; } } break; } case BoundKind.StackAllocArrayCreation: { var stackAllocExpression = (BoundStackAllocArrayCreation)operand; Error(diagnostics, ErrorCode.ERR_StackAllocConversionNotPossible, syntax, stackAllocExpression.ElementType, targetType); return; } case BoundKind.UnconvertedSwitchExpression: { var switchExpression = (BoundUnconvertedSwitchExpression)operand; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; bool reportedError = false; foreach (var arm in switchExpression.SwitchArms) { tryConversion(arm.Value, ref reportedError, ref discardedUseSiteInfo); } Debug.Assert(reportedError); return; } case BoundKind.AddressOfOperator when targetType.IsFunctionPointer(): { Error(diagnostics, ErrorCode.ERR_InvalidAddrOp, ((BoundAddressOfOperator)operand).Operand.Syntax); return; } case BoundKind.UnconvertedConditionalOperator: { var conditionalOperator = (BoundUnconvertedConditionalOperator)operand; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; bool reportedError = false; tryConversion(conditionalOperator.Consequence, ref reportedError, ref discardedUseSiteInfo); tryConversion(conditionalOperator.Alternative, ref reportedError, ref discardedUseSiteInfo); Debug.Assert(reportedError); return; } void tryConversion(BoundExpression expr, ref bool reportedError, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var conversion = this.Conversions.ClassifyImplicitConversionFromExpression(expr, targetType, ref useSiteInfo); if (!conversion.IsImplicit || !conversion.IsValid) { GenerateImplicitConversionError(diagnostics, expr.Syntax, conversion, expr, targetType); reportedError = true; } } } var sourceType = operand.Type; if ((object)sourceType != null) { GenerateImplicitConversionError(diagnostics, this.Compilation, syntax, conversion, sourceType, targetType, operand.ConstantValue); return; } Debug.Assert(operand.HasAnyErrors && operand.Kind != BoundKind.UnboundLambda, "Missing a case in implicit conversion error reporting"); void reportMethodGroupErrors(BoundMethodGroup methodGroup, bool fromAddressOf) { if (!Conversions.ReportDelegateOrFunctionPointerMethodGroupDiagnostics(this, methodGroup, targetType, diagnostics)) { var nodeForError = syntax; while (nodeForError.Kind() == SyntaxKind.ParenthesizedExpression) { nodeForError = ((ParenthesizedExpressionSyntax)nodeForError).Expression; } if (nodeForError.Kind() == SyntaxKind.SimpleMemberAccessExpression || nodeForError.Kind() == SyntaxKind.PointerMemberAccessExpression) { nodeForError = ((MemberAccessExpressionSyntax)nodeForError).Name; } var location = nodeForError.Location; if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, targetType, location)) { return; } ErrorCode errorCode; switch (targetType.TypeKind) { case TypeKind.FunctionPointer when fromAddressOf: errorCode = ErrorCode.ERR_MethFuncPtrMismatch; break; case TypeKind.FunctionPointer: Error(diagnostics, ErrorCode.ERR_MissingAddressOf, location); return; case TypeKind.Delegate when fromAddressOf: errorCode = ErrorCode.ERR_CannotConvertAddressOfToDelegate; break; case TypeKind.Delegate: errorCode = ErrorCode.ERR_MethDelegateMismatch; break; default: if (fromAddressOf) { errorCode = ErrorCode.ERR_AddressOfToNonFunctionPointer; } else if (targetType.SpecialType == SpecialType.System_Delegate && syntax.IsFeatureEnabled(MessageID.IDS_FeatureInferredDelegateType)) { Error(diagnostics, ErrorCode.ERR_CannotInferDelegateType, location); return; } else { errorCode = ErrorCode.ERR_MethGrpToNonDel; } break; } Error(diagnostics, errorCode, location, methodGroup.Name, targetType); } } } private void GenerateImplicitConversionErrorsForTupleLiteralArguments( BindingDiagnosticBag diagnostics, ImmutableArray<BoundExpression> tupleArguments, ImmutableArray<TypeWithAnnotations> targetElementTypes) { var argLength = tupleArguments.Length; // report all leaf elements of the tuple literal that failed to convert // NOTE: we are not responsible for reporting use site errors here, just the failed leaf conversions. // By the time we get here we have done analysis and know we have failed the cast in general, and diagnostics collected in the process is already in the bag. // The only thing left is to form a diagnostics about the actually failing conversion(s). // This whole method does not itself collect any usesite diagnostics. Its only purpose is to produce an error better than "conversion failed here" var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; for (int i = 0; i < targetElementTypes.Length; i++) { var argument = tupleArguments[i]; var targetElementType = targetElementTypes[i].Type; var elementConversion = Conversions.ClassifyImplicitConversionFromExpression(argument, targetElementType, ref discardedUseSiteInfo); if (!elementConversion.IsValid) { GenerateImplicitConversionError(diagnostics, argument.Syntax, elementConversion, argument, targetElementType); } } } private BoundStatement BindIfStatement(IfStatementSyntax node, BindingDiagnosticBag diagnostics) { var condition = BindBooleanExpression(node.Condition, diagnostics); var consequence = BindPossibleEmbeddedStatement(node.Statement, diagnostics); BoundStatement alternative = (node.Else == null) ? null : BindPossibleEmbeddedStatement(node.Else.Statement, diagnostics); BoundStatement result = new BoundIfStatement(node, condition, consequence, alternative); return result; } internal BoundExpression BindBooleanExpression(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { // SPEC: // A boolean-expression is an expression that yields a result of type bool; // either directly or through application of operator true in certain // contexts as specified in the following. // // The controlling conditional expression of an if-statement, while-statement, // do-statement, or for-statement is a boolean-expression. The controlling // conditional expression of the ?: operator follows the same rules as a // boolean-expression, but for reasons of operator precedence is classified // as a conditional-or-expression. // // A boolean-expression is required to be implicitly convertible to bool // or of a type that implements operator true. If neither requirement // is satisfied, a binding-time error occurs. // // When a boolean expression cannot be implicitly converted to bool but does // implement operator true, then following evaluation of the expression, // the operator true implementation provided by that type is invoked // to produce a bool value. // // SPEC ERROR: The third paragraph above is obviously not correct; we need // SPEC ERROR: to do more than just check to see whether the type implements // SPEC ERROR: operator true. First off, the type could implement the operator // SPEC ERROR: several times: if it is a struct then it could implement it // SPEC ERROR: twice, to take both nullable and non-nullable arguments, and // SPEC ERROR: if it is a class or type parameter then it could have several // SPEC ERROR: implementations on its base classes or effective base classes. // SPEC ERROR: Second, the type of the argument could be S? where S implements // SPEC ERROR: operator true(S?); we want to look at S, not S?, when looking // SPEC ERROR: for applicable candidates. // // SPEC ERROR: Basically, the spec should say "use unary operator overload resolution // SPEC ERROR: to find the candidate set and choose a unique best operator true". var expr = BindValue(node, diagnostics, BindValueKind.RValue); var boolean = GetSpecialType(SpecialType.System_Boolean, diagnostics, node); if (expr.HasAnyErrors) { // The expression could not be bound. Insert a fake conversion // around it to bool and keep on going. // NOTE: no user-defined conversion candidates. return BoundConversion.Synthesized(node, BindToTypeForErrorRecovery(expr), Conversion.NoConversion, false, explicitCastInCode: false, conversionGroupOpt: null, ConstantValue.NotAvailable, boolean, hasErrors: true); } // Oddly enough, "if(dyn)" is bound not as a dynamic conversion to bool, but as a dynamic // invocation of operator true. if (expr.HasDynamicType()) { return new BoundUnaryOperator( node, UnaryOperatorKind.DynamicTrue, BindToNaturalType(expr, diagnostics), ConstantValue.NotAvailable, methodOpt: null, constrainedToTypeOpt: null, LookupResultKind.Viable, boolean) { WasCompilerGenerated = true }; } // Is the operand implicitly convertible to bool? CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var conversion = this.Conversions.ClassifyConversionFromExpression(expr, boolean, ref useSiteInfo); diagnostics.Add(expr.Syntax, useSiteInfo); if (conversion.IsImplicit) { if (conversion.Kind == ConversionKind.Identity) { // Check to see if we're assigning a boolean literal in a place where an // equality check would be more conventional. // NOTE: Don't do this check unless the expression will be returned // without being wrapped in another bound node (i.e. identity conversion). if (expr.Kind == BoundKind.AssignmentOperator) { var assignment = (BoundAssignmentOperator)expr; if (assignment.Right.Kind == BoundKind.Literal && assignment.Right.ConstantValue.Discriminator == ConstantValueTypeDiscriminator.Boolean) { Error(diagnostics, ErrorCode.WRN_IncorrectBooleanAssg, assignment.Syntax); } } } return CreateConversion( syntax: expr.Syntax, source: expr, conversion: conversion, isCast: false, conversionGroupOpt: null, wasCompilerGenerated: true, destination: boolean, diagnostics: diagnostics); } // It was not. Does it implement operator true? expr = BindToNaturalType(expr, diagnostics); var best = this.UnaryOperatorOverloadResolution(UnaryOperatorKind.True, expr, node, diagnostics, out LookupResultKind resultKind, out ImmutableArray<MethodSymbol> originalUserDefinedOperators); if (!best.HasValue) { // No. Give a "not convertible to bool" error. Debug.Assert(resultKind == LookupResultKind.Empty, "How could overload resolution fail if a user-defined true operator was found?"); Debug.Assert(originalUserDefinedOperators.IsEmpty, "How could overload resolution fail if a user-defined true operator was found?"); GenerateImplicitConversionError(diagnostics, node, conversion, expr, boolean); return BoundConversion.Synthesized(node, expr, Conversion.NoConversion, false, explicitCastInCode: false, conversionGroupOpt: null, ConstantValue.NotAvailable, boolean, hasErrors: true); } UnaryOperatorSignature signature = best.Signature; BoundExpression resultOperand = CreateConversion( node, expr, best.Conversion, isCast: false, conversionGroupOpt: null, destination: best.Signature.OperandType, diagnostics: diagnostics); CheckConstraintLanguageVersionAndRuntimeSupportForOperator(node, signature.Method, signature.ConstrainedToTypeOpt, diagnostics); // Consider op_true to be compiler-generated so that it doesn't appear in the semantic model. // UNDONE: If we decide to expose the operator in the semantic model, we'll have to remove the // WasCompilerGenerated flag (and possibly suppress the symbol in specific APIs). return new BoundUnaryOperator(node, signature.Kind, resultOperand, ConstantValue.NotAvailable, signature.Method, signature.ConstrainedToTypeOpt, resultKind, originalUserDefinedOperators, signature.ReturnType) { WasCompilerGenerated = true }; } private BoundStatement BindSwitchStatement(SwitchStatementSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Binder switchBinder = this.GetBinder(node); return switchBinder.BindSwitchStatementCore(node, switchBinder, diagnostics); } internal virtual BoundStatement BindSwitchStatementCore(SwitchStatementSyntax node, Binder originalBinder, BindingDiagnosticBag diagnostics) { return this.Next.BindSwitchStatementCore(node, originalBinder, diagnostics); } internal virtual void BindPatternSwitchLabelForInference(CasePatternSwitchLabelSyntax node, BindingDiagnosticBag diagnostics) { this.Next.BindPatternSwitchLabelForInference(node, diagnostics); } private BoundStatement BindWhile(WhileStatementSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); var loopBinder = this.GetBinder(node); Debug.Assert(loopBinder != null); return loopBinder.BindWhileParts(diagnostics, loopBinder); } internal virtual BoundWhileStatement BindWhileParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindWhileParts(diagnostics, originalBinder); } private BoundStatement BindDo(DoStatementSyntax node, BindingDiagnosticBag diagnostics) { var loopBinder = this.GetBinder(node); Debug.Assert(loopBinder != null); return loopBinder.BindDoParts(diagnostics, loopBinder); } internal virtual BoundDoStatement BindDoParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindDoParts(diagnostics, originalBinder); } internal BoundForStatement BindFor(ForStatementSyntax node, BindingDiagnosticBag diagnostics) { var loopBinder = this.GetBinder(node); Debug.Assert(loopBinder != null); return loopBinder.BindForParts(diagnostics, loopBinder); } internal virtual BoundForStatement BindForParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindForParts(diagnostics, originalBinder); } internal BoundStatement BindForOrUsingOrFixedDeclarations(VariableDeclarationSyntax nodeOpt, LocalDeclarationKind localKind, BindingDiagnosticBag diagnostics, out ImmutableArray<BoundLocalDeclaration> declarations) { if (nodeOpt == null) { declarations = ImmutableArray<BoundLocalDeclaration>.Empty; return null; } var typeSyntax = nodeOpt.Type; // Fixed and using variables are not allowed to be ref-like, but regular variables are if (localKind == LocalDeclarationKind.RegularVariable) { typeSyntax = typeSyntax.SkipRef(out _); } AliasSymbol alias; bool isVar; TypeWithAnnotations declType = BindTypeOrVarKeyword(typeSyntax, diagnostics, out isVar, out alias); Debug.Assert(declType.HasType || isVar); var variables = nodeOpt.Variables; int count = variables.Count; Debug.Assert(count > 0); if (isVar && count > 1) { // There are a number of ways in which a var decl can be illegal, but in these // cases we should report an error and then keep right on going with the inference. Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, nodeOpt); } var declarationArray = new BoundLocalDeclaration[count]; for (int i = 0; i < count; i++) { var variableDeclarator = variables[i]; bool includeBoundType = i == 0; //To avoid duplicated expressions, only the first declaration should contain the bound type. var declaration = BindVariableDeclaration(localKind, isVar, variableDeclarator, typeSyntax, declType, alias, diagnostics, includeBoundType); declarationArray[i] = declaration; } declarations = declarationArray.AsImmutableOrNull(); return (count == 1) ? (BoundStatement)declarations[0] : new BoundMultipleLocalDeclarations(nodeOpt, declarations); } internal BoundStatement BindStatementExpressionList(SeparatedSyntaxList<ExpressionSyntax> statements, BindingDiagnosticBag diagnostics) { int count = statements.Count; if (count == 0) { return null; } else if (count == 1) { var syntax = statements[0]; return BindExpressionStatement(syntax, syntax, false, diagnostics); } else { var statementBuilder = ArrayBuilder<BoundStatement>.GetInstance(); for (int i = 0; i < count; i++) { var syntax = statements[i]; var statement = BindExpressionStatement(syntax, syntax, false, diagnostics); statementBuilder.Add(statement); } return BoundStatementList.Synthesized(statements.Node, statementBuilder.ToImmutableAndFree()); } } private BoundStatement BindForEach(CommonForEachStatementSyntax node, BindingDiagnosticBag diagnostics) { Binder loopBinder = this.GetBinder(node); return this.GetBinder(node.Expression).WrapWithVariablesIfAny(node.Expression, loopBinder.BindForEachParts(diagnostics, loopBinder)); } internal virtual BoundStatement BindForEachParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindForEachParts(diagnostics, originalBinder); } /// <summary> /// Like BindForEachParts, but only bind the deconstruction part of the foreach, for purpose of inferring the types of the declared locals. /// </summary> internal virtual BoundStatement BindForEachDeconstruction(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindForEachDeconstruction(diagnostics, originalBinder); } private BoundStatement BindBreak(BreakStatementSyntax node, BindingDiagnosticBag diagnostics) { var target = this.BreakLabel; if ((object)target == null) { Error(diagnostics, ErrorCode.ERR_NoBreakOrCont, node); return new BoundBadStatement(node, ImmutableArray<BoundNode>.Empty, hasErrors: true); } return new BoundBreakStatement(node, target); } private BoundStatement BindContinue(ContinueStatementSyntax node, BindingDiagnosticBag diagnostics) { var target = this.ContinueLabel; if ((object)target == null) { Error(diagnostics, ErrorCode.ERR_NoBreakOrCont, node); return new BoundBadStatement(node, ImmutableArray<BoundNode>.Empty, hasErrors: true); } return new BoundContinueStatement(node, target); } private static SwitchBinder GetSwitchBinder(Binder binder) { SwitchBinder switchBinder = binder as SwitchBinder; while (binder != null && switchBinder == null) { binder = binder.Next; switchBinder = binder as SwitchBinder; } return switchBinder; } protected static bool IsInAsyncMethod(MethodSymbol method) { return (object)method != null && method.IsAsync; } protected bool IsInAsyncMethod() { return IsInAsyncMethod(this.ContainingMemberOrLambda as MethodSymbol); } protected bool IsEffectivelyTaskReturningAsyncMethod() { var symbol = this.ContainingMemberOrLambda; return symbol?.Kind == SymbolKind.Method && ((MethodSymbol)symbol).IsAsyncEffectivelyReturningTask(this.Compilation); } protected bool IsEffectivelyGenericTaskReturningAsyncMethod() { var symbol = this.ContainingMemberOrLambda; return symbol?.Kind == SymbolKind.Method && ((MethodSymbol)symbol).IsAsyncEffectivelyReturningGenericTask(this.Compilation); } protected bool IsIAsyncEnumerableOrIAsyncEnumeratorReturningAsyncMethod() { var symbol = this.ContainingMemberOrLambda; if (symbol?.Kind == SymbolKind.Method) { var method = (MethodSymbol)symbol; return method.IsAsyncReturningIAsyncEnumerable(this.Compilation) || method.IsAsyncReturningIAsyncEnumerator(this.Compilation); } return false; } protected virtual TypeSymbol GetCurrentReturnType(out RefKind refKind) { var symbol = this.ContainingMemberOrLambda as MethodSymbol; if ((object)symbol != null) { refKind = symbol.RefKind; TypeSymbol returnType = symbol.ReturnType; if ((object)returnType == LambdaSymbol.ReturnTypeIsBeingInferred) { return null; } return returnType; } refKind = RefKind.None; return null; } private BoundStatement BindReturn(ReturnStatementSyntax syntax, BindingDiagnosticBag diagnostics) { var refKind = RefKind.None; var expressionSyntax = syntax.Expression?.CheckAndUnwrapRefExpression(diagnostics, out refKind); BoundExpression arg = null; if (expressionSyntax != null) { BindValueKind requiredValueKind = GetRequiredReturnValueKind(refKind); arg = BindValue(expressionSyntax, diagnostics, requiredValueKind); } else { // If this is a void return statement in a script, return default(T). var interactiveInitializerMethod = this.ContainingMemberOrLambda as SynthesizedInteractiveInitializerMethod; if (interactiveInitializerMethod != null) { arg = new BoundDefaultExpression(interactiveInitializerMethod.GetNonNullSyntaxNode(), interactiveInitializerMethod.ResultType); } } RefKind sigRefKind; TypeSymbol retType = GetCurrentReturnType(out sigRefKind); bool hasErrors = false; if (IsDirectlyInIterator) { diagnostics.Add(ErrorCode.ERR_ReturnInIterator, syntax.ReturnKeyword.GetLocation()); hasErrors = true; } else if (IsInAsyncMethod()) { if (refKind != RefKind.None) { // This can happen if we are binding an async anonymous method to a delegate type. diagnostics.Add(ErrorCode.ERR_MustNotHaveRefReturn, syntax.ReturnKeyword.GetLocation()); hasErrors = true; } else if (IsIAsyncEnumerableOrIAsyncEnumeratorReturningAsyncMethod()) { diagnostics.Add(ErrorCode.ERR_ReturnInIterator, syntax.ReturnKeyword.GetLocation()); hasErrors = true; } } else if ((object)retType != null && (refKind != RefKind.None) != (sigRefKind != RefKind.None)) { var errorCode = refKind != RefKind.None ? ErrorCode.ERR_MustNotHaveRefReturn : ErrorCode.ERR_MustHaveRefReturn; diagnostics.Add(errorCode, syntax.ReturnKeyword.GetLocation()); hasErrors = true; } if (arg != null) { hasErrors |= arg.HasErrors || ((object)arg.Type != null && arg.Type.IsErrorType()); } if (hasErrors) { return new BoundReturnStatement(syntax, refKind, BindToTypeForErrorRecovery(arg), hasErrors: true); } // The return type could be null; we might be attempting to infer the return type either // because of method type inference, or because we are attempting to do error analysis // on a lambda expression of unknown return type. if ((object)retType != null) { if (retType.IsVoidType() || IsEffectivelyTaskReturningAsyncMethod()) { if (arg != null) { var container = this.ContainingMemberOrLambda; var lambda = container as LambdaSymbol; if ((object)lambda != null) { // Error case: void-returning or async task-returning method or lambda with "return x;" var errorCode = retType.IsVoidType() ? ErrorCode.ERR_RetNoObjectRequiredLambda : ErrorCode.ERR_TaskRetNoObjectRequiredLambda; // Anonymous function converted to a void returning delegate cannot return a value Error(diagnostics, errorCode, syntax.ReturnKeyword); hasErrors = true; // COMPATIBILITY: The native compiler also produced an error // COMPATIBILITY: "Cannot convert lambda expression to delegate type 'Action' because some of the // COMPATIBILITY: return types in the block are not implicitly convertible to the delegate return type" // COMPATIBILITY: This error doesn't make sense in the "void" case because the whole idea of // COMPATIBILITY: "conversion to void" is a bit unusual, and we've already given a good error. } else { // Error case: void-returning or async task-returning method or lambda with "return x;" var errorCode = retType.IsVoidType() ? ErrorCode.ERR_RetNoObjectRequired : ErrorCode.ERR_TaskRetNoObjectRequired; Error(diagnostics, errorCode, syntax.ReturnKeyword, container); hasErrors = true; } } } else { if (arg == null) { // Error case: non-void-returning or Task<T>-returning method or lambda but just have "return;" var requiredType = IsEffectivelyGenericTaskReturningAsyncMethod() ? retType.GetMemberTypeArgumentsNoUseSiteDiagnostics().Single() : retType; Error(diagnostics, ErrorCode.ERR_RetObjectRequired, syntax.ReturnKeyword, requiredType); hasErrors = true; } else { arg = CreateReturnConversion(syntax, diagnostics, arg, sigRefKind, retType); arg = ValidateEscape(arg, Binder.ExternalScope, refKind != RefKind.None, diagnostics); } } } else { // Check that the returned expression is not void. if ((object)arg?.Type != null && arg.Type.IsVoidType()) { Error(diagnostics, ErrorCode.ERR_CantReturnVoid, expressionSyntax); hasErrors = true; } } return new BoundReturnStatement(syntax, refKind, hasErrors ? BindToTypeForErrorRecovery(arg) : arg, hasErrors); } internal BoundExpression CreateReturnConversion( SyntaxNode syntax, BindingDiagnosticBag diagnostics, BoundExpression argument, RefKind returnRefKind, TypeSymbol returnType) { // If the return type is not void then the expression must be implicitly convertible. Conversion conversion; bool badAsyncReturnAlreadyReported = false; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (IsInAsyncMethod()) { Debug.Assert(returnRefKind == RefKind.None); if (!IsEffectivelyGenericTaskReturningAsyncMethod()) { conversion = Conversion.NoConversion; badAsyncReturnAlreadyReported = true; } else { returnType = returnType.GetMemberTypeArgumentsNoUseSiteDiagnostics().Single(); conversion = this.Conversions.ClassifyConversionFromExpression(argument, returnType, ref useSiteInfo); } } else { conversion = this.Conversions.ClassifyConversionFromExpression(argument, returnType, ref useSiteInfo); } diagnostics.Add(syntax, useSiteInfo); if (!argument.HasAnyErrors) { if (returnRefKind != RefKind.None) { if (conversion.Kind != ConversionKind.Identity) { Error(diagnostics, ErrorCode.ERR_RefReturnMustHaveIdentityConversion, argument.Syntax, returnType); argument = argument.WithHasErrors(); } else { return BindToNaturalType(argument, diagnostics); } } else if (!conversion.IsImplicit || !conversion.IsValid) { if (!badAsyncReturnAlreadyReported) { RefKind unusedRefKind; if (IsEffectivelyGenericTaskReturningAsyncMethod() && TypeSymbol.Equals(argument.Type, this.GetCurrentReturnType(out unusedRefKind), TypeCompareKind.ConsiderEverything2)) { // Since this is an async method, the return expression must be of type '{0}' rather than 'Task<{0}>' Error(diagnostics, ErrorCode.ERR_BadAsyncReturnExpression, argument.Syntax, returnType); } else { GenerateImplicitConversionError(diagnostics, argument.Syntax, conversion, argument, returnType); if (this.ContainingMemberOrLambda is LambdaSymbol) { ReportCantConvertLambdaReturn(argument.Syntax, diagnostics); } } } } } return CreateConversion(argument.Syntax, argument, conversion, isCast: false, conversionGroupOpt: null, returnType, diagnostics); } private BoundTryStatement BindTryStatement(TryStatementSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); var tryBlock = BindEmbeddedBlock(node.Block, diagnostics); var catchBlocks = BindCatchBlocks(node.Catches, diagnostics); var finallyBlockOpt = (node.Finally != null) ? BindEmbeddedBlock(node.Finally.Block, diagnostics) : null; return new BoundTryStatement(node, tryBlock, catchBlocks, finallyBlockOpt); } private ImmutableArray<BoundCatchBlock> BindCatchBlocks(SyntaxList<CatchClauseSyntax> catchClauses, BindingDiagnosticBag diagnostics) { int n = catchClauses.Count; if (n == 0) { return ImmutableArray<BoundCatchBlock>.Empty; } var catchBlocks = ArrayBuilder<BoundCatchBlock>.GetInstance(n); var hasCatchAll = false; foreach (var catchSyntax in catchClauses) { if (hasCatchAll) { diagnostics.Add(ErrorCode.ERR_TooManyCatches, catchSyntax.CatchKeyword.GetLocation()); } var catchBinder = this.GetBinder(catchSyntax); var catchBlock = catchBinder.BindCatchBlock(catchSyntax, catchBlocks, diagnostics); catchBlocks.Add(catchBlock); hasCatchAll |= catchSyntax.Declaration == null && catchSyntax.Filter == null; } return catchBlocks.ToImmutableAndFree(); } private BoundCatchBlock BindCatchBlock(CatchClauseSyntax node, ArrayBuilder<BoundCatchBlock> previousBlocks, BindingDiagnosticBag diagnostics) { bool hasError = false; TypeSymbol type = null; BoundExpression boundFilter = null; var declaration = node.Declaration; if (declaration != null) { // Note: The type is being bound twice: here and in LocalSymbol.Type. Currently, // LocalSymbol.Type ignores diagnostics so it seems cleaner to bind the type here // as well. However, if LocalSymbol.Type is changed to report diagnostics, we'll // need to avoid binding here since that will result in duplicate diagnostics. type = this.BindType(declaration.Type, diagnostics).Type; Debug.Assert((object)type != null); if (type.IsErrorType()) { hasError = true; } else { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); TypeSymbol effectiveType = type.EffectiveType(ref useSiteInfo); if (!Compilation.IsExceptionType(effectiveType, ref useSiteInfo)) { // "The type caught or thrown must be derived from System.Exception" Error(diagnostics, ErrorCode.ERR_BadExceptionType, declaration.Type); hasError = true; diagnostics.Add(declaration.Type, useSiteInfo); } else { diagnostics.AddDependencies(useSiteInfo); } } } var filter = node.Filter; if (filter != null) { var filterBinder = this.GetBinder(filter); boundFilter = filterBinder.BindCatchFilter(filter, diagnostics); hasError |= boundFilter.HasAnyErrors; } if (!hasError) { // TODO: Loop is O(n), caller is O(n^2). Perhaps we could iterate in reverse order (since it's easier to find // base types than to find derived types). Debug.Assert(((object)type == null) || !type.IsErrorType()); foreach (var previousBlock in previousBlocks) { var previousType = previousBlock.ExceptionTypeOpt; // If the previous type is a generic parameter we don't know what exception types it's gonna catch exactly. // If it is a class-type we know it's gonna catch all exception types of its type and types that are derived from it. // So if the current type is a class-type (or an effective base type of a generic parameter) // that derives from the previous type the current catch is unreachable. if (previousBlock.ExceptionFilterOpt == null && (object)previousType != null && !previousType.IsErrorType()) { if ((object)type != null) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (Conversions.HasIdentityOrImplicitReferenceConversion(type, previousType, ref useSiteInfo)) { // "A previous catch clause already catches all exceptions of this or of a super type ('{0}')" Error(diagnostics, ErrorCode.ERR_UnreachableCatch, declaration.Type, previousType); diagnostics.Add(declaration.Type, useSiteInfo); hasError = true; break; } diagnostics.Add(declaration.Type, useSiteInfo); } else if (TypeSymbol.Equals(previousType, Compilation.GetWellKnownType(WellKnownType.System_Exception), TypeCompareKind.ConsiderEverything2) && Compilation.SourceAssembly.RuntimeCompatibilityWrapNonExceptionThrows) { // If the RuntimeCompatibility(WrapNonExceptionThrows = false) is applied on the source assembly or any referenced netmodule. // an empty catch may catch exceptions that don't derive from System.Exception. // "A previous catch clause already catches all exceptions..." Error(diagnostics, ErrorCode.WRN_UnreachableGeneralCatch, node.CatchKeyword); break; } } } } var binder = GetBinder(node); Debug.Assert(binder != null); ImmutableArray<LocalSymbol> locals = binder.GetDeclaredLocalsForScope(node); BoundExpression exceptionSource = null; LocalSymbol local = locals.FirstOrDefault(); if (local?.DeclarationKind == LocalDeclarationKind.CatchVariable) { Debug.Assert(local.Type.IsErrorType() || (TypeSymbol.Equals(local.Type, type, TypeCompareKind.ConsiderEverything2))); // Check for local variable conflicts in the *enclosing* binder, not the *current* binder; // obviously we will find a local of the given name in the current binder. hasError |= this.ValidateDeclarationNameConflictsInScope(local, diagnostics); exceptionSource = new BoundLocal(declaration, local, ConstantValue.NotAvailable, local.Type); } var block = BindEmbeddedBlock(node.Block, diagnostics); return new BoundCatchBlock(node, locals, exceptionSource, type, exceptionFilterPrologueOpt: null, boundFilter, block, hasError); } private BoundExpression BindCatchFilter(CatchFilterClauseSyntax filter, BindingDiagnosticBag diagnostics) { BoundExpression boundFilter = this.BindBooleanExpression(filter.FilterExpression, diagnostics); if (boundFilter.ConstantValue != ConstantValue.NotAvailable) { // Depending on whether the filter constant is true or false, and whether there are other catch clauses, // we suggest different actions var errorCode = boundFilter.ConstantValue.BooleanValue ? ErrorCode.WRN_FilterIsConstantTrue : (filter.Parent.Parent is TryStatementSyntax s && s.Catches.Count == 1 && s.Finally == null) ? ErrorCode.WRN_FilterIsConstantFalseRedundantTryCatch : ErrorCode.WRN_FilterIsConstantFalse; // Since the expression is a constant, the name can be retrieved from the first token Error(diagnostics, errorCode, filter.FilterExpression); } return boundFilter; } // Report an extra error on the return if we are in a lambda conversion. private void ReportCantConvertLambdaReturn(SyntaxNode syntax, BindingDiagnosticBag diagnostics) { // Suppress this error if the lambda is a result of a query rewrite. if (syntax.Parent is QueryClauseSyntax || syntax.Parent is SelectOrGroupClauseSyntax) return; var lambda = this.ContainingMemberOrLambda as LambdaSymbol; if ((object)lambda != null) { Location location = GetLocationForDiagnostics(syntax); if (IsInAsyncMethod()) { // Cannot convert async {0} to intended delegate type. An async {0} may return void, Task or Task<T>, none of which are convertible to '{1}'. Error(diagnostics, ErrorCode.ERR_CantConvAsyncAnonFuncReturns, location, lambda.MessageID.Localize(), lambda.ReturnType); } else { // Cannot convert {0} to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type Error(diagnostics, ErrorCode.ERR_CantConvAnonMethReturns, location, lambda.MessageID.Localize()); } } } private static Location GetLocationForDiagnostics(SyntaxNode node) { switch (node) { case LambdaExpressionSyntax lambdaSyntax: return Location.Create(lambdaSyntax.SyntaxTree, Text.TextSpan.FromBounds(lambdaSyntax.SpanStart, lambdaSyntax.ArrowToken.Span.End)); case AnonymousMethodExpressionSyntax anonymousMethodSyntax: return Location.Create(anonymousMethodSyntax.SyntaxTree, Text.TextSpan.FromBounds(anonymousMethodSyntax.SpanStart, anonymousMethodSyntax.ParameterList?.Span.End ?? anonymousMethodSyntax.DelegateKeyword.Span.End)); } return node.Location; } private static bool IsValidStatementExpression(SyntaxNode syntax, BoundExpression expression) { bool syntacticallyValid = SyntaxFacts.IsStatementExpression(syntax); if (!syntacticallyValid) { return false; } if (expression.IsSuppressed) { return false; } // It is possible that an expression is syntactically valid but semantic analysis // reveals it to be illegal in a statement expression: "new MyDelegate(M)" for example // is not legal because it is a delegate-creation-expression and not an // object-creation-expression, but of course we don't know that syntactically. if (expression.Kind == BoundKind.DelegateCreationExpression || expression.Kind == BoundKind.NameOfOperator) { return false; } return true; } /// <summary> /// Wrap a given expression e into a block as either { e; } or { return e; } /// Shared between lambda and expression-bodied method binding. /// </summary> internal BoundBlock CreateBlockFromExpression(CSharpSyntaxNode node, ImmutableArray<LocalSymbol> locals, RefKind refKind, BoundExpression expression, ExpressionSyntax expressionSyntax, BindingDiagnosticBag diagnostics) { RefKind returnRefKind; var returnType = GetCurrentReturnType(out returnRefKind); var syntax = expressionSyntax ?? expression.Syntax; BoundStatement statement; if (IsInAsyncMethod() && refKind != RefKind.None) { // This can happen if we are binding an async anonymous method to a delegate type. Error(diagnostics, ErrorCode.ERR_MustNotHaveRefReturn, syntax); expression = BindToTypeForErrorRecovery(expression); statement = new BoundReturnStatement(syntax, refKind, expression) { WasCompilerGenerated = true }; } else if ((object)returnType != null) { if ((refKind != RefKind.None) != (returnRefKind != RefKind.None) && expression.Kind != BoundKind.ThrowExpression) { var errorCode = refKind != RefKind.None ? ErrorCode.ERR_MustNotHaveRefReturn : ErrorCode.ERR_MustHaveRefReturn; Error(diagnostics, errorCode, syntax); expression = BindToTypeForErrorRecovery(expression); statement = new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; } else if (returnType.IsVoidType() || IsEffectivelyTaskReturningAsyncMethod()) { // If the return type is void then the expression is required to be a legal // statement expression. Debug.Assert(expressionSyntax != null || !IsValidExpressionBody(expressionSyntax, expression)); bool errors = false; if (expressionSyntax == null || !IsValidExpressionBody(expressionSyntax, expression)) { expression = BindToTypeForErrorRecovery(expression); Error(diagnostics, ErrorCode.ERR_IllegalStatement, syntax); errors = true; } else { expression = BindToNaturalType(expression, diagnostics); } // Don't mark compiler generated so that the rewriter generates sequence points var expressionStatement = new BoundExpressionStatement(syntax, expression, errors); CheckForUnobservedAwaitable(expression, diagnostics); statement = expressionStatement; } else if (IsIAsyncEnumerableOrIAsyncEnumeratorReturningAsyncMethod()) { Error(diagnostics, ErrorCode.ERR_ReturnInIterator, syntax); expression = BindToTypeForErrorRecovery(expression); statement = new BoundReturnStatement(syntax, returnRefKind, expression) { WasCompilerGenerated = true }; } else { expression = returnType.IsErrorType() ? BindToTypeForErrorRecovery(expression) : CreateReturnConversion(syntax, diagnostics, expression, refKind, returnType); statement = new BoundReturnStatement(syntax, returnRefKind, expression) { WasCompilerGenerated = true }; } } else if (expression.Type?.SpecialType == SpecialType.System_Void) { expression = BindToNaturalType(expression, diagnostics); statement = new BoundExpressionStatement(syntax, expression) { WasCompilerGenerated = true }; } else { // When binding for purpose of inferring the return type of a lambda, we do not require returned expressions (such as `default` or switch expressions) to have a natural type var inferringLambda = this.ContainingMemberOrLambda is MethodSymbol method && (object)method.ReturnType == LambdaSymbol.ReturnTypeIsBeingInferred; if (!inferringLambda) { expression = BindToNaturalType(expression, diagnostics); } statement = new BoundReturnStatement(syntax, refKind, expression) { WasCompilerGenerated = true }; } // Need to attach the tree for when we generate sequence points. return new BoundBlock(node, locals, ImmutableArray.Create(statement)) { WasCompilerGenerated = node.Kind() != SyntaxKind.ArrowExpressionClause }; } private static bool IsValidExpressionBody(SyntaxNode expressionSyntax, BoundExpression expression) { return IsValidStatementExpression(expressionSyntax, expression) || expressionSyntax.Kind() == SyntaxKind.ThrowExpression; } /// <summary> /// Binds an expression-bodied member with expression e as either { return e; } or { e; }. /// </summary> internal virtual BoundBlock BindExpressionBodyAsBlock(ArrowExpressionClauseSyntax expressionBody, BindingDiagnosticBag diagnostics) { Binder bodyBinder = this.GetBinder(expressionBody); Debug.Assert(bodyBinder != null); return bindExpressionBodyAsBlockInternal(expressionBody, bodyBinder, diagnostics); // Use static local function to prevent accidentally calling instance methods on `this` instead of `bodyBinder` static BoundBlock bindExpressionBodyAsBlockInternal(ArrowExpressionClauseSyntax expressionBody, Binder bodyBinder, BindingDiagnosticBag diagnostics) { RefKind refKind; ExpressionSyntax expressionSyntax = expressionBody.Expression.CheckAndUnwrapRefExpression(diagnostics, out refKind); BindValueKind requiredValueKind = bodyBinder.GetRequiredReturnValueKind(refKind); BoundExpression expression = bodyBinder.BindValue(expressionSyntax, diagnostics, requiredValueKind); expression = bodyBinder.ValidateEscape(expression, Binder.ExternalScope, refKind != RefKind.None, diagnostics); return bodyBinder.CreateBlockFromExpression(expressionBody, bodyBinder.GetDeclaredLocalsForScope(expressionBody), refKind, expression, expressionSyntax, diagnostics); } } /// <summary> /// Binds a lambda with expression e as either { return e; } or { e; }. /// </summary> public BoundBlock BindLambdaExpressionAsBlock(ExpressionSyntax body, BindingDiagnosticBag diagnostics) { Binder bodyBinder = this.GetBinder(body); Debug.Assert(bodyBinder != null); RefKind refKind; var expressionSyntax = body.CheckAndUnwrapRefExpression(diagnostics, out refKind); BindValueKind requiredValueKind = GetRequiredReturnValueKind(refKind); BoundExpression expression = bodyBinder.BindValue(expressionSyntax, diagnostics, requiredValueKind); expression = ValidateEscape(expression, Binder.ExternalScope, refKind != RefKind.None, diagnostics); return bodyBinder.CreateBlockFromExpression(body, bodyBinder.GetDeclaredLocalsForScope(body), refKind, expression, expressionSyntax, diagnostics); } public BoundBlock CreateBlockFromExpression(ExpressionSyntax body, BoundExpression expression, BindingDiagnosticBag diagnostics) { Binder bodyBinder = this.GetBinder(body); Debug.Assert(bodyBinder != null); Debug.Assert(body.Kind() != SyntaxKind.RefExpression); return bodyBinder.CreateBlockFromExpression(body, bodyBinder.GetDeclaredLocalsForScope(body), RefKind.None, expression, body, diagnostics); } private BindValueKind GetRequiredReturnValueKind(RefKind refKind) { BindValueKind requiredValueKind = BindValueKind.RValue; if (refKind != RefKind.None) { GetCurrentReturnType(out var sigRefKind); requiredValueKind = sigRefKind == RefKind.Ref ? BindValueKind.RefReturn : BindValueKind.ReadonlyRef; } return requiredValueKind; } public virtual BoundNode BindMethodBody(CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics, bool includesFieldInitializers = false) { switch (syntax) { case RecordDeclarationSyntax recordDecl: return BindRecordConstructorBody(recordDecl, diagnostics); case BaseMethodDeclarationSyntax method: if (method.Kind() == SyntaxKind.ConstructorDeclaration) { return BindConstructorBody((ConstructorDeclarationSyntax)method, diagnostics, includesFieldInitializers); } return BindMethodBody(method, method.Body, method.ExpressionBody, diagnostics); case AccessorDeclarationSyntax accessor: return BindMethodBody(accessor, accessor.Body, accessor.ExpressionBody, diagnostics); case ArrowExpressionClauseSyntax arrowExpression: return BindExpressionBodyAsBlock(arrowExpression, diagnostics); case CompilationUnitSyntax compilationUnit: return BindSimpleProgram(compilationUnit, diagnostics); default: throw ExceptionUtilities.UnexpectedValue(syntax.Kind()); } } private BoundNode BindSimpleProgram(CompilationUnitSyntax compilationUnit, BindingDiagnosticBag diagnostics) { var simpleProgram = (SynthesizedSimpleProgramEntryPointSymbol)ContainingMemberOrLambda; return GetBinder(compilationUnit).BindSimpleProgramCompilationUnit(compilationUnit, simpleProgram, diagnostics); } private BoundNode BindSimpleProgramCompilationUnit(CompilationUnitSyntax compilationUnit, SynthesizedSimpleProgramEntryPointSymbol simpleProgram, BindingDiagnosticBag diagnostics) { ArrayBuilder<BoundStatement> boundStatements = ArrayBuilder<BoundStatement>.GetInstance(); foreach (var statement in compilationUnit.Members) { if (statement is GlobalStatementSyntax topLevelStatement) { var boundStatement = BindStatement(topLevelStatement.Statement, diagnostics); boundStatements.Add(boundStatement); } } return new BoundNonConstructorMethodBody(compilationUnit, FinishBindBlockParts(compilationUnit, boundStatements.ToImmutableAndFree(), diagnostics).MakeCompilerGenerated(), expressionBody: null); } private BoundNode BindRecordConstructorBody(RecordDeclarationSyntax recordDecl, BindingDiagnosticBag diagnostics) { Debug.Assert(recordDecl.ParameterList is object); Debug.Assert(recordDecl.IsKind(SyntaxKind.RecordDeclaration)); Binder bodyBinder = this.GetBinder(recordDecl); Debug.Assert(bodyBinder != null); BoundExpressionStatement initializer = null; if (recordDecl.PrimaryConstructorBaseTypeIfClass is PrimaryConstructorBaseTypeSyntax baseWithArguments) { initializer = bodyBinder.BindConstructorInitializer(baseWithArguments, diagnostics); } return new BoundConstructorMethodBody(recordDecl, bodyBinder.GetDeclaredLocalsForScope(recordDecl), initializer, blockBody: new BoundBlock(recordDecl, ImmutableArray<LocalSymbol>.Empty, ImmutableArray<BoundStatement>.Empty).MakeCompilerGenerated(), expressionBody: null); } internal virtual BoundExpressionStatement BindConstructorInitializer(PrimaryConstructorBaseTypeSyntax initializer, BindingDiagnosticBag diagnostics) { BoundExpression initializerInvocation = GetBinder(initializer).BindConstructorInitializer(initializer.ArgumentList, (MethodSymbol)this.ContainingMember(), diagnostics); var constructorInitializer = new BoundExpressionStatement(initializer, initializerInvocation); Debug.Assert(initializerInvocation.HasAnyErrors || constructorInitializer.IsConstructorInitializer(), "Please keep this bound node in sync with BoundNodeExtensions.IsConstructorInitializer."); return constructorInitializer; } private BoundNode BindConstructorBody(ConstructorDeclarationSyntax constructor, BindingDiagnosticBag diagnostics, bool includesFieldInitializers) { ConstructorInitializerSyntax initializer = constructor.Initializer; if (initializer == null && constructor.Body == null && constructor.ExpressionBody == null) { return null; } Binder bodyBinder = this.GetBinder(constructor); Debug.Assert(bodyBinder != null); bool thisInitializer = initializer?.IsKind(SyntaxKind.ThisConstructorInitializer) == true; if (!thisInitializer && ContainingType.GetMembersUnordered().OfType<SynthesizedRecordConstructor>().Any()) { var constructorSymbol = (MethodSymbol)this.ContainingMember(); if (!constructorSymbol.IsStatic && !SynthesizedRecordCopyCtor.IsCopyConstructor(constructorSymbol)) { // Note: we check the constructor initializer of copy constructors elsewhere Error(diagnostics, ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, initializer?.ThisOrBaseKeyword ?? constructor.Identifier); } } // The `: this()` initializer is ignored when it is a default value type constructor // and we need to include field initializers into the constructor. bool skipInitializer = includesFieldInitializers && thisInitializer && ContainingType.IsDefaultValueTypeConstructor(initializer); // Using BindStatement to bind block to make sure we are reusing results of partial binding in SemanticModel return new BoundConstructorMethodBody(constructor, bodyBinder.GetDeclaredLocalsForScope(constructor), skipInitializer ? new BoundNoOpStatement(constructor, NoOpStatementFlavor.Default) : initializer == null ? null : bodyBinder.BindConstructorInitializer(initializer, diagnostics), constructor.Body == null ? null : (BoundBlock)bodyBinder.BindStatement(constructor.Body, diagnostics), constructor.ExpressionBody == null ? null : bodyBinder.BindExpressionBodyAsBlock(constructor.ExpressionBody, constructor.Body == null ? diagnostics : BindingDiagnosticBag.Discarded)); } internal virtual BoundExpressionStatement BindConstructorInitializer(ConstructorInitializerSyntax initializer, BindingDiagnosticBag diagnostics) { BoundExpression initializerInvocation = GetBinder(initializer).BindConstructorInitializer(initializer.ArgumentList, (MethodSymbol)this.ContainingMember(), diagnostics); // Base WasCompilerGenerated state off of whether constructor is implicitly declared, this will ensure proper instrumentation. Debug.Assert(!this.ContainingMember().IsImplicitlyDeclared); var constructorInitializer = new BoundExpressionStatement(initializer, initializerInvocation); Debug.Assert(initializerInvocation.HasAnyErrors || constructorInitializer.IsConstructorInitializer(), "Please keep this bound node in sync with BoundNodeExtensions.IsConstructorInitializer."); return constructorInitializer; } private BoundNode BindMethodBody(CSharpSyntaxNode declaration, BlockSyntax blockBody, ArrowExpressionClauseSyntax expressionBody, BindingDiagnosticBag diagnostics) { if (blockBody == null && expressionBody == null) { return null; } // Using BindStatement to bind block to make sure we are reusing results of partial binding in SemanticModel return new BoundNonConstructorMethodBody(declaration, blockBody == null ? null : (BoundBlock)BindStatement(blockBody, diagnostics), expressionBody == null ? null : BindExpressionBodyAsBlock(expressionBody, blockBody == null ? diagnostics : BindingDiagnosticBag.Discarded)); } internal virtual ImmutableArray<LocalSymbol> Locals { get { return ImmutableArray<LocalSymbol>.Empty; } } internal virtual ImmutableArray<LocalFunctionSymbol> LocalFunctions { get { return ImmutableArray<LocalFunctionSymbol>.Empty; } } internal virtual ImmutableArray<LabelSymbol> Labels { get { return ImmutableArray<LabelSymbol>.Empty; } } /// <summary> /// If this binder owns the scope that can declare extern aliases, a set of declared aliases should be returned (even if empty). /// Otherwise, a default instance should be returned. /// </summary> internal virtual ImmutableArray<AliasAndExternAliasDirective> ExternAliases { get { return default; } } /// <summary> /// If this binder owns the scope that can declare using aliases, a set of declared aliases should be returned (even if empty). /// Otherwise, a default instance should be returned. /// Note, only aliases syntactically declared within the enclosing declaration are included. For example, global aliases /// declared in a different compilation units are not included. /// </summary> internal virtual ImmutableArray<AliasAndUsingDirective> UsingAliases { get { return default; } } /// <summary> /// Perform a lookup for the specified method on the specified expression by attempting to invoke it /// </summary> /// <param name="receiver">The expression to perform pattern lookup on</param> /// <param name="methodName">Method to search for.</param> /// <param name="syntaxNode">The expression for which lookup is being performed</param> /// <param name="diagnostics">Populated with binding diagnostics.</param> /// <param name="result">The method symbol that was looked up, or null</param> /// <returns>A <see cref="PatternLookupResult"/> value with the outcome of the lookup</returns> internal PatternLookupResult PerformPatternMethodLookup(BoundExpression receiver, string methodName, SyntaxNode syntaxNode, BindingDiagnosticBag diagnostics, out MethodSymbol result) { var bindingDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); try { result = null; var boundAccess = BindInstanceMemberAccess( syntaxNode, syntaxNode, receiver, methodName, rightArity: 0, typeArgumentsSyntax: default, typeArgumentsWithAnnotations: default, invoked: true, indexed: false, bindingDiagnostics); if (boundAccess.Kind != BoundKind.MethodGroup) { // the thing is not a method return PatternLookupResult.NotAMethod; } // NOTE: Because we're calling this method with no arguments and we // explicitly ignore default values for params parameters // (see ParameterSymbol.IsOptional) we know that no ParameterArray // containing method can be invoked in normal form which allows // us to skip some work during the lookup. var analyzedArguments = AnalyzedArguments.GetInstance(); var patternMethodCall = BindMethodGroupInvocation( syntaxNode, syntaxNode, methodName, (BoundMethodGroup)boundAccess, analyzedArguments, bindingDiagnostics, queryClause: null, allowUnexpandedForm: false, anyApplicableCandidates: out _); analyzedArguments.Free(); if (patternMethodCall.Kind != BoundKind.Call) { return PatternLookupResult.NotCallable; } var call = (BoundCall)patternMethodCall; if (call.ResultKind == LookupResultKind.Empty) { return PatternLookupResult.NoResults; } // we have succeeded or almost succeeded to bind the method // report additional binding diagnostics that we have seen so far diagnostics.AddRange(bindingDiagnostics); var patternMethodSymbol = call.Method; if (patternMethodSymbol is ErrorMethodSymbol || patternMethodCall.HasAnyErrors) { return PatternLookupResult.ResultHasErrors; } // Success! result = patternMethodSymbol; return PatternLookupResult.Success; } finally { bindingDiagnostics.Free(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This portion of the binder converts StatementSyntax nodes into BoundStatements /// </summary> internal partial class Binder { /// <summary> /// This is the set of parameters and local variables that were used as arguments to /// lock or using statements in enclosing scopes. /// </summary> /// <remarks> /// using (x) { } // x counts /// using (IDisposable y = null) { } // y does not count /// </remarks> internal virtual ImmutableHashSet<Symbol> LockedOrDisposedVariables { get { return Next.LockedOrDisposedVariables; } } /// <remarks> /// Noteworthy override is in MemberSemanticModel.IncrementalBinder (used for caching). /// </remarks> public virtual BoundStatement BindStatement(StatementSyntax node, BindingDiagnosticBag diagnostics) { if (node.AttributeLists.Count > 0) { var attributeList = node.AttributeLists[0]; // Currently, attributes are only allowed on local-functions. if (node.Kind() == SyntaxKind.LocalFunctionStatement) { CheckFeatureAvailability(attributeList, MessageID.IDS_FeatureLocalFunctionAttributes, diagnostics); } else if (node.Kind() != SyntaxKind.Block) { // Don't explicitly error here for blocks. Some codepaths bypass BindStatement // to directly call BindBlock. Error(diagnostics, ErrorCode.ERR_AttributesNotAllowed, attributeList); } } Debug.Assert(node != null); BoundStatement result; switch (node.Kind()) { case SyntaxKind.Block: result = BindBlock((BlockSyntax)node, diagnostics); break; case SyntaxKind.LocalDeclarationStatement: result = BindLocalDeclarationStatement((LocalDeclarationStatementSyntax)node, diagnostics); break; case SyntaxKind.LocalFunctionStatement: result = BindLocalFunctionStatement((LocalFunctionStatementSyntax)node, diagnostics); break; case SyntaxKind.ExpressionStatement: result = BindExpressionStatement((ExpressionStatementSyntax)node, diagnostics); break; case SyntaxKind.IfStatement: result = BindIfStatement((IfStatementSyntax)node, diagnostics); break; case SyntaxKind.SwitchStatement: result = BindSwitchStatement((SwitchStatementSyntax)node, diagnostics); break; case SyntaxKind.DoStatement: result = BindDo((DoStatementSyntax)node, diagnostics); break; case SyntaxKind.WhileStatement: result = BindWhile((WhileStatementSyntax)node, diagnostics); break; case SyntaxKind.ForStatement: result = BindFor((ForStatementSyntax)node, diagnostics); break; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: result = BindForEach((CommonForEachStatementSyntax)node, diagnostics); break; case SyntaxKind.BreakStatement: result = BindBreak((BreakStatementSyntax)node, diagnostics); break; case SyntaxKind.ContinueStatement: result = BindContinue((ContinueStatementSyntax)node, diagnostics); break; case SyntaxKind.ReturnStatement: result = BindReturn((ReturnStatementSyntax)node, diagnostics); break; case SyntaxKind.FixedStatement: result = BindFixedStatement((FixedStatementSyntax)node, diagnostics); break; case SyntaxKind.LabeledStatement: result = BindLabeled((LabeledStatementSyntax)node, diagnostics); break; case SyntaxKind.GotoStatement: case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoDefaultStatement: result = BindGoto((GotoStatementSyntax)node, diagnostics); break; case SyntaxKind.TryStatement: result = BindTryStatement((TryStatementSyntax)node, diagnostics); break; case SyntaxKind.EmptyStatement: result = BindEmpty((EmptyStatementSyntax)node); break; case SyntaxKind.ThrowStatement: result = BindThrow((ThrowStatementSyntax)node, diagnostics); break; case SyntaxKind.UnsafeStatement: result = BindUnsafeStatement((UnsafeStatementSyntax)node, diagnostics); break; case SyntaxKind.UncheckedStatement: case SyntaxKind.CheckedStatement: result = BindCheckedStatement((CheckedStatementSyntax)node, diagnostics); break; case SyntaxKind.UsingStatement: result = BindUsingStatement((UsingStatementSyntax)node, diagnostics); break; case SyntaxKind.YieldBreakStatement: result = BindYieldBreakStatement((YieldStatementSyntax)node, diagnostics); break; case SyntaxKind.YieldReturnStatement: result = BindYieldReturnStatement((YieldStatementSyntax)node, diagnostics); break; case SyntaxKind.LockStatement: result = BindLockStatement((LockStatementSyntax)node, diagnostics); break; default: // NOTE: We could probably throw an exception here, but it's conceivable // that a non-parser syntax tree could reach this point with an unexpected // SyntaxKind and we don't want to throw if that occurs. result = new BoundBadStatement(node, ImmutableArray<BoundNode>.Empty, hasErrors: true); break; } BoundBlock block; Debug.Assert(result.WasCompilerGenerated == false || (result.Kind == BoundKind.Block && (block = (BoundBlock)result).Statements.Length == 1 && block.Statements.Single().WasCompilerGenerated == false), "Synthetic node would not get cached"); Debug.Assert(result.Syntax is StatementSyntax, "BoundStatement should be associated with a statement syntax."); Debug.Assert(System.Linq.Enumerable.Contains(result.Syntax.AncestorsAndSelf(), node), @"Bound statement (or one of its parents) should have same syntax as the given syntax node. Otherwise it may be confusing to the binder cache that uses syntax node as keys."); return result; } private BoundStatement BindCheckedStatement(CheckedStatementSyntax node, BindingDiagnosticBag diagnostics) { return BindEmbeddedBlock(node.Block, diagnostics); } private BoundStatement BindUnsafeStatement(UnsafeStatementSyntax node, BindingDiagnosticBag diagnostics) { var unsafeBinder = this.GetBinder(node); if (!this.Compilation.Options.AllowUnsafe) { Error(diagnostics, ErrorCode.ERR_IllegalUnsafe, node.UnsafeKeyword); } else if (this.IsIndirectlyInIterator) // called *after* we know the binder map has been created. { // Spec 8.2: "An iterator block always defines a safe context, even when its declaration // is nested in an unsafe context." Error(diagnostics, ErrorCode.ERR_IllegalInnerUnsafe, node.UnsafeKeyword); } return BindEmbeddedBlock(node.Block, diagnostics); } private BoundStatement BindFixedStatement(FixedStatementSyntax node, BindingDiagnosticBag diagnostics) { var fixedBinder = this.GetBinder(node); Debug.Assert(fixedBinder != null); fixedBinder.ReportUnsafeIfNotAllowed(node, diagnostics); return fixedBinder.BindFixedStatementParts(node, diagnostics); } private BoundStatement BindFixedStatementParts(FixedStatementSyntax node, BindingDiagnosticBag diagnostics) { VariableDeclarationSyntax declarationSyntax = node.Declaration; ImmutableArray<BoundLocalDeclaration> declarations; BindForOrUsingOrFixedDeclarations(declarationSyntax, LocalDeclarationKind.FixedVariable, diagnostics, out declarations); Debug.Assert(!declarations.IsEmpty); BoundMultipleLocalDeclarations boundMultipleDeclarations = new BoundMultipleLocalDeclarations(declarationSyntax, declarations); BoundStatement boundBody = BindPossibleEmbeddedStatement(node.Statement, diagnostics); return new BoundFixedStatement(node, GetDeclaredLocalsForScope(node), boundMultipleDeclarations, boundBody); } private void CheckRequiredLangVersionForAsyncIteratorMethods(BindingDiagnosticBag diagnostics) { var method = (MethodSymbol)this.ContainingMemberOrLambda; if (method.IsAsync) { MessageID.IDS_FeatureAsyncStreams.CheckFeatureAvailability( diagnostics, method.DeclaringCompilation, method.Locations[0]); } } protected virtual void ValidateYield(YieldStatementSyntax node, BindingDiagnosticBag diagnostics) { Next?.ValidateYield(node, diagnostics); } private BoundStatement BindYieldReturnStatement(YieldStatementSyntax node, BindingDiagnosticBag diagnostics) { ValidateYield(node, diagnostics); TypeSymbol elementType = GetIteratorElementType().Type; BoundExpression argument = (node.Expression == null) ? BadExpression(node).MakeCompilerGenerated() : BindValue(node.Expression, diagnostics, BindValueKind.RValue); argument = ValidateEscape(argument, ExternalScope, isByRef: false, diagnostics: diagnostics); if (!argument.HasAnyErrors) { argument = GenerateConversionForAssignment(elementType, argument, diagnostics); } else { argument = BindToTypeForErrorRecovery(argument); } // NOTE: it's possible that more than one of these conditions is satisfied and that // we won't report the syntactically innermost. However, dev11 appears to check // them in this order, regardless of syntactic nesting (StatementBinder::bindYield). if (this.Flags.Includes(BinderFlags.InFinallyBlock)) { Error(diagnostics, ErrorCode.ERR_BadYieldInFinally, node.YieldKeyword); } else if (this.Flags.Includes(BinderFlags.InTryBlockOfTryCatch)) { Error(diagnostics, ErrorCode.ERR_BadYieldInTryOfCatch, node.YieldKeyword); } else if (this.Flags.Includes(BinderFlags.InCatchBlock)) { Error(diagnostics, ErrorCode.ERR_BadYieldInCatch, node.YieldKeyword); } else if (BindingTopLevelScriptCode) { Error(diagnostics, ErrorCode.ERR_YieldNotAllowedInScript, node.YieldKeyword); } CheckRequiredLangVersionForAsyncIteratorMethods(diagnostics); return new BoundYieldReturnStatement(node, argument); } private BoundStatement BindYieldBreakStatement(YieldStatementSyntax node, BindingDiagnosticBag diagnostics) { if (this.Flags.Includes(BinderFlags.InFinallyBlock)) { Error(diagnostics, ErrorCode.ERR_BadYieldInFinally, node.YieldKeyword); } else if (BindingTopLevelScriptCode) { Error(diagnostics, ErrorCode.ERR_YieldNotAllowedInScript, node.YieldKeyword); } ValidateYield(node, diagnostics); CheckRequiredLangVersionForAsyncIteratorMethods(diagnostics); return new BoundYieldBreakStatement(node); } private BoundStatement BindLockStatement(LockStatementSyntax node, BindingDiagnosticBag diagnostics) { var lockBinder = this.GetBinder(node); Debug.Assert(lockBinder != null); return lockBinder.BindLockStatementParts(diagnostics, lockBinder); } internal virtual BoundStatement BindLockStatementParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindLockStatementParts(diagnostics, originalBinder); } private BoundStatement BindUsingStatement(UsingStatementSyntax node, BindingDiagnosticBag diagnostics) { var usingBinder = this.GetBinder(node); Debug.Assert(usingBinder != null); return usingBinder.BindUsingStatementParts(diagnostics, usingBinder); } internal virtual BoundStatement BindUsingStatementParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindUsingStatementParts(diagnostics, originalBinder); } internal BoundStatement BindPossibleEmbeddedStatement(StatementSyntax node, BindingDiagnosticBag diagnostics) { Binder binder; switch (node.Kind()) { case SyntaxKind.LocalDeclarationStatement: // Local declarations are not legal in contexts where we need embedded statements. diagnostics.Add(ErrorCode.ERR_BadEmbeddedStmt, node.GetLocation()); // fall through goto case SyntaxKind.ExpressionStatement; case SyntaxKind.ExpressionStatement: case SyntaxKind.LockStatement: case SyntaxKind.IfStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.ThrowStatement: binder = this.GetBinder(node); Debug.Assert(binder != null); return binder.WrapWithVariablesIfAny(node, binder.BindStatement(node, diagnostics)); case SyntaxKind.LabeledStatement: case SyntaxKind.LocalFunctionStatement: // Labeled statements and local function statements are not legal in contexts where we need embedded statements. diagnostics.Add(ErrorCode.ERR_BadEmbeddedStmt, node.GetLocation()); binder = this.GetBinder(node); Debug.Assert(binder != null); return binder.WrapWithVariablesAndLocalFunctionsIfAny(node, binder.BindStatement(node, diagnostics)); case SyntaxKind.SwitchStatement: var switchStatement = (SwitchStatementSyntax)node; binder = this.GetBinder(switchStatement.Expression); Debug.Assert(binder != null); return binder.WrapWithVariablesIfAny(switchStatement.Expression, binder.BindStatement(node, diagnostics)); case SyntaxKind.EmptyStatement: var emptyStatement = (EmptyStatementSyntax)node; if (!emptyStatement.SemicolonToken.IsMissing) { switch (node.Parent.Kind()) { case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: case SyntaxKind.WhileStatement: // For loop constructs, only warn if we see a block following the statement. // That indicates code like: "while (x) ; { }" // which is most likely a bug. if (emptyStatement.SemicolonToken.GetNextToken().Kind() != SyntaxKind.OpenBraceToken) { break; } goto default; default: // For non-loop constructs, always warn. This is for code like: // "if (x) ;" which is almost certainly a bug. diagnostics.Add(ErrorCode.WRN_PossibleMistakenNullStatement, node.GetLocation()); break; } } // fall through goto default; default: return BindStatement(node, diagnostics); } } private BoundExpression BindThrownExpression(ExpressionSyntax exprSyntax, BindingDiagnosticBag diagnostics, ref bool hasErrors) { var boundExpr = BindValue(exprSyntax, diagnostics, BindValueKind.RValue); if (Compilation.LanguageVersion < MessageID.IDS_FeatureSwitchExpression.RequiredVersion()) { // This is the pre-C# 8 algorithm for binding a thrown expression. // SPEC VIOLATION: The spec requires the thrown exception to have a type, and that the type // be System.Exception or derived from System.Exception. (Or, if a type parameter, to have // an effective base class that meets that criterion.) However, we allow the literal null // to be thrown, even though it does not meet that criterion and will at runtime always // produce a null reference exception. if (!boundExpr.IsLiteralNull()) { boundExpr = BindToNaturalType(boundExpr, diagnostics); var type = boundExpr.Type; // If the expression is a lambda, anonymous method, or method group then it will // have no compile-time type; give the same error as if the type was wrong. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if ((object)type == null || !type.IsErrorType() && !Compilation.IsExceptionType(type.EffectiveType(ref useSiteInfo), ref useSiteInfo)) { diagnostics.Add(ErrorCode.ERR_BadExceptionType, exprSyntax.Location); hasErrors = true; diagnostics.Add(exprSyntax, useSiteInfo); } else { diagnostics.AddDependencies(useSiteInfo); } } } else { // In C# 8 and later we follow the ECMA specification, which neatly handles null and expressions of exception type. boundExpr = GenerateConversionForAssignment(GetWellKnownType(WellKnownType.System_Exception, diagnostics, exprSyntax), boundExpr, diagnostics); } return boundExpr; } private BoundStatement BindThrow(ThrowStatementSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression boundExpr = null; bool hasErrors = false; ExpressionSyntax exprSyntax = node.Expression; if (exprSyntax != null) { boundExpr = BindThrownExpression(exprSyntax, diagnostics, ref hasErrors); } else if (!this.Flags.Includes(BinderFlags.InCatchBlock)) { diagnostics.Add(ErrorCode.ERR_BadEmptyThrow, node.ThrowKeyword.GetLocation()); hasErrors = true; } else if (this.Flags.Includes(BinderFlags.InNestedFinallyBlock)) { // There's a special error code for a rethrow in a finally clause in a catch clause. // Best guess interpretation: if an exception occurs within the nested try block // (i.e. the one in the catch clause, to which the finally clause is attached), // then it's not clear whether the runtime will try to rethrow the "inner" exception // or the "outer" exception. For this reason, the case is disallowed. diagnostics.Add(ErrorCode.ERR_BadEmptyThrowInFinally, node.ThrowKeyword.GetLocation()); hasErrors = true; } return new BoundThrowStatement(node, boundExpr, hasErrors); } private static BoundStatement BindEmpty(EmptyStatementSyntax node) { return new BoundNoOpStatement(node, NoOpStatementFlavor.Default); } private BoundLabeledStatement BindLabeled(LabeledStatementSyntax node, BindingDiagnosticBag diagnostics) { // TODO: verify that goto label lookup was valid (e.g. error checking of symbol resolution for labels) bool hasError = false; var result = LookupResult.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var binder = this.LookupSymbolsWithFallback(result, node.Identifier.ValueText, arity: 0, useSiteInfo: ref useSiteInfo, options: LookupOptions.LabelsOnly); // result.Symbols can be empty in some malformed code, e.g. when a labeled statement is used an embedded statement in an if or foreach statement // In this case we create new label symbol on the fly, and an error is reported by parser var symbol = result.Symbols.Count > 0 && result.IsMultiViable ? (LabelSymbol)result.Symbols.First() : new SourceLabelSymbol((MethodSymbol)ContainingMemberOrLambda, node.Identifier); if (!symbol.IdentifierNodeOrToken.IsToken || symbol.IdentifierNodeOrToken.AsToken() != node.Identifier) { Error(diagnostics, ErrorCode.ERR_DuplicateLabel, node.Identifier, node.Identifier.ValueText); hasError = true; } // check to see if this label (illegally) hides a label from an enclosing scope if (binder != null) { result.Clear(); binder.Next.LookupSymbolsWithFallback(result, node.Identifier.ValueText, arity: 0, useSiteInfo: ref useSiteInfo, options: LookupOptions.LabelsOnly); if (result.IsMultiViable) { // The label '{0}' shadows another label by the same name in a contained scope Error(diagnostics, ErrorCode.ERR_LabelShadow, node.Identifier, node.Identifier.ValueText); hasError = true; } } diagnostics.Add(node, useSiteInfo); result.Free(); var body = BindStatement(node.Statement, diagnostics); return new BoundLabeledStatement(node, symbol, body, hasError); } private BoundStatement BindGoto(GotoStatementSyntax node, BindingDiagnosticBag diagnostics) { switch (node.Kind()) { case SyntaxKind.GotoStatement: var expression = BindLabel(node.Expression, diagnostics); var boundLabel = expression as BoundLabel; if (boundLabel == null) { // diagnostics already reported return new BoundBadStatement(node, ImmutableArray.Create<BoundNode>(expression), true); } var symbol = boundLabel.Label; return new BoundGotoStatement(node, symbol, null, boundLabel); case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoDefaultStatement: // SPEC: If the goto case statement is not enclosed by a switch statement, a compile-time error occurs. // SPEC: If the goto default statement is not enclosed by a switch statement, a compile-time error occurs. SwitchBinder binder = GetSwitchBinder(this); if (binder == null) { Error(diagnostics, ErrorCode.ERR_InvalidGotoCase, node); ImmutableArray<BoundNode> childNodes; if (node.Expression != null) { var value = BindRValueWithoutTargetType(node.Expression, BindingDiagnosticBag.Discarded); childNodes = ImmutableArray.Create<BoundNode>(value); } else { childNodes = ImmutableArray<BoundNode>.Empty; } return new BoundBadStatement(node, childNodes, true); } return binder.BindGotoCaseOrDefault(node, this, diagnostics); default: throw ExceptionUtilities.UnexpectedValue(node.Kind()); } } private BoundStatement BindLocalFunctionStatement(LocalFunctionStatementSyntax node, BindingDiagnosticBag diagnostics) { // already defined symbol in containing block var localSymbol = this.LookupLocalFunction(node.Identifier); var hasErrors = localSymbol.ScopeBinder .ValidateDeclarationNameConflictsInScope(localSymbol, diagnostics); BoundBlock blockBody = null; BoundBlock expressionBody = null; if (node.Body != null) { blockBody = runAnalysis(BindEmbeddedBlock(node.Body, diagnostics), diagnostics); if (node.ExpressionBody != null) { expressionBody = runAnalysis(BindExpressionBodyAsBlock(node.ExpressionBody, BindingDiagnosticBag.Discarded), BindingDiagnosticBag.Discarded); } } else if (node.ExpressionBody != null) { expressionBody = runAnalysis(BindExpressionBodyAsBlock(node.ExpressionBody, diagnostics), diagnostics); } else if (!hasErrors && (!localSymbol.IsExtern || !localSymbol.IsStatic)) { hasErrors = true; diagnostics.Add(ErrorCode.ERR_LocalFunctionMissingBody, localSymbol.Locations[0], localSymbol); } if (!hasErrors && (blockBody != null || expressionBody != null) && localSymbol.IsExtern) { hasErrors = true; diagnostics.Add(ErrorCode.ERR_ExternHasBody, localSymbol.Locations[0], localSymbol); } Debug.Assert(blockBody != null || expressionBody != null || (localSymbol.IsExtern && localSymbol.IsStatic) || hasErrors); localSymbol.GetDeclarationDiagnostics(diagnostics); Symbol.CheckForBlockAndExpressionBody( node.Body, node.ExpressionBody, node, diagnostics); return new BoundLocalFunctionStatement(node, localSymbol, blockBody, expressionBody, hasErrors); BoundBlock runAnalysis(BoundBlock block, BindingDiagnosticBag blockDiagnostics) { if (block != null) { // Have to do ControlFlowPass here because in MethodCompiler, we don't call this for synthed methods // rather we go directly to LowerBodyOrInitializer, which skips over flow analysis (which is in CompileMethod) // (the same thing - calling ControlFlowPass.Analyze in the lowering - is done for lambdas) // It's a bit of code duplication, but refactoring would make things worse. // However, we don't need to report diagnostics here. They will be reported when analyzing the parent method. var ignored = DiagnosticBag.GetInstance(); var endIsReachable = ControlFlowPass.Analyze(localSymbol.DeclaringCompilation, localSymbol, block, ignored); ignored.Free(); if (endIsReachable) { if (ImplicitReturnIsOkay(localSymbol)) { block = FlowAnalysisPass.AppendImplicitReturn(block, localSymbol); } else { blockDiagnostics.Add(ErrorCode.ERR_ReturnExpected, localSymbol.Locations[0], localSymbol); } } } return block; } } private bool ImplicitReturnIsOkay(MethodSymbol method) { return method.ReturnsVoid || method.IsIterator || method.IsAsyncEffectivelyReturningTask(this.Compilation); } public BoundStatement BindExpressionStatement(ExpressionStatementSyntax node, BindingDiagnosticBag diagnostics) { return BindExpressionStatement(node, node.Expression, node.AllowsAnyExpression, diagnostics); } private BoundExpressionStatement BindExpressionStatement(CSharpSyntaxNode node, ExpressionSyntax syntax, bool allowsAnyExpression, BindingDiagnosticBag diagnostics) { BoundExpressionStatement expressionStatement; var expression = BindRValueWithoutTargetType(syntax, diagnostics); ReportSuppressionIfNeeded(expression, diagnostics); if (!allowsAnyExpression && !IsValidStatementExpression(syntax, expression)) { if (!node.HasErrors) { Error(diagnostics, ErrorCode.ERR_IllegalStatement, syntax); } expressionStatement = new BoundExpressionStatement(node, expression, hasErrors: true); } else { expressionStatement = new BoundExpressionStatement(node, expression); } CheckForUnobservedAwaitable(expression, diagnostics); return expressionStatement; } /// <summary> /// Report an error if this is an awaitable async method invocation that is not being awaited. /// </summary> /// <remarks> /// The checks here are equivalent to StatementBinder::CheckForUnobservedAwaitable() in the native compiler. /// </remarks> private void CheckForUnobservedAwaitable(BoundExpression expression, BindingDiagnosticBag diagnostics) { if (CouldBeAwaited(expression)) { Error(diagnostics, ErrorCode.WRN_UnobservedAwaitableExpression, expression.Syntax); } } internal BoundStatement BindLocalDeclarationStatement(LocalDeclarationStatementSyntax node, BindingDiagnosticBag diagnostics) { if (node.UsingKeyword != default) { return BindUsingDeclarationStatementParts(node, diagnostics); } else { return BindDeclarationStatementParts(node, diagnostics); } } private BoundStatement BindUsingDeclarationStatementParts(LocalDeclarationStatementSyntax node, BindingDiagnosticBag diagnostics) { var usingDeclaration = UsingStatementBinder.BindUsingStatementOrDeclarationFromParts(node, node.UsingKeyword, node.AwaitKeyword, originalBinder: this, usingBinderOpt: null, diagnostics); Debug.Assert(usingDeclaration is BoundUsingLocalDeclarations); return usingDeclaration; } private BoundStatement BindDeclarationStatementParts(LocalDeclarationStatementSyntax node, BindingDiagnosticBag diagnostics) { var typeSyntax = node.Declaration.Type.SkipRef(out _); bool isConst = node.IsConst; bool isVar; AliasSymbol alias; TypeWithAnnotations declType = BindVariableTypeWithAnnotations(node.Declaration, diagnostics, typeSyntax, ref isConst, isVar: out isVar, alias: out alias); var kind = isConst ? LocalDeclarationKind.Constant : LocalDeclarationKind.RegularVariable; var variableList = node.Declaration.Variables; int variableCount = variableList.Count; if (variableCount == 1) { return BindVariableDeclaration(kind, isVar, variableList[0], typeSyntax, declType, alias, diagnostics, includeBoundType: true, associatedSyntaxNode: node); } else { BoundLocalDeclaration[] boundDeclarations = new BoundLocalDeclaration[variableCount]; int i = 0; foreach (var variableDeclarationSyntax in variableList) { bool includeBoundType = i == 0; //To avoid duplicated expressions, only the first declaration should contain the bound type. boundDeclarations[i++] = BindVariableDeclaration(kind, isVar, variableDeclarationSyntax, typeSyntax, declType, alias, diagnostics, includeBoundType); } return new BoundMultipleLocalDeclarations(node, boundDeclarations.AsImmutableOrNull()); } } /// <summary> /// Checks for a Dispose method on <paramref name="expr"/> and returns its <see cref="MethodSymbol"/> if found. /// </summary> /// <param name="expr">Expression on which to perform lookup</param> /// <param name="syntaxNode">The syntax node to perform lookup on</param> /// <param name="diagnostics">Populated with invocation errors, and warnings of near misses</param> /// <returns>The <see cref="MethodSymbol"/> of the Dispose method if one is found, otherwise null.</returns> internal MethodSymbol TryFindDisposePatternMethod(BoundExpression expr, SyntaxNode syntaxNode, bool hasAwait, BindingDiagnosticBag diagnostics) { Debug.Assert(expr is object); Debug.Assert(expr.Type is object); Debug.Assert(expr.Type.IsRefLikeType || hasAwait); // pattern dispose lookup is only valid on ref structs or asynchronous usings var result = PerformPatternMethodLookup(expr, hasAwait ? WellKnownMemberNames.DisposeAsyncMethodName : WellKnownMemberNames.DisposeMethodName, syntaxNode, diagnostics, out var disposeMethod); if (disposeMethod?.IsExtensionMethod == true) { // Extension methods should just be ignored, rather than rejected after-the-fact // Tracked by https://github.com/dotnet/roslyn/issues/32767 // extension methods do not contribute to pattern-based disposal disposeMethod = null; } else if ((!hasAwait && disposeMethod?.ReturnsVoid == false) || result == PatternLookupResult.NotAMethod) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (this.IsAccessible(disposeMethod, ref useSiteInfo)) { diagnostics.Add(ErrorCode.WRN_PatternBadSignature, syntaxNode.Location, expr.Type, MessageID.IDS_Disposable.Localize(), disposeMethod); } diagnostics.Add(syntaxNode, useSiteInfo); disposeMethod = null; } return disposeMethod; } private TypeWithAnnotations BindVariableTypeWithAnnotations(CSharpSyntaxNode declarationNode, BindingDiagnosticBag diagnostics, TypeSyntax typeSyntax, ref bool isConst, out bool isVar, out AliasSymbol alias) { Debug.Assert( declarationNode is VariableDesignationSyntax || declarationNode.Kind() == SyntaxKind.VariableDeclaration || declarationNode.Kind() == SyntaxKind.DeclarationExpression || declarationNode.Kind() == SyntaxKind.DiscardDesignation); // If the type is "var" then suppress errors when binding it. "var" might be a legal type // or it might not; if it is not then we do not want to report an error. If it is, then // we want to treat the declaration as an explicitly typed declaration. TypeWithAnnotations declType = BindTypeOrVarKeyword(typeSyntax.SkipRef(out _), diagnostics, out isVar, out alias); Debug.Assert(declType.HasType || isVar); if (isVar) { // There are a number of ways in which a var decl can be illegal, but in these // cases we should report an error and then keep right on going with the inference. if (isConst) { Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableCannotBeConst, declarationNode); // Keep processing it as a non-const local. isConst = false; } // In the dev10 compiler the error recovery semantics for the illegal case // "var x = 10, y = 123.4;" are somewhat undesirable. // // First off, this is an error because a straw poll of language designers and // users showed that there was no consensus on whether the above should mean // "double x = 10, y = 123.4;", taking the best type available and substituting // that for "var", or treating it as "var x = 10; var y = 123.4;" -- since there // was no consensus we decided to simply make it illegal. // // In dev10 for error recovery in the IDE we do an odd thing -- we simply take // the type of the first variable and use it. So that is "int x = 10, y = 123.4;". // // This seems less than ideal. In the error recovery scenario it probably makes // more sense to treat that as "var x = 10; var y = 123.4;" and do each inference // separately. if (declarationNode.Parent.Kind() == SyntaxKind.LocalDeclarationStatement && ((VariableDeclarationSyntax)declarationNode).Variables.Count > 1 && !declarationNode.HasErrors) { Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, declarationNode); } } else { // In the native compiler when given a situation like // // D[] x; // // where D is a static type we report both that D cannot be an element type // of an array, and that D[] is not a valid type for a local variable. // This seems silly; the first error is entirely sufficient. We no longer // produce additional errors for local variables of arrays of static types. if (declType.IsStatic) { Error(diagnostics, ErrorCode.ERR_VarDeclIsStaticClass, typeSyntax, declType.Type); } if (isConst && !declType.Type.CanBeConst()) { Error(diagnostics, ErrorCode.ERR_BadConstType, typeSyntax, declType.Type); // Keep processing it as a non-const local. isConst = false; } } return declType; } internal BoundExpression BindInferredVariableInitializer(BindingDiagnosticBag diagnostics, RefKind refKind, EqualsValueClauseSyntax initializer, CSharpSyntaxNode errorSyntax) { BindValueKind valueKind; ExpressionSyntax value; IsInitializerRefKindValid(initializer, initializer, refKind, diagnostics, out valueKind, out value); // The return value isn't important here; we just want the diagnostics and the BindValueKind return BindInferredVariableInitializer(diagnostics, value, valueKind, errorSyntax); } // The location where the error is reported might not be the initializer. protected BoundExpression BindInferredVariableInitializer(BindingDiagnosticBag diagnostics, ExpressionSyntax initializer, BindValueKind valueKind, CSharpSyntaxNode errorSyntax) { if (initializer == null) { if (!errorSyntax.HasErrors) { Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, errorSyntax); } return null; } if (initializer.Kind() == SyntaxKind.ArrayInitializerExpression) { var result = BindUnexpectedArrayInitializer((InitializerExpressionSyntax)initializer, diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableAssignedArrayInitializer, errorSyntax); return CheckValue(result, valueKind, diagnostics); } BoundExpression value = BindValue(initializer, diagnostics, valueKind); BoundExpression expression = value.Kind is BoundKind.UnboundLambda or BoundKind.MethodGroup ? BindToInferredDelegateType(value, diagnostics) : BindToNaturalType(value, diagnostics); // Certain expressions (null literals, method groups and anonymous functions) have no type of // their own and therefore cannot be the initializer of an implicitly typed local. if (!expression.HasAnyErrors && !expression.HasExpressionType()) { // Cannot assign {0} to an implicitly-typed local variable Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, errorSyntax, expression.Display); } return expression; } private static bool IsInitializerRefKindValid( EqualsValueClauseSyntax initializer, CSharpSyntaxNode node, RefKind variableRefKind, BindingDiagnosticBag diagnostics, out BindValueKind valueKind, out ExpressionSyntax value) { RefKind expressionRefKind = RefKind.None; value = initializer?.Value.CheckAndUnwrapRefExpression(diagnostics, out expressionRefKind); if (variableRefKind == RefKind.None) { valueKind = BindValueKind.RValue; if (expressionRefKind == RefKind.Ref) { Error(diagnostics, ErrorCode.ERR_InitializeByValueVariableWithReference, node); return false; } } else { valueKind = variableRefKind == RefKind.RefReadOnly ? BindValueKind.ReadonlyRef : BindValueKind.RefOrOut; if (initializer == null) { Error(diagnostics, ErrorCode.ERR_ByReferenceVariableMustBeInitialized, node); return false; } else if (expressionRefKind != RefKind.Ref) { Error(diagnostics, ErrorCode.ERR_InitializeByReferenceVariableWithValue, node); return false; } } return true; } protected BoundLocalDeclaration BindVariableDeclaration( LocalDeclarationKind kind, bool isVar, VariableDeclaratorSyntax declarator, TypeSyntax typeSyntax, TypeWithAnnotations declTypeOpt, AliasSymbol aliasOpt, BindingDiagnosticBag diagnostics, bool includeBoundType, CSharpSyntaxNode associatedSyntaxNode = null) { Debug.Assert(declarator != null); return BindVariableDeclaration(LocateDeclaredVariableSymbol(declarator, typeSyntax, kind), kind, isVar, declarator, typeSyntax, declTypeOpt, aliasOpt, diagnostics, includeBoundType, associatedSyntaxNode); } protected BoundLocalDeclaration BindVariableDeclaration( SourceLocalSymbol localSymbol, LocalDeclarationKind kind, bool isVar, VariableDeclaratorSyntax declarator, TypeSyntax typeSyntax, TypeWithAnnotations declTypeOpt, AliasSymbol aliasOpt, BindingDiagnosticBag diagnostics, bool includeBoundType, CSharpSyntaxNode associatedSyntaxNode = null) { Debug.Assert(declarator != null); Debug.Assert(declTypeOpt.HasType || isVar); Debug.Assert(typeSyntax != null); var localDiagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, diagnostics.AccumulatesDependencies); // if we are not given desired syntax, we use declarator associatedSyntaxNode = associatedSyntaxNode ?? declarator; // Check for variable declaration errors. // Use the binder that owns the scope for the local because this (the current) binder // might own nested scope. bool nameConflict = localSymbol.ScopeBinder.ValidateDeclarationNameConflictsInScope(localSymbol, diagnostics); bool hasErrors = false; if (localSymbol.RefKind != RefKind.None) { CheckRefLocalInAsyncOrIteratorMethod(localSymbol.IdentifierToken, diagnostics); } EqualsValueClauseSyntax equalsClauseSyntax = declarator.Initializer; BindValueKind valueKind; ExpressionSyntax value; if (!IsInitializerRefKindValid(equalsClauseSyntax, declarator, localSymbol.RefKind, diagnostics, out valueKind, out value)) { hasErrors = true; } BoundExpression initializerOpt; if (isVar) { aliasOpt = null; initializerOpt = BindInferredVariableInitializer(diagnostics, value, valueKind, declarator); // If we got a good result then swap the inferred type for the "var" TypeSymbol initializerType = initializerOpt?.Type; if ((object)initializerType != null) { declTypeOpt = TypeWithAnnotations.Create(initializerType); if (declTypeOpt.IsVoidType()) { Error(localDiagnostics, ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, declarator, declTypeOpt.Type); declTypeOpt = TypeWithAnnotations.Create(CreateErrorType("var")); hasErrors = true; } if (!declTypeOpt.Type.IsErrorType()) { if (declTypeOpt.IsStatic) { Error(localDiagnostics, ErrorCode.ERR_VarDeclIsStaticClass, typeSyntax, initializerType); hasErrors = true; } } } else { declTypeOpt = TypeWithAnnotations.Create(CreateErrorType("var")); hasErrors = true; } } else { if (ReferenceEquals(equalsClauseSyntax, null)) { initializerOpt = null; } else { // Basically inlined BindVariableInitializer, but with conversion optional. initializerOpt = BindPossibleArrayInitializer(value, declTypeOpt.Type, valueKind, diagnostics); if (kind != LocalDeclarationKind.FixedVariable) { // If this is for a fixed statement, we'll do our own conversion since there are some special cases. initializerOpt = GenerateConversionForAssignment( declTypeOpt.Type, initializerOpt, localDiagnostics, isRefAssignment: localSymbol.RefKind != RefKind.None); } } } Debug.Assert(declTypeOpt.HasType); if (kind == LocalDeclarationKind.FixedVariable) { // NOTE: this is an error, but it won't prevent further binding. if (isVar) { if (!hasErrors) { Error(localDiagnostics, ErrorCode.ERR_ImplicitlyTypedLocalCannotBeFixed, declarator); hasErrors = true; } } if (!declTypeOpt.Type.IsPointerType()) { if (!hasErrors) { Error(localDiagnostics, declTypeOpt.Type.IsFunctionPointer() ? ErrorCode.ERR_CannotUseFunctionPointerAsFixedLocal : ErrorCode.ERR_BadFixedInitType, declarator); hasErrors = true; } } else if (!IsValidFixedVariableInitializer(declTypeOpt.Type, localSymbol, ref initializerOpt, localDiagnostics)) { hasErrors = true; } } if (CheckRestrictedTypeInAsyncMethod(this.ContainingMemberOrLambda, declTypeOpt.Type, localDiagnostics, typeSyntax)) { hasErrors = true; } localSymbol.SetTypeWithAnnotations(declTypeOpt); if (initializerOpt != null) { var currentScope = LocalScopeDepth; localSymbol.SetValEscape(GetValEscape(initializerOpt, currentScope)); if (localSymbol.RefKind != RefKind.None) { localSymbol.SetRefEscape(GetRefEscape(initializerOpt, currentScope)); } } ImmutableArray<BoundExpression> arguments = BindDeclaratorArguments(declarator, localDiagnostics); if (kind == LocalDeclarationKind.FixedVariable || kind == LocalDeclarationKind.UsingVariable) { // CONSIDER: The error message is "you must provide an initializer in a fixed // CONSIDER: or using declaration". The error message could be targeted to // CONSIDER: the actual situation. "you must provide an initializer in a // CONSIDER: 'fixed' declaration." if (initializerOpt == null) { Error(localDiagnostics, ErrorCode.ERR_FixedMustInit, declarator); hasErrors = true; } } else if (kind == LocalDeclarationKind.Constant && initializerOpt != null && !localDiagnostics.HasAnyResolvedErrors()) { var constantValueDiagnostics = localSymbol.GetConstantValueDiagnostics(initializerOpt); diagnostics.AddRange(constantValueDiagnostics, allowMismatchInDependencyAccumulation: true); hasErrors = constantValueDiagnostics.Diagnostics.HasAnyErrors(); } diagnostics.AddRangeAndFree(localDiagnostics); BoundTypeExpression boundDeclType = null; if (includeBoundType) { var invalidDimensions = ArrayBuilder<BoundExpression>.GetInstance(); typeSyntax.VisitRankSpecifiers((rankSpecifier, args) => { bool _ = false; foreach (var expressionSyntax in rankSpecifier.Sizes) { var size = args.binder.BindArrayDimension(expressionSyntax, args.diagnostics, ref _); if (size != null) { args.invalidDimensions.Add(size); } } }, (binder: this, invalidDimensions: invalidDimensions, diagnostics: diagnostics)); boundDeclType = new BoundTypeExpression(typeSyntax, aliasOpt, dimensionsOpt: invalidDimensions.ToImmutableAndFree(), typeWithAnnotations: declTypeOpt); } return new BoundLocalDeclaration( syntax: associatedSyntaxNode, localSymbol: localSymbol, declaredTypeOpt: boundDeclType, initializerOpt: hasErrors ? BindToTypeForErrorRecovery(initializerOpt)?.WithHasErrors() : initializerOpt, argumentsOpt: arguments, inferredType: isVar, hasErrors: hasErrors | nameConflict); } protected bool CheckRefLocalInAsyncOrIteratorMethod(SyntaxToken identifierToken, BindingDiagnosticBag diagnostics) { if (IsInAsyncMethod()) { Error(diagnostics, ErrorCode.ERR_BadAsyncLocalType, identifierToken); return true; } else if (IsDirectlyInIterator) { Error(diagnostics, ErrorCode.ERR_BadIteratorLocalType, identifierToken); return true; } return false; } internal ImmutableArray<BoundExpression> BindDeclaratorArguments(VariableDeclaratorSyntax declarator, BindingDiagnosticBag diagnostics) { // It is possible that we have a bracketed argument list, like "int x[];" or "int x[123];" // in a non-fixed-size-array declaration . This is a common error made by C++ programmers. // We have already given a good error at parse time telling the user to either make it "fixed" // or to move the brackets to the type. However, we should still do semantic analysis of // the arguments, so that errors in them are discovered, hovering over them in the IDE // gives good results, and so on. var arguments = default(ImmutableArray<BoundExpression>); if (declarator.ArgumentList != null) { AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); BindArgumentsAndNames(declarator.ArgumentList, diagnostics, analyzedArguments); arguments = BuildArgumentsForErrorRecovery(analyzedArguments); analyzedArguments.Free(); } return arguments; } private SourceLocalSymbol LocateDeclaredVariableSymbol(VariableDeclaratorSyntax declarator, TypeSyntax typeSyntax, LocalDeclarationKind outerKind) { LocalDeclarationKind kind = outerKind == LocalDeclarationKind.UsingVariable ? LocalDeclarationKind.UsingVariable : LocalDeclarationKind.RegularVariable; return LocateDeclaredVariableSymbol(declarator.Identifier, typeSyntax, declarator.Initializer, kind); } private SourceLocalSymbol LocateDeclaredVariableSymbol(SyntaxToken identifier, TypeSyntax typeSyntax, EqualsValueClauseSyntax equalsValue, LocalDeclarationKind kind) { SourceLocalSymbol localSymbol = this.LookupLocal(identifier); // In error scenarios with misplaced code, it is possible we can't bind the local declaration. // This occurs through the semantic model. In that case concoct a plausible result. if ((object)localSymbol == null) { localSymbol = SourceLocalSymbol.MakeLocal( ContainingMemberOrLambda, this, false, // do not allow ref typeSyntax, identifier, kind, equalsValue); } return localSymbol; } private bool IsValidFixedVariableInitializer(TypeSymbol declType, SourceLocalSymbol localSymbol, ref BoundExpression initializerOpt, BindingDiagnosticBag diagnostics) { Debug.Assert(!ReferenceEquals(declType, null)); Debug.Assert(declType.IsPointerType()); if (initializerOpt?.HasAnyErrors != false) { return false; } TypeSymbol initializerType = initializerOpt.Type; SyntaxNode initializerSyntax = initializerOpt.Syntax; if ((object)initializerType == null) { Error(diagnostics, ErrorCode.ERR_ExprCannotBeFixed, initializerSyntax); return false; } TypeSymbol elementType; bool hasErrors = false; MethodSymbol fixedPatternMethod = null; switch (initializerOpt.Kind) { case BoundKind.AddressOfOperator: elementType = ((BoundAddressOfOperator)initializerOpt).Operand.Type; break; case BoundKind.FieldAccess: var fa = (BoundFieldAccess)initializerOpt; if (fa.FieldSymbol.IsFixedSizeBuffer) { elementType = ((PointerTypeSymbol)fa.Type).PointedAtType; break; } goto default; default: // fixed (T* variable = <expr>) ... // check for arrays if (initializerType.IsArray()) { // See ExpressionBinder::BindPtrToArray (though most of that functionality is now in LocalRewriter). elementType = ((ArrayTypeSymbol)initializerType).ElementType; break; } // check for a special ref-returning method var additionalDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); fixedPatternMethod = GetFixedPatternMethodOpt(initializerOpt, additionalDiagnostics); // check for String // NOTE: We will allow the pattern method to take precedence, but only if it is an instance member of System.String if (initializerType.SpecialType == SpecialType.System_String && ((object)fixedPatternMethod == null || fixedPatternMethod.ContainingType.SpecialType != SpecialType.System_String)) { fixedPatternMethod = null; elementType = this.GetSpecialType(SpecialType.System_Char, diagnostics, initializerSyntax); additionalDiagnostics.Free(); break; } // if the feature was enabled, but something went wrong with the method, report that, otherwise don't. // If feature is not enabled, additional errors would be just noise. bool extensibleFixedEnabled = ((CSharpParseOptions)initializerOpt.SyntaxTree.Options)?.IsFeatureEnabled(MessageID.IDS_FeatureExtensibleFixedStatement) != false; if (extensibleFixedEnabled) { diagnostics.AddRange(additionalDiagnostics); } additionalDiagnostics.Free(); if ((object)fixedPatternMethod != null) { elementType = fixedPatternMethod.ReturnType; CheckFeatureAvailability(initializerOpt.Syntax, MessageID.IDS_FeatureExtensibleFixedStatement, diagnostics); break; } else { Error(diagnostics, ErrorCode.ERR_ExprCannotBeFixed, initializerSyntax); return false; } } if (CheckManagedAddr(Compilation, elementType, initializerSyntax.Location, diagnostics)) { hasErrors = true; } initializerOpt = BindToNaturalType(initializerOpt, diagnostics, reportNoTargetType: false); initializerOpt = GetFixedLocalCollectionInitializer(initializerOpt, elementType, declType, fixedPatternMethod, hasErrors, diagnostics); return true; } private MethodSymbol GetFixedPatternMethodOpt(BoundExpression initializer, BindingDiagnosticBag additionalDiagnostics) { if (initializer.Type.IsVoidType()) { return null; } const string methodName = "GetPinnableReference"; var result = PerformPatternMethodLookup(initializer, methodName, initializer.Syntax, additionalDiagnostics, out var patternMethodSymbol); if (patternMethodSymbol is null) { return null; } if (HasOptionalOrVariableParameters(patternMethodSymbol) || patternMethodSymbol.ReturnsVoid || !patternMethodSymbol.RefKind.IsManagedReference() || !(patternMethodSymbol.ParameterCount == 0 || patternMethodSymbol.IsStatic && patternMethodSymbol.ParameterCount == 1)) { // the method does not fit the pattern additionalDiagnostics.Add(ErrorCode.WRN_PatternBadSignature, initializer.Syntax.Location, initializer.Type, "fixed", patternMethodSymbol); return null; } return patternMethodSymbol; } /// <summary> /// Wrap the initializer in a BoundFixedLocalCollectionInitializer so that the rewriter will have the /// information it needs (e.g. conversions, helper methods). /// </summary> private BoundExpression GetFixedLocalCollectionInitializer( BoundExpression initializer, TypeSymbol elementType, TypeSymbol declType, MethodSymbol patternMethodOpt, bool hasErrors, BindingDiagnosticBag diagnostics) { Debug.Assert(initializer != null); SyntaxNode initializerSyntax = initializer.Syntax; TypeSymbol pointerType = new PointerTypeSymbol(TypeWithAnnotations.Create(elementType)); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion elementConversion = this.Conversions.ClassifyConversionFromType(pointerType, declType, ref useSiteInfo); diagnostics.Add(initializerSyntax, useSiteInfo); if (!elementConversion.IsValid || !elementConversion.IsImplicit) { GenerateImplicitConversionError(diagnostics, this.Compilation, initializerSyntax, elementConversion, pointerType, declType); hasErrors = true; } return new BoundFixedLocalCollectionInitializer( initializerSyntax, pointerType, elementConversion, initializer, patternMethodOpt, declType, hasErrors); } private BoundExpression BindAssignment(AssignmentExpressionSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Debug.Assert(node.Left != null); Debug.Assert(node.Right != null); node.Left.CheckDeconstructionCompatibleArgument(diagnostics); if (node.Left.Kind() == SyntaxKind.TupleExpression || node.Left.Kind() == SyntaxKind.DeclarationExpression) { return BindDeconstruction(node, diagnostics); } BindValueKind lhsKind; BindValueKind rhsKind; ExpressionSyntax rhsExpr; bool isRef = false; if (node.Right.Kind() == SyntaxKind.RefExpression) { isRef = true; lhsKind = BindValueKind.RefAssignable; rhsKind = BindValueKind.RefersToLocation; rhsExpr = ((RefExpressionSyntax)node.Right).Expression; } else { lhsKind = BindValueKind.Assignable; rhsKind = BindValueKind.RValue; rhsExpr = node.Right; } var op1 = BindValue(node.Left, diagnostics, lhsKind); ReportSuppressionIfNeeded(op1, diagnostics); var lhsRefKind = RefKind.None; // If the LHS is a ref (not ref-readonly), the rhs // must also be value-assignable if (lhsKind == BindValueKind.RefAssignable && !op1.HasErrors) { // We should now know that op1 is a valid lvalue lhsRefKind = op1.GetRefKind(); if (lhsRefKind == RefKind.Ref || lhsRefKind == RefKind.Out) { rhsKind |= BindValueKind.Assignable; } } var op2 = BindValue(rhsExpr, diagnostics, rhsKind); if (op1.Kind == BoundKind.DiscardExpression) { op2 = BindToNaturalType(op2, diagnostics); op1 = InferTypeForDiscardAssignment((BoundDiscardExpression)op1, op2, diagnostics); } return BindAssignment(node, op1, op2, isRef, diagnostics); } private BoundExpression InferTypeForDiscardAssignment(BoundDiscardExpression op1, BoundExpression op2, BindingDiagnosticBag diagnostics) { var inferredType = op2.Type; if ((object)inferredType == null) { return op1.FailInference(this, diagnostics); } if (inferredType.IsVoidType()) { diagnostics.Add(ErrorCode.ERR_VoidAssignment, op1.Syntax.Location); } return op1.SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(inferredType)); } private BoundAssignmentOperator BindAssignment( SyntaxNode node, BoundExpression op1, BoundExpression op2, bool isRef, BindingDiagnosticBag diagnostics) { Debug.Assert(op1 != null); Debug.Assert(op2 != null); bool hasErrors = op1.HasAnyErrors || op2.HasAnyErrors; if (!op1.HasAnyErrors) { // Build bound conversion. The node might not be used if this is a dynamic conversion // but diagnostics should be reported anyways. var conversion = GenerateConversionForAssignment(op1.Type, op2, diagnostics, isRefAssignment: isRef); // If the result is a dynamic assignment operation (SetMember or SetIndex), // don't generate the boxing conversion to the dynamic type. // Leave the values as they are, and deal with the conversions at runtime. if (op1.Kind != BoundKind.DynamicIndexerAccess && op1.Kind != BoundKind.DynamicMemberAccess && op1.Kind != BoundKind.DynamicObjectInitializerMember) { op2 = conversion; } else { op2 = BindToNaturalType(op2, diagnostics); } if (isRef) { var leftEscape = GetRefEscape(op1, LocalScopeDepth); var rightEscape = GetRefEscape(op2, LocalScopeDepth); if (leftEscape < rightEscape) { Error(diagnostics, ErrorCode.ERR_RefAssignNarrower, node, op1.ExpressionSymbol.Name, op2.Syntax); op2 = ToBadExpression(op2); } } if (op1.Type.IsRefLikeType) { var leftEscape = GetValEscape(op1, LocalScopeDepth); op2 = ValidateEscape(op2, leftEscape, isByRef: false, diagnostics); } } else { op2 = BindToTypeForErrorRecovery(op2); } TypeSymbol type; if ((op1.Kind == BoundKind.EventAccess) && ((BoundEventAccess)op1).EventSymbol.IsWindowsRuntimeEvent) { // Event assignment is a call to void WindowsRuntimeMarshal.AddEventHandler<T>(). type = this.GetSpecialType(SpecialType.System_Void, diagnostics, node); } else { type = op1.Type; } return new BoundAssignmentOperator(node, op1, op2, isRef, type, hasErrors); } private static PropertySymbol GetPropertySymbol(BoundExpression expr, out BoundExpression receiver, out SyntaxNode propertySyntax) { PropertySymbol propertySymbol; switch (expr.Kind) { case BoundKind.PropertyAccess: { var propertyAccess = (BoundPropertyAccess)expr; receiver = propertyAccess.ReceiverOpt; propertySymbol = propertyAccess.PropertySymbol; } break; case BoundKind.IndexerAccess: { var indexerAccess = (BoundIndexerAccess)expr; receiver = indexerAccess.ReceiverOpt; propertySymbol = indexerAccess.Indexer; } break; case BoundKind.IndexOrRangePatternIndexerAccess: { var patternIndexer = (BoundIndexOrRangePatternIndexerAccess)expr; receiver = patternIndexer.Receiver; propertySymbol = (PropertySymbol)patternIndexer.PatternSymbol; } break; default: receiver = null; propertySymbol = null; propertySyntax = null; return null; } var syntax = expr.Syntax; switch (syntax.Kind()) { case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: propertySyntax = ((MemberAccessExpressionSyntax)syntax).Name; break; case SyntaxKind.IdentifierName: propertySyntax = syntax; break; case SyntaxKind.ElementAccessExpression: propertySyntax = ((ElementAccessExpressionSyntax)syntax).ArgumentList; break; default: // Other syntax types, such as QualifiedName, // might occur in invalid code. propertySyntax = syntax; break; } return propertySymbol; } private static SyntaxNode GetEventName(BoundEventAccess expr) { SyntaxNode syntax = expr.Syntax; switch (syntax.Kind()) { case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: return ((MemberAccessExpressionSyntax)syntax).Name; case SyntaxKind.QualifiedName: // This case is reachable only through SemanticModel return ((QualifiedNameSyntax)syntax).Right; case SyntaxKind.IdentifierName: return syntax; case SyntaxKind.MemberBindingExpression: return ((MemberBindingExpressionSyntax)syntax).Name; default: throw ExceptionUtilities.UnexpectedValue(syntax.Kind()); } } /// <summary> /// There are two BadEventUsage error codes and this method decides which one should /// be used for a given event. /// </summary> private DiagnosticInfo GetBadEventUsageDiagnosticInfo(EventSymbol eventSymbol) { var leastOverridden = (EventSymbol)eventSymbol.GetLeastOverriddenMember(this.ContainingType); return leastOverridden.HasAssociatedField ? new CSDiagnosticInfo(ErrorCode.ERR_BadEventUsage, leastOverridden, leastOverridden.ContainingType) : new CSDiagnosticInfo(ErrorCode.ERR_BadEventUsageNoField, leastOverridden); } internal static bool AccessingAutoPropertyFromConstructor(BoundPropertyAccess propertyAccess, Symbol fromMember) { return AccessingAutoPropertyFromConstructor(propertyAccess.ReceiverOpt, propertyAccess.PropertySymbol, fromMember); } private static bool AccessingAutoPropertyFromConstructor(BoundExpression receiver, PropertySymbol propertySymbol, Symbol fromMember) { if (!propertySymbol.IsDefinition && propertySymbol.ContainingType.Equals(propertySymbol.ContainingType.OriginalDefinition, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { propertySymbol = propertySymbol.OriginalDefinition; } var sourceProperty = propertySymbol as SourcePropertySymbolBase; var propertyIsStatic = propertySymbol.IsStatic; return (object)sourceProperty != null && sourceProperty.IsAutoPropertyWithGetAccessor && TypeSymbol.Equals(sourceProperty.ContainingType, fromMember.ContainingType, TypeCompareKind.ConsiderEverything2) && IsConstructorOrField(fromMember, isStatic: propertyIsStatic) && (propertyIsStatic || receiver.Kind == BoundKind.ThisReference); } private static bool IsConstructorOrField(Symbol member, bool isStatic) { return (member as MethodSymbol)?.MethodKind == (isStatic ? MethodKind.StaticConstructor : MethodKind.Constructor) || (member as FieldSymbol)?.IsStatic == isStatic; } private TypeSymbol GetAccessThroughType(BoundExpression receiver) { if (receiver == null) { return this.ContainingType; } else if (receiver.Kind == BoundKind.BaseReference) { // Allow protected access to members defined // in base classes. See spec section 3.5.3. return null; } else { Debug.Assert((object)receiver.Type != null); return receiver.Type; } } private BoundExpression BindPossibleArrayInitializer( ExpressionSyntax node, TypeSymbol destinationType, BindValueKind valueKind, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); if (node.Kind() != SyntaxKind.ArrayInitializerExpression) { return BindValue(node, diagnostics, valueKind); } BoundExpression result; if (destinationType.Kind == SymbolKind.ArrayType) { result = BindArrayCreationWithInitializer(diagnostics, null, (InitializerExpressionSyntax)node, (ArrayTypeSymbol)destinationType, ImmutableArray<BoundExpression>.Empty); } else { result = BindUnexpectedArrayInitializer((InitializerExpressionSyntax)node, diagnostics, ErrorCode.ERR_ArrayInitToNonArrayType); } return CheckValue(result, valueKind, diagnostics); } protected virtual SourceLocalSymbol LookupLocal(SyntaxToken nameToken) { return Next.LookupLocal(nameToken); } protected virtual LocalFunctionSymbol LookupLocalFunction(SyntaxToken nameToken) { return Next.LookupLocalFunction(nameToken); } /// <summary> /// Returns a value that tells how many local scopes are visible, including the current. /// I.E. outside of any method will be 0 /// immediately inside a method - 1 /// </summary> internal virtual uint LocalScopeDepth => Next.LocalScopeDepth; internal virtual BoundBlock BindEmbeddedBlock(BlockSyntax node, BindingDiagnosticBag diagnostics) { return BindBlock(node, diagnostics); } private BoundBlock BindBlock(BlockSyntax node, BindingDiagnosticBag diagnostics) { if (node.AttributeLists.Count > 0) { Error(diagnostics, ErrorCode.ERR_AttributesNotAllowed, node.AttributeLists[0]); } var binder = GetBinder(node); Debug.Assert(binder != null); return binder.BindBlockParts(node, diagnostics); } private BoundBlock BindBlockParts(BlockSyntax node, BindingDiagnosticBag diagnostics) { var syntaxStatements = node.Statements; int nStatements = syntaxStatements.Count; ArrayBuilder<BoundStatement> boundStatements = ArrayBuilder<BoundStatement>.GetInstance(nStatements); for (int i = 0; i < nStatements; i++) { var boundStatement = BindStatement(syntaxStatements[i], diagnostics); boundStatements.Add(boundStatement); } return FinishBindBlockParts(node, boundStatements.ToImmutableAndFree(), diagnostics); } private BoundBlock FinishBindBlockParts(CSharpSyntaxNode node, ImmutableArray<BoundStatement> boundStatements, BindingDiagnosticBag diagnostics) { ImmutableArray<LocalSymbol> locals = GetDeclaredLocalsForScope(node); if (IsDirectlyInIterator) { var method = ContainingMemberOrLambda as MethodSymbol; if ((object)method != null) { method.IteratorElementTypeWithAnnotations = GetIteratorElementType(); } else { Debug.Assert(diagnostics.DiagnosticBag is null || !diagnostics.DiagnosticBag.IsEmptyWithoutResolution); } } return new BoundBlock( node, locals, GetDeclaredLocalFunctionsForScope(node), boundStatements); } internal BoundExpression GenerateConversionForAssignment(TypeSymbol targetType, BoundExpression expression, BindingDiagnosticBag diagnostics, bool isDefaultParameter = false, bool isRefAssignment = false) { Debug.Assert((object)targetType != null); Debug.Assert(expression != null); // We wish to avoid "cascading" errors, so if the expression we are // attempting to convert to a type had errors, suppress additional // diagnostics. However, if the expression // with errors is an unbound lambda then the errors are almost certainly // syntax errors. For error recovery analysis purposes we wish to bind // error lambdas like "Action<int> f = x=>{ x. };" because IntelliSense // needs to know that x is of type int. if (expression.HasAnyErrors && expression.Kind != BoundKind.UnboundLambda) { diagnostics = BindingDiagnosticBag.Discarded; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var conversion = this.Conversions.ClassifyConversionFromExpression(expression, targetType, ref useSiteInfo); diagnostics.Add(expression.Syntax, useSiteInfo); if (isRefAssignment) { if (conversion.Kind != ConversionKind.Identity) { Error(diagnostics, ErrorCode.ERR_RefAssignmentMustHaveIdentityConversion, expression.Syntax, targetType); } else { return expression; } } else if (!conversion.IsImplicit || !conversion.IsValid) { // We suppress conversion errors on default parameters; eg, // if someone says "void M(string s = 123) {}". We will report // a special error in the default parameter binder. if (!isDefaultParameter) { GenerateImplicitConversionError(diagnostics, expression.Syntax, conversion, expression, targetType); } // Suppress any additional diagnostics diagnostics = BindingDiagnosticBag.Discarded; } return CreateConversion(expression.Syntax, expression, conversion, isCast: false, conversionGroupOpt: null, targetType, diagnostics); } #nullable enable internal void GenerateAnonymousFunctionConversionError(BindingDiagnosticBag diagnostics, SyntaxNode syntax, UnboundLambda anonymousFunction, TypeSymbol targetType) { Debug.Assert((object)targetType != null); Debug.Assert(anonymousFunction != null); // Is the target type simply bad? // If the target type is an error then we've already reported a diagnostic. Don't bother // reporting the conversion error. if (targetType.IsErrorType()) { return; } // CONSIDER: Instead of computing this again, cache the reason why the conversion failed in // CONSIDER: the Conversion result, and simply report that. var reason = Conversions.IsAnonymousFunctionCompatibleWithType(anonymousFunction, targetType); // It is possible that the conversion from lambda to delegate is just fine, and // that we ended up here because the target type, though itself is not an error // type, contains a type argument which is an error type. For example, converting // (Goo goo)=>{} to Action<Goo> is a perfectly legal conversion even if Goo is undefined! // In that case we have already reported an error that Goo is undefined, so just bail out. if (reason == LambdaConversionResult.Success) { return; } var id = anonymousFunction.MessageID.Localize(); if (reason == LambdaConversionResult.BadTargetType) { if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, targetType, node: syntax)) { return; } // Cannot convert {0} to type '{1}' because it is not a delegate type Error(diagnostics, ErrorCode.ERR_AnonMethToNonDel, syntax, id, targetType); return; } if (reason == LambdaConversionResult.ExpressionTreeMustHaveDelegateTypeArgument) { Debug.Assert(targetType.IsExpressionTree()); Error(diagnostics, ErrorCode.ERR_ExpressionTreeMustHaveDelegate, syntax, ((NamedTypeSymbol)targetType).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type); return; } if (reason == LambdaConversionResult.ExpressionTreeFromAnonymousMethod) { Debug.Assert(targetType.IsGenericOrNonGenericExpressionType(out _)); Error(diagnostics, ErrorCode.ERR_AnonymousMethodToExpressionTree, syntax); return; } if (reason == LambdaConversionResult.MismatchedReturnType) { Error(diagnostics, ErrorCode.ERR_CantConvAnonMethReturnType, syntax, id, targetType); return; } if (reason == LambdaConversionResult.CannotInferDelegateType) { Debug.Assert(targetType.SpecialType == SpecialType.System_Delegate || targetType.IsNonGenericExpressionType()); Error(diagnostics, ErrorCode.ERR_CannotInferDelegateType, syntax); var lambda = anonymousFunction.BindForErrorRecovery(); diagnostics.AddRange(lambda.Diagnostics); return; } // At this point we know that we have either a delegate type or an expression type for the target. // The target type is a valid delegate or expression tree type. Is there something wrong with the // parameter list? // First off, is there a parameter list at all? if (reason == LambdaConversionResult.MissingSignatureWithOutParameter) { // COMPATIBILITY: The C# 4 compiler produces two errors for: // // delegate void D (out int x); // ... // D d = delegate {}; // // error CS1676: Parameter 1 must be declared with the 'out' keyword // error CS1688: Cannot convert anonymous method block without a parameter list // to delegate type 'D' because it has one or more out parameters // // This seems redundant, (because there is no "parameter 1" in the source code) // and unnecessary. I propose that we eliminate the first error. Error(diagnostics, ErrorCode.ERR_CantConvAnonMethNoParams, syntax, targetType); return; } var delegateType = targetType.GetDelegateType(); Debug.Assert(delegateType is not null); // There is a parameter list. Does it have the right number of elements? if (reason == LambdaConversionResult.BadParameterCount) { // Delegate '{0}' does not take {1} arguments Error(diagnostics, ErrorCode.ERR_BadDelArgCount, syntax, delegateType, anonymousFunction.ParameterCount); return; } // The parameter list exists and had the right number of parameters. Were any of its types bad? // If any parameter type of the lambda is an error type then suppress // further errors. We've already reported errors on the bad type. if (anonymousFunction.HasExplicitlyTypedParameterList) { for (int i = 0; i < anonymousFunction.ParameterCount; ++i) { if (anonymousFunction.ParameterType(i).IsErrorType()) { return; } } } // The parameter list exists and had the right number of parameters. Were any of its types // mismatched with the delegate parameter types? // The simplest possible case is (x, y, z)=>whatever where the target type has a ref or out parameter. var delegateParameters = delegateType.DelegateParameters(); if (reason == LambdaConversionResult.RefInImplicitlyTypedLambda) { for (int i = 0; i < anonymousFunction.ParameterCount; ++i) { var delegateRefKind = delegateParameters[i].RefKind; if (delegateRefKind != RefKind.None) { // Parameter {0} must be declared with the '{1}' keyword Error(diagnostics, ErrorCode.ERR_BadParamRef, anonymousFunction.ParameterLocation(i), i + 1, delegateRefKind.ToParameterDisplayString()); } } return; } // See the comments in IsAnonymousFunctionCompatibleWithDelegate for an explanation of this one. if (reason == LambdaConversionResult.StaticTypeInImplicitlyTypedLambda) { for (int i = 0; i < anonymousFunction.ParameterCount; ++i) { if (delegateParameters[i].TypeWithAnnotations.IsStatic) { // {0}: Static types cannot be used as parameter Error(diagnostics, ErrorFacts.GetStaticClassParameterCode(useWarning: false), anonymousFunction.ParameterLocation(i), delegateParameters[i].Type); } } return; } // Otherwise, there might be a more complex reason why the parameter types are mismatched. if (reason == LambdaConversionResult.MismatchedParameterType) { // Cannot convert {0} to type '{1}' because the parameter types do not match the delegate parameter types Error(diagnostics, ErrorCode.ERR_CantConvAnonMethParams, syntax, id, targetType); Debug.Assert(anonymousFunction.ParameterCount == delegateParameters.Length); for (int i = 0; i < anonymousFunction.ParameterCount; ++i) { var lambdaParameterType = anonymousFunction.ParameterType(i); if (lambdaParameterType.IsErrorType()) { continue; } var lambdaParameterLocation = anonymousFunction.ParameterLocation(i); var lambdaRefKind = anonymousFunction.RefKind(i); var delegateParameterType = delegateParameters[i].Type; var delegateRefKind = delegateParameters[i].RefKind; if (!lambdaParameterType.Equals(delegateParameterType, TypeCompareKind.AllIgnoreOptions)) { SymbolDistinguisher distinguisher = new SymbolDistinguisher(this.Compilation, lambdaParameterType, delegateParameterType); // Parameter {0} is declared as type '{1}{2}' but should be '{3}{4}' Error(diagnostics, ErrorCode.ERR_BadParamType, lambdaParameterLocation, i + 1, lambdaRefKind.ToParameterPrefix(), distinguisher.First, delegateRefKind.ToParameterPrefix(), distinguisher.Second); } else if (lambdaRefKind != delegateRefKind) { if (delegateRefKind == RefKind.None) { // Parameter {0} should not be declared with the '{1}' keyword Error(diagnostics, ErrorCode.ERR_BadParamExtraRef, lambdaParameterLocation, i + 1, lambdaRefKind.ToParameterDisplayString()); } else { // Parameter {0} must be declared with the '{1}' keyword Error(diagnostics, ErrorCode.ERR_BadParamRef, lambdaParameterLocation, i + 1, delegateRefKind.ToParameterDisplayString()); } } } return; } if (reason == LambdaConversionResult.BindingFailed) { var bindingResult = anonymousFunction.Bind(delegateType, isExpressionTree: false); Debug.Assert(ErrorFacts.PreventsSuccessfulDelegateConversion(bindingResult.Diagnostics.Diagnostics)); diagnostics.AddRange(bindingResult.Diagnostics); return; } // UNDONE: LambdaConversionResult.VoidExpressionLambdaMustBeStatementExpression: Debug.Assert(false, "Missing case in lambda conversion error reporting"); diagnostics.Add(ErrorCode.ERR_InternalError, syntax.Location); } #nullable disable protected static void GenerateImplicitConversionError(BindingDiagnosticBag diagnostics, CSharpCompilation compilation, SyntaxNode syntax, Conversion conversion, TypeSymbol sourceType, TypeSymbol targetType, ConstantValue sourceConstantValueOpt = null) { Debug.Assert(!conversion.IsImplicit || !conversion.IsValid); // If the either type is an error then an error has already been reported // for some aspect of the analysis of this expression. (For example, something like // "garbage g = null; short s = g;" -- we don't want to report that g is not // convertible to short because we've already reported that g does not have a good type. if (!sourceType.IsErrorType() && !targetType.IsErrorType()) { if (conversion.IsExplicit) { if (sourceType.SpecialType == SpecialType.System_Double && syntax.Kind() == SyntaxKind.NumericLiteralExpression && (targetType.SpecialType == SpecialType.System_Single || targetType.SpecialType == SpecialType.System_Decimal)) { Error(diagnostics, ErrorCode.ERR_LiteralDoubleCast, syntax, (targetType.SpecialType == SpecialType.System_Single) ? "F" : "M", targetType); } else if (conversion.Kind == ConversionKind.ExplicitNumeric && sourceConstantValueOpt != null && sourceConstantValueOpt != ConstantValue.Bad && ConversionsBase.HasImplicitConstantExpressionConversion(new BoundLiteral(syntax, ConstantValue.Bad, sourceType), targetType)) { // CLEVERNESS: By passing ConstantValue.Bad, we tell HasImplicitConstantExpressionConversion to ignore the constant // value and only consider the types. // If there would be an implicit constant conversion for a different constant of the same type // (i.e. one that's not out of range), then it's more helpful to report the range check failure // than to suggest inserting a cast. Error(diagnostics, ErrorCode.ERR_ConstOutOfRange, syntax, sourceConstantValueOpt.Value, targetType); } else { SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, sourceType, targetType); Error(diagnostics, ErrorCode.ERR_NoImplicitConvCast, syntax, distinguisher.First, distinguisher.Second); } } else if (conversion.ResultKind == LookupResultKind.OverloadResolutionFailure) { Debug.Assert(conversion.IsUserDefined); ImmutableArray<MethodSymbol> originalUserDefinedConversions = conversion.OriginalUserDefinedConversions; if (originalUserDefinedConversions.Length > 1) { Error(diagnostics, ErrorCode.ERR_AmbigUDConv, syntax, originalUserDefinedConversions[0], originalUserDefinedConversions[1], sourceType, targetType); } else { Debug.Assert(originalUserDefinedConversions.Length == 0, "How can there be exactly one applicable user-defined conversion if the conversion doesn't exist?"); SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, sourceType, targetType); Error(diagnostics, ErrorCode.ERR_NoImplicitConv, syntax, distinguisher.First, distinguisher.Second); } } else if (TypeSymbol.Equals(sourceType, targetType, TypeCompareKind.ConsiderEverything2)) { // This occurs for `void`, which cannot even convert to itself. Since SymbolDistinguisher // requires two distinct types, we preempt its use here. The diagnostic is strange, but correct. // Though this diagnostic tends to be a cascaded one, we cannot suppress it until // we have proven that it is always so. Error(diagnostics, ErrorCode.ERR_NoImplicitConv, syntax, sourceType, targetType); } else { SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, sourceType, targetType); Error(diagnostics, ErrorCode.ERR_NoImplicitConv, syntax, distinguisher.First, distinguisher.Second); } } } protected void GenerateImplicitConversionError( BindingDiagnosticBag diagnostics, SyntaxNode syntax, Conversion conversion, BoundExpression operand, TypeSymbol targetType) { Debug.Assert(operand != null); Debug.Assert((object)targetType != null); if (targetType.TypeKind == TypeKind.Error) { return; } if (targetType.IsVoidType()) { Error(diagnostics, ErrorCode.ERR_NoImplicitConv, syntax, operand.Display, targetType); return; } switch (operand.Kind) { case BoundKind.BadExpression: { return; } case BoundKind.UnboundLambda: { GenerateAnonymousFunctionConversionError(diagnostics, syntax, (UnboundLambda)operand, targetType); return; } case BoundKind.TupleLiteral: { var tuple = (BoundTupleLiteral)operand; var targetElementTypes = default(ImmutableArray<TypeWithAnnotations>); // If target is a tuple or compatible type with the same number of elements, // report errors for tuple arguments that failed to convert, which would be more useful. if (targetType.TryGetElementTypesWithAnnotationsIfTupleType(out targetElementTypes) && targetElementTypes.Length == tuple.Arguments.Length) { GenerateImplicitConversionErrorsForTupleLiteralArguments(diagnostics, tuple.Arguments, targetElementTypes); return; } // target is not compatible with source and source does not have a type if ((object)tuple.Type == null) { Error(diagnostics, ErrorCode.ERR_ConversionNotTupleCompatible, syntax, tuple.Arguments.Length, targetType); return; } // Otherwise it is just a regular conversion failure from T1 to T2. break; } case BoundKind.MethodGroup: { reportMethodGroupErrors((BoundMethodGroup)operand, fromAddressOf: false); return; } case BoundKind.UnconvertedAddressOfOperator: { reportMethodGroupErrors(((BoundUnconvertedAddressOfOperator)operand).Operand, fromAddressOf: true); return; } case BoundKind.Literal: { if (operand.IsLiteralNull()) { if (targetType.TypeKind == TypeKind.TypeParameter) { Error(diagnostics, ErrorCode.ERR_TypeVarCantBeNull, syntax, targetType); return; } if (targetType.IsValueType) { Error(diagnostics, ErrorCode.ERR_ValueCantBeNull, syntax, targetType); return; } } break; } case BoundKind.StackAllocArrayCreation: { var stackAllocExpression = (BoundStackAllocArrayCreation)operand; Error(diagnostics, ErrorCode.ERR_StackAllocConversionNotPossible, syntax, stackAllocExpression.ElementType, targetType); return; } case BoundKind.UnconvertedSwitchExpression: { var switchExpression = (BoundUnconvertedSwitchExpression)operand; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; bool reportedError = false; foreach (var arm in switchExpression.SwitchArms) { tryConversion(arm.Value, ref reportedError, ref discardedUseSiteInfo); } Debug.Assert(reportedError); return; } case BoundKind.AddressOfOperator when targetType.IsFunctionPointer(): { Error(diagnostics, ErrorCode.ERR_InvalidAddrOp, ((BoundAddressOfOperator)operand).Operand.Syntax); return; } case BoundKind.UnconvertedConditionalOperator: { var conditionalOperator = (BoundUnconvertedConditionalOperator)operand; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; bool reportedError = false; tryConversion(conditionalOperator.Consequence, ref reportedError, ref discardedUseSiteInfo); tryConversion(conditionalOperator.Alternative, ref reportedError, ref discardedUseSiteInfo); Debug.Assert(reportedError); return; } void tryConversion(BoundExpression expr, ref bool reportedError, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var conversion = this.Conversions.ClassifyImplicitConversionFromExpression(expr, targetType, ref useSiteInfo); if (!conversion.IsImplicit || !conversion.IsValid) { GenerateImplicitConversionError(diagnostics, expr.Syntax, conversion, expr, targetType); reportedError = true; } } } var sourceType = operand.Type; if ((object)sourceType != null) { GenerateImplicitConversionError(diagnostics, this.Compilation, syntax, conversion, sourceType, targetType, operand.ConstantValue); return; } Debug.Assert(operand.HasAnyErrors && operand.Kind != BoundKind.UnboundLambda, "Missing a case in implicit conversion error reporting"); void reportMethodGroupErrors(BoundMethodGroup methodGroup, bool fromAddressOf) { if (!Conversions.ReportDelegateOrFunctionPointerMethodGroupDiagnostics(this, methodGroup, targetType, diagnostics)) { var nodeForError = syntax; while (nodeForError.Kind() == SyntaxKind.ParenthesizedExpression) { nodeForError = ((ParenthesizedExpressionSyntax)nodeForError).Expression; } if (nodeForError.Kind() == SyntaxKind.SimpleMemberAccessExpression || nodeForError.Kind() == SyntaxKind.PointerMemberAccessExpression) { nodeForError = ((MemberAccessExpressionSyntax)nodeForError).Name; } var location = nodeForError.Location; if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, targetType, location)) { return; } ErrorCode errorCode; switch (targetType.TypeKind) { case TypeKind.FunctionPointer when fromAddressOf: errorCode = ErrorCode.ERR_MethFuncPtrMismatch; break; case TypeKind.FunctionPointer: Error(diagnostics, ErrorCode.ERR_MissingAddressOf, location); return; case TypeKind.Delegate when fromAddressOf: errorCode = ErrorCode.ERR_CannotConvertAddressOfToDelegate; break; case TypeKind.Delegate: errorCode = ErrorCode.ERR_MethDelegateMismatch; break; default: if (fromAddressOf) { errorCode = ErrorCode.ERR_AddressOfToNonFunctionPointer; } else if (targetType.SpecialType == SpecialType.System_Delegate && syntax.IsFeatureEnabled(MessageID.IDS_FeatureInferredDelegateType)) { Error(diagnostics, ErrorCode.ERR_CannotInferDelegateType, location); return; } else { errorCode = ErrorCode.ERR_MethGrpToNonDel; } break; } Error(diagnostics, errorCode, location, methodGroup.Name, targetType); } } } private void GenerateImplicitConversionErrorsForTupleLiteralArguments( BindingDiagnosticBag diagnostics, ImmutableArray<BoundExpression> tupleArguments, ImmutableArray<TypeWithAnnotations> targetElementTypes) { var argLength = tupleArguments.Length; // report all leaf elements of the tuple literal that failed to convert // NOTE: we are not responsible for reporting use site errors here, just the failed leaf conversions. // By the time we get here we have done analysis and know we have failed the cast in general, and diagnostics collected in the process is already in the bag. // The only thing left is to form a diagnostics about the actually failing conversion(s). // This whole method does not itself collect any usesite diagnostics. Its only purpose is to produce an error better than "conversion failed here" var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; for (int i = 0; i < targetElementTypes.Length; i++) { var argument = tupleArguments[i]; var targetElementType = targetElementTypes[i].Type; var elementConversion = Conversions.ClassifyImplicitConversionFromExpression(argument, targetElementType, ref discardedUseSiteInfo); if (!elementConversion.IsValid) { GenerateImplicitConversionError(diagnostics, argument.Syntax, elementConversion, argument, targetElementType); } } } private BoundStatement BindIfStatement(IfStatementSyntax node, BindingDiagnosticBag diagnostics) { var condition = BindBooleanExpression(node.Condition, diagnostics); var consequence = BindPossibleEmbeddedStatement(node.Statement, diagnostics); BoundStatement alternative = (node.Else == null) ? null : BindPossibleEmbeddedStatement(node.Else.Statement, diagnostics); BoundStatement result = new BoundIfStatement(node, condition, consequence, alternative); return result; } internal BoundExpression BindBooleanExpression(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { // SPEC: // A boolean-expression is an expression that yields a result of type bool; // either directly or through application of operator true in certain // contexts as specified in the following. // // The controlling conditional expression of an if-statement, while-statement, // do-statement, or for-statement is a boolean-expression. The controlling // conditional expression of the ?: operator follows the same rules as a // boolean-expression, but for reasons of operator precedence is classified // as a conditional-or-expression. // // A boolean-expression is required to be implicitly convertible to bool // or of a type that implements operator true. If neither requirement // is satisfied, a binding-time error occurs. // // When a boolean expression cannot be implicitly converted to bool but does // implement operator true, then following evaluation of the expression, // the operator true implementation provided by that type is invoked // to produce a bool value. // // SPEC ERROR: The third paragraph above is obviously not correct; we need // SPEC ERROR: to do more than just check to see whether the type implements // SPEC ERROR: operator true. First off, the type could implement the operator // SPEC ERROR: several times: if it is a struct then it could implement it // SPEC ERROR: twice, to take both nullable and non-nullable arguments, and // SPEC ERROR: if it is a class or type parameter then it could have several // SPEC ERROR: implementations on its base classes or effective base classes. // SPEC ERROR: Second, the type of the argument could be S? where S implements // SPEC ERROR: operator true(S?); we want to look at S, not S?, when looking // SPEC ERROR: for applicable candidates. // // SPEC ERROR: Basically, the spec should say "use unary operator overload resolution // SPEC ERROR: to find the candidate set and choose a unique best operator true". var expr = BindValue(node, diagnostics, BindValueKind.RValue); var boolean = GetSpecialType(SpecialType.System_Boolean, diagnostics, node); if (expr.HasAnyErrors) { // The expression could not be bound. Insert a fake conversion // around it to bool and keep on going. // NOTE: no user-defined conversion candidates. return BoundConversion.Synthesized(node, BindToTypeForErrorRecovery(expr), Conversion.NoConversion, false, explicitCastInCode: false, conversionGroupOpt: null, ConstantValue.NotAvailable, boolean, hasErrors: true); } // Oddly enough, "if(dyn)" is bound not as a dynamic conversion to bool, but as a dynamic // invocation of operator true. if (expr.HasDynamicType()) { return new BoundUnaryOperator( node, UnaryOperatorKind.DynamicTrue, BindToNaturalType(expr, diagnostics), ConstantValue.NotAvailable, methodOpt: null, constrainedToTypeOpt: null, LookupResultKind.Viable, boolean) { WasCompilerGenerated = true }; } // Is the operand implicitly convertible to bool? CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var conversion = this.Conversions.ClassifyConversionFromExpression(expr, boolean, ref useSiteInfo); diagnostics.Add(expr.Syntax, useSiteInfo); if (conversion.IsImplicit) { if (conversion.Kind == ConversionKind.Identity) { // Check to see if we're assigning a boolean literal in a place where an // equality check would be more conventional. // NOTE: Don't do this check unless the expression will be returned // without being wrapped in another bound node (i.e. identity conversion). if (expr.Kind == BoundKind.AssignmentOperator) { var assignment = (BoundAssignmentOperator)expr; if (assignment.Right.Kind == BoundKind.Literal && assignment.Right.ConstantValue.Discriminator == ConstantValueTypeDiscriminator.Boolean) { Error(diagnostics, ErrorCode.WRN_IncorrectBooleanAssg, assignment.Syntax); } } } return CreateConversion( syntax: expr.Syntax, source: expr, conversion: conversion, isCast: false, conversionGroupOpt: null, wasCompilerGenerated: true, destination: boolean, diagnostics: diagnostics); } // It was not. Does it implement operator true? expr = BindToNaturalType(expr, diagnostics); var best = this.UnaryOperatorOverloadResolution(UnaryOperatorKind.True, expr, node, diagnostics, out LookupResultKind resultKind, out ImmutableArray<MethodSymbol> originalUserDefinedOperators); if (!best.HasValue) { // No. Give a "not convertible to bool" error. Debug.Assert(resultKind == LookupResultKind.Empty, "How could overload resolution fail if a user-defined true operator was found?"); Debug.Assert(originalUserDefinedOperators.IsEmpty, "How could overload resolution fail if a user-defined true operator was found?"); GenerateImplicitConversionError(diagnostics, node, conversion, expr, boolean); return BoundConversion.Synthesized(node, expr, Conversion.NoConversion, false, explicitCastInCode: false, conversionGroupOpt: null, ConstantValue.NotAvailable, boolean, hasErrors: true); } UnaryOperatorSignature signature = best.Signature; BoundExpression resultOperand = CreateConversion( node, expr, best.Conversion, isCast: false, conversionGroupOpt: null, destination: best.Signature.OperandType, diagnostics: diagnostics); CheckConstraintLanguageVersionAndRuntimeSupportForOperator(node, signature.Method, signature.ConstrainedToTypeOpt, diagnostics); // Consider op_true to be compiler-generated so that it doesn't appear in the semantic model. // UNDONE: If we decide to expose the operator in the semantic model, we'll have to remove the // WasCompilerGenerated flag (and possibly suppress the symbol in specific APIs). return new BoundUnaryOperator(node, signature.Kind, resultOperand, ConstantValue.NotAvailable, signature.Method, signature.ConstrainedToTypeOpt, resultKind, originalUserDefinedOperators, signature.ReturnType) { WasCompilerGenerated = true }; } private BoundStatement BindSwitchStatement(SwitchStatementSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Binder switchBinder = this.GetBinder(node); return switchBinder.BindSwitchStatementCore(node, switchBinder, diagnostics); } internal virtual BoundStatement BindSwitchStatementCore(SwitchStatementSyntax node, Binder originalBinder, BindingDiagnosticBag diagnostics) { return this.Next.BindSwitchStatementCore(node, originalBinder, diagnostics); } internal virtual void BindPatternSwitchLabelForInference(CasePatternSwitchLabelSyntax node, BindingDiagnosticBag diagnostics) { this.Next.BindPatternSwitchLabelForInference(node, diagnostics); } private BoundStatement BindWhile(WhileStatementSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); var loopBinder = this.GetBinder(node); Debug.Assert(loopBinder != null); return loopBinder.BindWhileParts(diagnostics, loopBinder); } internal virtual BoundWhileStatement BindWhileParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindWhileParts(diagnostics, originalBinder); } private BoundStatement BindDo(DoStatementSyntax node, BindingDiagnosticBag diagnostics) { var loopBinder = this.GetBinder(node); Debug.Assert(loopBinder != null); return loopBinder.BindDoParts(diagnostics, loopBinder); } internal virtual BoundDoStatement BindDoParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindDoParts(diagnostics, originalBinder); } internal BoundForStatement BindFor(ForStatementSyntax node, BindingDiagnosticBag diagnostics) { var loopBinder = this.GetBinder(node); Debug.Assert(loopBinder != null); return loopBinder.BindForParts(diagnostics, loopBinder); } internal virtual BoundForStatement BindForParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindForParts(diagnostics, originalBinder); } internal BoundStatement BindForOrUsingOrFixedDeclarations(VariableDeclarationSyntax nodeOpt, LocalDeclarationKind localKind, BindingDiagnosticBag diagnostics, out ImmutableArray<BoundLocalDeclaration> declarations) { if (nodeOpt == null) { declarations = ImmutableArray<BoundLocalDeclaration>.Empty; return null; } var typeSyntax = nodeOpt.Type; // Fixed and using variables are not allowed to be ref-like, but regular variables are if (localKind == LocalDeclarationKind.RegularVariable) { typeSyntax = typeSyntax.SkipRef(out _); } AliasSymbol alias; bool isVar; TypeWithAnnotations declType = BindTypeOrVarKeyword(typeSyntax, diagnostics, out isVar, out alias); Debug.Assert(declType.HasType || isVar); var variables = nodeOpt.Variables; int count = variables.Count; Debug.Assert(count > 0); if (isVar && count > 1) { // There are a number of ways in which a var decl can be illegal, but in these // cases we should report an error and then keep right on going with the inference. Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, nodeOpt); } var declarationArray = new BoundLocalDeclaration[count]; for (int i = 0; i < count; i++) { var variableDeclarator = variables[i]; bool includeBoundType = i == 0; //To avoid duplicated expressions, only the first declaration should contain the bound type. var declaration = BindVariableDeclaration(localKind, isVar, variableDeclarator, typeSyntax, declType, alias, diagnostics, includeBoundType); declarationArray[i] = declaration; } declarations = declarationArray.AsImmutableOrNull(); return (count == 1) ? (BoundStatement)declarations[0] : new BoundMultipleLocalDeclarations(nodeOpt, declarations); } internal BoundStatement BindStatementExpressionList(SeparatedSyntaxList<ExpressionSyntax> statements, BindingDiagnosticBag diagnostics) { int count = statements.Count; if (count == 0) { return null; } else if (count == 1) { var syntax = statements[0]; return BindExpressionStatement(syntax, syntax, false, diagnostics); } else { var statementBuilder = ArrayBuilder<BoundStatement>.GetInstance(); for (int i = 0; i < count; i++) { var syntax = statements[i]; var statement = BindExpressionStatement(syntax, syntax, false, diagnostics); statementBuilder.Add(statement); } return BoundStatementList.Synthesized(statements.Node, statementBuilder.ToImmutableAndFree()); } } private BoundStatement BindForEach(CommonForEachStatementSyntax node, BindingDiagnosticBag diagnostics) { Binder loopBinder = this.GetBinder(node); return this.GetBinder(node.Expression).WrapWithVariablesIfAny(node.Expression, loopBinder.BindForEachParts(diagnostics, loopBinder)); } internal virtual BoundStatement BindForEachParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindForEachParts(diagnostics, originalBinder); } /// <summary> /// Like BindForEachParts, but only bind the deconstruction part of the foreach, for purpose of inferring the types of the declared locals. /// </summary> internal virtual BoundStatement BindForEachDeconstruction(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindForEachDeconstruction(diagnostics, originalBinder); } private BoundStatement BindBreak(BreakStatementSyntax node, BindingDiagnosticBag diagnostics) { var target = this.BreakLabel; if ((object)target == null) { Error(diagnostics, ErrorCode.ERR_NoBreakOrCont, node); return new BoundBadStatement(node, ImmutableArray<BoundNode>.Empty, hasErrors: true); } return new BoundBreakStatement(node, target); } private BoundStatement BindContinue(ContinueStatementSyntax node, BindingDiagnosticBag diagnostics) { var target = this.ContinueLabel; if ((object)target == null) { Error(diagnostics, ErrorCode.ERR_NoBreakOrCont, node); return new BoundBadStatement(node, ImmutableArray<BoundNode>.Empty, hasErrors: true); } return new BoundContinueStatement(node, target); } private static SwitchBinder GetSwitchBinder(Binder binder) { SwitchBinder switchBinder = binder as SwitchBinder; while (binder != null && switchBinder == null) { binder = binder.Next; switchBinder = binder as SwitchBinder; } return switchBinder; } protected static bool IsInAsyncMethod(MethodSymbol method) { return (object)method != null && method.IsAsync; } protected bool IsInAsyncMethod() { return IsInAsyncMethod(this.ContainingMemberOrLambda as MethodSymbol); } protected bool IsEffectivelyTaskReturningAsyncMethod() { var symbol = this.ContainingMemberOrLambda; return symbol?.Kind == SymbolKind.Method && ((MethodSymbol)symbol).IsAsyncEffectivelyReturningTask(this.Compilation); } protected bool IsEffectivelyGenericTaskReturningAsyncMethod() { var symbol = this.ContainingMemberOrLambda; return symbol?.Kind == SymbolKind.Method && ((MethodSymbol)symbol).IsAsyncEffectivelyReturningGenericTask(this.Compilation); } protected bool IsIAsyncEnumerableOrIAsyncEnumeratorReturningAsyncMethod() { var symbol = this.ContainingMemberOrLambda; if (symbol?.Kind == SymbolKind.Method) { var method = (MethodSymbol)symbol; return method.IsAsyncReturningIAsyncEnumerable(this.Compilation) || method.IsAsyncReturningIAsyncEnumerator(this.Compilation); } return false; } protected virtual TypeSymbol GetCurrentReturnType(out RefKind refKind) { var symbol = this.ContainingMemberOrLambda as MethodSymbol; if ((object)symbol != null) { refKind = symbol.RefKind; TypeSymbol returnType = symbol.ReturnType; if ((object)returnType == LambdaSymbol.ReturnTypeIsBeingInferred) { return null; } return returnType; } refKind = RefKind.None; return null; } private BoundStatement BindReturn(ReturnStatementSyntax syntax, BindingDiagnosticBag diagnostics) { var refKind = RefKind.None; var expressionSyntax = syntax.Expression?.CheckAndUnwrapRefExpression(diagnostics, out refKind); BoundExpression arg = null; if (expressionSyntax != null) { BindValueKind requiredValueKind = GetRequiredReturnValueKind(refKind); arg = BindValue(expressionSyntax, diagnostics, requiredValueKind); } else { // If this is a void return statement in a script, return default(T). var interactiveInitializerMethod = this.ContainingMemberOrLambda as SynthesizedInteractiveInitializerMethod; if (interactiveInitializerMethod != null) { arg = new BoundDefaultExpression(interactiveInitializerMethod.GetNonNullSyntaxNode(), interactiveInitializerMethod.ResultType); } } RefKind sigRefKind; TypeSymbol retType = GetCurrentReturnType(out sigRefKind); bool hasErrors = false; if (IsDirectlyInIterator) { diagnostics.Add(ErrorCode.ERR_ReturnInIterator, syntax.ReturnKeyword.GetLocation()); hasErrors = true; } else if (IsInAsyncMethod()) { if (refKind != RefKind.None) { // This can happen if we are binding an async anonymous method to a delegate type. diagnostics.Add(ErrorCode.ERR_MustNotHaveRefReturn, syntax.ReturnKeyword.GetLocation()); hasErrors = true; } else if (IsIAsyncEnumerableOrIAsyncEnumeratorReturningAsyncMethod()) { diagnostics.Add(ErrorCode.ERR_ReturnInIterator, syntax.ReturnKeyword.GetLocation()); hasErrors = true; } } else if ((object)retType != null && (refKind != RefKind.None) != (sigRefKind != RefKind.None)) { var errorCode = refKind != RefKind.None ? ErrorCode.ERR_MustNotHaveRefReturn : ErrorCode.ERR_MustHaveRefReturn; diagnostics.Add(errorCode, syntax.ReturnKeyword.GetLocation()); hasErrors = true; } if (arg != null) { hasErrors |= arg.HasErrors || ((object)arg.Type != null && arg.Type.IsErrorType()); } if (hasErrors) { return new BoundReturnStatement(syntax, refKind, BindToTypeForErrorRecovery(arg), hasErrors: true); } // The return type could be null; we might be attempting to infer the return type either // because of method type inference, or because we are attempting to do error analysis // on a lambda expression of unknown return type. if ((object)retType != null) { if (retType.IsVoidType() || IsEffectivelyTaskReturningAsyncMethod()) { if (arg != null) { var container = this.ContainingMemberOrLambda; var lambda = container as LambdaSymbol; if ((object)lambda != null) { // Error case: void-returning or async task-returning method or lambda with "return x;" var errorCode = retType.IsVoidType() ? ErrorCode.ERR_RetNoObjectRequiredLambda : ErrorCode.ERR_TaskRetNoObjectRequiredLambda; // Anonymous function converted to a void returning delegate cannot return a value Error(diagnostics, errorCode, syntax.ReturnKeyword); hasErrors = true; // COMPATIBILITY: The native compiler also produced an error // COMPATIBILITY: "Cannot convert lambda expression to delegate type 'Action' because some of the // COMPATIBILITY: return types in the block are not implicitly convertible to the delegate return type" // COMPATIBILITY: This error doesn't make sense in the "void" case because the whole idea of // COMPATIBILITY: "conversion to void" is a bit unusual, and we've already given a good error. } else { // Error case: void-returning or async task-returning method or lambda with "return x;" var errorCode = retType.IsVoidType() ? ErrorCode.ERR_RetNoObjectRequired : ErrorCode.ERR_TaskRetNoObjectRequired; Error(diagnostics, errorCode, syntax.ReturnKeyword, container); hasErrors = true; } } } else { if (arg == null) { // Error case: non-void-returning or Task<T>-returning method or lambda but just have "return;" var requiredType = IsEffectivelyGenericTaskReturningAsyncMethod() ? retType.GetMemberTypeArgumentsNoUseSiteDiagnostics().Single() : retType; Error(diagnostics, ErrorCode.ERR_RetObjectRequired, syntax.ReturnKeyword, requiredType); hasErrors = true; } else { arg = CreateReturnConversion(syntax, diagnostics, arg, sigRefKind, retType); arg = ValidateEscape(arg, Binder.ExternalScope, refKind != RefKind.None, diagnostics); } } } else { // Check that the returned expression is not void. if ((object)arg?.Type != null && arg.Type.IsVoidType()) { Error(diagnostics, ErrorCode.ERR_CantReturnVoid, expressionSyntax); hasErrors = true; } } return new BoundReturnStatement(syntax, refKind, hasErrors ? BindToTypeForErrorRecovery(arg) : arg, hasErrors); } internal BoundExpression CreateReturnConversion( SyntaxNode syntax, BindingDiagnosticBag diagnostics, BoundExpression argument, RefKind returnRefKind, TypeSymbol returnType) { // If the return type is not void then the expression must be implicitly convertible. Conversion conversion; bool badAsyncReturnAlreadyReported = false; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (IsInAsyncMethod()) { Debug.Assert(returnRefKind == RefKind.None); if (!IsEffectivelyGenericTaskReturningAsyncMethod()) { conversion = Conversion.NoConversion; badAsyncReturnAlreadyReported = true; } else { returnType = returnType.GetMemberTypeArgumentsNoUseSiteDiagnostics().Single(); conversion = this.Conversions.ClassifyConversionFromExpression(argument, returnType, ref useSiteInfo); } } else { conversion = this.Conversions.ClassifyConversionFromExpression(argument, returnType, ref useSiteInfo); } diagnostics.Add(syntax, useSiteInfo); if (!argument.HasAnyErrors) { if (returnRefKind != RefKind.None) { if (conversion.Kind != ConversionKind.Identity) { Error(diagnostics, ErrorCode.ERR_RefReturnMustHaveIdentityConversion, argument.Syntax, returnType); argument = argument.WithHasErrors(); } else { return BindToNaturalType(argument, diagnostics); } } else if (!conversion.IsImplicit || !conversion.IsValid) { if (!badAsyncReturnAlreadyReported) { RefKind unusedRefKind; if (IsEffectivelyGenericTaskReturningAsyncMethod() && TypeSymbol.Equals(argument.Type, this.GetCurrentReturnType(out unusedRefKind), TypeCompareKind.ConsiderEverything2)) { // Since this is an async method, the return expression must be of type '{0}' rather than 'Task<{0}>' Error(diagnostics, ErrorCode.ERR_BadAsyncReturnExpression, argument.Syntax, returnType); } else { GenerateImplicitConversionError(diagnostics, argument.Syntax, conversion, argument, returnType); if (this.ContainingMemberOrLambda is LambdaSymbol) { ReportCantConvertLambdaReturn(argument.Syntax, diagnostics); } } } } } return CreateConversion(argument.Syntax, argument, conversion, isCast: false, conversionGroupOpt: null, returnType, diagnostics); } private BoundTryStatement BindTryStatement(TryStatementSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); var tryBlock = BindEmbeddedBlock(node.Block, diagnostics); var catchBlocks = BindCatchBlocks(node.Catches, diagnostics); var finallyBlockOpt = (node.Finally != null) ? BindEmbeddedBlock(node.Finally.Block, diagnostics) : null; return new BoundTryStatement(node, tryBlock, catchBlocks, finallyBlockOpt); } private ImmutableArray<BoundCatchBlock> BindCatchBlocks(SyntaxList<CatchClauseSyntax> catchClauses, BindingDiagnosticBag diagnostics) { int n = catchClauses.Count; if (n == 0) { return ImmutableArray<BoundCatchBlock>.Empty; } var catchBlocks = ArrayBuilder<BoundCatchBlock>.GetInstance(n); var hasCatchAll = false; foreach (var catchSyntax in catchClauses) { if (hasCatchAll) { diagnostics.Add(ErrorCode.ERR_TooManyCatches, catchSyntax.CatchKeyword.GetLocation()); } var catchBinder = this.GetBinder(catchSyntax); var catchBlock = catchBinder.BindCatchBlock(catchSyntax, catchBlocks, diagnostics); catchBlocks.Add(catchBlock); hasCatchAll |= catchSyntax.Declaration == null && catchSyntax.Filter == null; } return catchBlocks.ToImmutableAndFree(); } private BoundCatchBlock BindCatchBlock(CatchClauseSyntax node, ArrayBuilder<BoundCatchBlock> previousBlocks, BindingDiagnosticBag diagnostics) { bool hasError = false; TypeSymbol type = null; BoundExpression boundFilter = null; var declaration = node.Declaration; if (declaration != null) { // Note: The type is being bound twice: here and in LocalSymbol.Type. Currently, // LocalSymbol.Type ignores diagnostics so it seems cleaner to bind the type here // as well. However, if LocalSymbol.Type is changed to report diagnostics, we'll // need to avoid binding here since that will result in duplicate diagnostics. type = this.BindType(declaration.Type, diagnostics).Type; Debug.Assert((object)type != null); if (type.IsErrorType()) { hasError = true; } else { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); TypeSymbol effectiveType = type.EffectiveType(ref useSiteInfo); if (!Compilation.IsExceptionType(effectiveType, ref useSiteInfo)) { // "The type caught or thrown must be derived from System.Exception" Error(diagnostics, ErrorCode.ERR_BadExceptionType, declaration.Type); hasError = true; diagnostics.Add(declaration.Type, useSiteInfo); } else { diagnostics.AddDependencies(useSiteInfo); } } } var filter = node.Filter; if (filter != null) { var filterBinder = this.GetBinder(filter); boundFilter = filterBinder.BindCatchFilter(filter, diagnostics); hasError |= boundFilter.HasAnyErrors; } if (!hasError) { // TODO: Loop is O(n), caller is O(n^2). Perhaps we could iterate in reverse order (since it's easier to find // base types than to find derived types). Debug.Assert(((object)type == null) || !type.IsErrorType()); foreach (var previousBlock in previousBlocks) { var previousType = previousBlock.ExceptionTypeOpt; // If the previous type is a generic parameter we don't know what exception types it's gonna catch exactly. // If it is a class-type we know it's gonna catch all exception types of its type and types that are derived from it. // So if the current type is a class-type (or an effective base type of a generic parameter) // that derives from the previous type the current catch is unreachable. if (previousBlock.ExceptionFilterOpt == null && (object)previousType != null && !previousType.IsErrorType()) { if ((object)type != null) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (Conversions.HasIdentityOrImplicitReferenceConversion(type, previousType, ref useSiteInfo)) { // "A previous catch clause already catches all exceptions of this or of a super type ('{0}')" Error(diagnostics, ErrorCode.ERR_UnreachableCatch, declaration.Type, previousType); diagnostics.Add(declaration.Type, useSiteInfo); hasError = true; break; } diagnostics.Add(declaration.Type, useSiteInfo); } else if (TypeSymbol.Equals(previousType, Compilation.GetWellKnownType(WellKnownType.System_Exception), TypeCompareKind.ConsiderEverything2) && Compilation.SourceAssembly.RuntimeCompatibilityWrapNonExceptionThrows) { // If the RuntimeCompatibility(WrapNonExceptionThrows = false) is applied on the source assembly or any referenced netmodule. // an empty catch may catch exceptions that don't derive from System.Exception. // "A previous catch clause already catches all exceptions..." Error(diagnostics, ErrorCode.WRN_UnreachableGeneralCatch, node.CatchKeyword); break; } } } } var binder = GetBinder(node); Debug.Assert(binder != null); ImmutableArray<LocalSymbol> locals = binder.GetDeclaredLocalsForScope(node); BoundExpression exceptionSource = null; LocalSymbol local = locals.FirstOrDefault(); if (local?.DeclarationKind == LocalDeclarationKind.CatchVariable) { Debug.Assert(local.Type.IsErrorType() || (TypeSymbol.Equals(local.Type, type, TypeCompareKind.ConsiderEverything2))); // Check for local variable conflicts in the *enclosing* binder, not the *current* binder; // obviously we will find a local of the given name in the current binder. hasError |= this.ValidateDeclarationNameConflictsInScope(local, diagnostics); exceptionSource = new BoundLocal(declaration, local, ConstantValue.NotAvailable, local.Type); } var block = BindEmbeddedBlock(node.Block, diagnostics); return new BoundCatchBlock(node, locals, exceptionSource, type, exceptionFilterPrologueOpt: null, boundFilter, block, hasError); } private BoundExpression BindCatchFilter(CatchFilterClauseSyntax filter, BindingDiagnosticBag diagnostics) { BoundExpression boundFilter = this.BindBooleanExpression(filter.FilterExpression, diagnostics); if (boundFilter.ConstantValue != ConstantValue.NotAvailable) { // Depending on whether the filter constant is true or false, and whether there are other catch clauses, // we suggest different actions var errorCode = boundFilter.ConstantValue.BooleanValue ? ErrorCode.WRN_FilterIsConstantTrue : (filter.Parent.Parent is TryStatementSyntax s && s.Catches.Count == 1 && s.Finally == null) ? ErrorCode.WRN_FilterIsConstantFalseRedundantTryCatch : ErrorCode.WRN_FilterIsConstantFalse; // Since the expression is a constant, the name can be retrieved from the first token Error(diagnostics, errorCode, filter.FilterExpression); } return boundFilter; } // Report an extra error on the return if we are in a lambda conversion. private void ReportCantConvertLambdaReturn(SyntaxNode syntax, BindingDiagnosticBag diagnostics) { // Suppress this error if the lambda is a result of a query rewrite. if (syntax.Parent is QueryClauseSyntax || syntax.Parent is SelectOrGroupClauseSyntax) return; var lambda = this.ContainingMemberOrLambda as LambdaSymbol; if ((object)lambda != null) { Location location = GetLocationForDiagnostics(syntax); if (IsInAsyncMethod()) { // Cannot convert async {0} to intended delegate type. An async {0} may return void, Task or Task<T>, none of which are convertible to '{1}'. Error(diagnostics, ErrorCode.ERR_CantConvAsyncAnonFuncReturns, location, lambda.MessageID.Localize(), lambda.ReturnType); } else { // Cannot convert {0} to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type Error(diagnostics, ErrorCode.ERR_CantConvAnonMethReturns, location, lambda.MessageID.Localize()); } } } private static Location GetLocationForDiagnostics(SyntaxNode node) { switch (node) { case LambdaExpressionSyntax lambdaSyntax: return Location.Create(lambdaSyntax.SyntaxTree, Text.TextSpan.FromBounds(lambdaSyntax.SpanStart, lambdaSyntax.ArrowToken.Span.End)); case AnonymousMethodExpressionSyntax anonymousMethodSyntax: return Location.Create(anonymousMethodSyntax.SyntaxTree, Text.TextSpan.FromBounds(anonymousMethodSyntax.SpanStart, anonymousMethodSyntax.ParameterList?.Span.End ?? anonymousMethodSyntax.DelegateKeyword.Span.End)); } return node.Location; } private static bool IsValidStatementExpression(SyntaxNode syntax, BoundExpression expression) { bool syntacticallyValid = SyntaxFacts.IsStatementExpression(syntax); if (!syntacticallyValid) { return false; } if (expression.IsSuppressed) { return false; } // It is possible that an expression is syntactically valid but semantic analysis // reveals it to be illegal in a statement expression: "new MyDelegate(M)" for example // is not legal because it is a delegate-creation-expression and not an // object-creation-expression, but of course we don't know that syntactically. if (expression.Kind == BoundKind.DelegateCreationExpression || expression.Kind == BoundKind.NameOfOperator) { return false; } return true; } /// <summary> /// Wrap a given expression e into a block as either { e; } or { return e; } /// Shared between lambda and expression-bodied method binding. /// </summary> internal BoundBlock CreateBlockFromExpression(CSharpSyntaxNode node, ImmutableArray<LocalSymbol> locals, RefKind refKind, BoundExpression expression, ExpressionSyntax expressionSyntax, BindingDiagnosticBag diagnostics) { RefKind returnRefKind; var returnType = GetCurrentReturnType(out returnRefKind); var syntax = expressionSyntax ?? expression.Syntax; BoundStatement statement; if (IsInAsyncMethod() && refKind != RefKind.None) { // This can happen if we are binding an async anonymous method to a delegate type. Error(diagnostics, ErrorCode.ERR_MustNotHaveRefReturn, syntax); expression = BindToTypeForErrorRecovery(expression); statement = new BoundReturnStatement(syntax, refKind, expression) { WasCompilerGenerated = true }; } else if ((object)returnType != null) { if ((refKind != RefKind.None) != (returnRefKind != RefKind.None) && expression.Kind != BoundKind.ThrowExpression) { var errorCode = refKind != RefKind.None ? ErrorCode.ERR_MustNotHaveRefReturn : ErrorCode.ERR_MustHaveRefReturn; Error(diagnostics, errorCode, syntax); expression = BindToTypeForErrorRecovery(expression); statement = new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; } else if (returnType.IsVoidType() || IsEffectivelyTaskReturningAsyncMethod()) { // If the return type is void then the expression is required to be a legal // statement expression. Debug.Assert(expressionSyntax != null || !IsValidExpressionBody(expressionSyntax, expression)); bool errors = false; if (expressionSyntax == null || !IsValidExpressionBody(expressionSyntax, expression)) { expression = BindToTypeForErrorRecovery(expression); Error(diagnostics, ErrorCode.ERR_IllegalStatement, syntax); errors = true; } else { expression = BindToNaturalType(expression, diagnostics); } // Don't mark compiler generated so that the rewriter generates sequence points var expressionStatement = new BoundExpressionStatement(syntax, expression, errors); CheckForUnobservedAwaitable(expression, diagnostics); statement = expressionStatement; } else if (IsIAsyncEnumerableOrIAsyncEnumeratorReturningAsyncMethod()) { Error(diagnostics, ErrorCode.ERR_ReturnInIterator, syntax); expression = BindToTypeForErrorRecovery(expression); statement = new BoundReturnStatement(syntax, returnRefKind, expression) { WasCompilerGenerated = true }; } else { expression = returnType.IsErrorType() ? BindToTypeForErrorRecovery(expression) : CreateReturnConversion(syntax, diagnostics, expression, refKind, returnType); statement = new BoundReturnStatement(syntax, returnRefKind, expression) { WasCompilerGenerated = true }; } } else if (expression.Type?.SpecialType == SpecialType.System_Void) { expression = BindToNaturalType(expression, diagnostics); statement = new BoundExpressionStatement(syntax, expression) { WasCompilerGenerated = true }; } else { // When binding for purpose of inferring the return type of a lambda, we do not require returned expressions (such as `default` or switch expressions) to have a natural type var inferringLambda = this.ContainingMemberOrLambda is MethodSymbol method && (object)method.ReturnType == LambdaSymbol.ReturnTypeIsBeingInferred; if (!inferringLambda) { expression = BindToNaturalType(expression, diagnostics); } statement = new BoundReturnStatement(syntax, refKind, expression) { WasCompilerGenerated = true }; } // Need to attach the tree for when we generate sequence points. return new BoundBlock(node, locals, ImmutableArray.Create(statement)) { WasCompilerGenerated = node.Kind() != SyntaxKind.ArrowExpressionClause }; } private static bool IsValidExpressionBody(SyntaxNode expressionSyntax, BoundExpression expression) { return IsValidStatementExpression(expressionSyntax, expression) || expressionSyntax.Kind() == SyntaxKind.ThrowExpression; } /// <summary> /// Binds an expression-bodied member with expression e as either { return e; } or { e; }. /// </summary> internal virtual BoundBlock BindExpressionBodyAsBlock(ArrowExpressionClauseSyntax expressionBody, BindingDiagnosticBag diagnostics) { Binder bodyBinder = this.GetBinder(expressionBody); Debug.Assert(bodyBinder != null); return bindExpressionBodyAsBlockInternal(expressionBody, bodyBinder, diagnostics); // Use static local function to prevent accidentally calling instance methods on `this` instead of `bodyBinder` static BoundBlock bindExpressionBodyAsBlockInternal(ArrowExpressionClauseSyntax expressionBody, Binder bodyBinder, BindingDiagnosticBag diagnostics) { RefKind refKind; ExpressionSyntax expressionSyntax = expressionBody.Expression.CheckAndUnwrapRefExpression(diagnostics, out refKind); BindValueKind requiredValueKind = bodyBinder.GetRequiredReturnValueKind(refKind); BoundExpression expression = bodyBinder.BindValue(expressionSyntax, diagnostics, requiredValueKind); expression = bodyBinder.ValidateEscape(expression, Binder.ExternalScope, refKind != RefKind.None, diagnostics); return bodyBinder.CreateBlockFromExpression(expressionBody, bodyBinder.GetDeclaredLocalsForScope(expressionBody), refKind, expression, expressionSyntax, diagnostics); } } /// <summary> /// Binds a lambda with expression e as either { return e; } or { e; }. /// </summary> public BoundBlock BindLambdaExpressionAsBlock(ExpressionSyntax body, BindingDiagnosticBag diagnostics) { Binder bodyBinder = this.GetBinder(body); Debug.Assert(bodyBinder != null); RefKind refKind; var expressionSyntax = body.CheckAndUnwrapRefExpression(diagnostics, out refKind); BindValueKind requiredValueKind = GetRequiredReturnValueKind(refKind); BoundExpression expression = bodyBinder.BindValue(expressionSyntax, diagnostics, requiredValueKind); expression = ValidateEscape(expression, Binder.ExternalScope, refKind != RefKind.None, diagnostics); return bodyBinder.CreateBlockFromExpression(body, bodyBinder.GetDeclaredLocalsForScope(body), refKind, expression, expressionSyntax, diagnostics); } public BoundBlock CreateBlockFromExpression(ExpressionSyntax body, BoundExpression expression, BindingDiagnosticBag diagnostics) { Binder bodyBinder = this.GetBinder(body); Debug.Assert(bodyBinder != null); Debug.Assert(body.Kind() != SyntaxKind.RefExpression); return bodyBinder.CreateBlockFromExpression(body, bodyBinder.GetDeclaredLocalsForScope(body), RefKind.None, expression, body, diagnostics); } private BindValueKind GetRequiredReturnValueKind(RefKind refKind) { BindValueKind requiredValueKind = BindValueKind.RValue; if (refKind != RefKind.None) { GetCurrentReturnType(out var sigRefKind); requiredValueKind = sigRefKind == RefKind.Ref ? BindValueKind.RefReturn : BindValueKind.ReadonlyRef; } return requiredValueKind; } public virtual BoundNode BindMethodBody(CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics, bool includesFieldInitializers = false) { switch (syntax) { case RecordDeclarationSyntax recordDecl: return BindRecordConstructorBody(recordDecl, diagnostics); case BaseMethodDeclarationSyntax method: if (method.Kind() == SyntaxKind.ConstructorDeclaration) { return BindConstructorBody((ConstructorDeclarationSyntax)method, diagnostics, includesFieldInitializers); } return BindMethodBody(method, method.Body, method.ExpressionBody, diagnostics); case AccessorDeclarationSyntax accessor: return BindMethodBody(accessor, accessor.Body, accessor.ExpressionBody, diagnostics); case ArrowExpressionClauseSyntax arrowExpression: return BindExpressionBodyAsBlock(arrowExpression, diagnostics); case CompilationUnitSyntax compilationUnit: return BindSimpleProgram(compilationUnit, diagnostics); default: throw ExceptionUtilities.UnexpectedValue(syntax.Kind()); } } private BoundNode BindSimpleProgram(CompilationUnitSyntax compilationUnit, BindingDiagnosticBag diagnostics) { var simpleProgram = (SynthesizedSimpleProgramEntryPointSymbol)ContainingMemberOrLambda; return GetBinder(compilationUnit).BindSimpleProgramCompilationUnit(compilationUnit, simpleProgram, diagnostics); } private BoundNode BindSimpleProgramCompilationUnit(CompilationUnitSyntax compilationUnit, SynthesizedSimpleProgramEntryPointSymbol simpleProgram, BindingDiagnosticBag diagnostics) { ArrayBuilder<BoundStatement> boundStatements = ArrayBuilder<BoundStatement>.GetInstance(); foreach (var statement in compilationUnit.Members) { if (statement is GlobalStatementSyntax topLevelStatement) { var boundStatement = BindStatement(topLevelStatement.Statement, diagnostics); boundStatements.Add(boundStatement); } } return new BoundNonConstructorMethodBody(compilationUnit, FinishBindBlockParts(compilationUnit, boundStatements.ToImmutableAndFree(), diagnostics).MakeCompilerGenerated(), expressionBody: null); } private BoundNode BindRecordConstructorBody(RecordDeclarationSyntax recordDecl, BindingDiagnosticBag diagnostics) { Debug.Assert(recordDecl.ParameterList is object); Debug.Assert(recordDecl.IsKind(SyntaxKind.RecordDeclaration)); Binder bodyBinder = this.GetBinder(recordDecl); Debug.Assert(bodyBinder != null); BoundExpressionStatement initializer = null; if (recordDecl.PrimaryConstructorBaseTypeIfClass is PrimaryConstructorBaseTypeSyntax baseWithArguments) { initializer = bodyBinder.BindConstructorInitializer(baseWithArguments, diagnostics); } return new BoundConstructorMethodBody(recordDecl, bodyBinder.GetDeclaredLocalsForScope(recordDecl), initializer, blockBody: new BoundBlock(recordDecl, ImmutableArray<LocalSymbol>.Empty, ImmutableArray<BoundStatement>.Empty).MakeCompilerGenerated(), expressionBody: null); } internal virtual BoundExpressionStatement BindConstructorInitializer(PrimaryConstructorBaseTypeSyntax initializer, BindingDiagnosticBag diagnostics) { BoundExpression initializerInvocation = GetBinder(initializer).BindConstructorInitializer(initializer.ArgumentList, (MethodSymbol)this.ContainingMember(), diagnostics); var constructorInitializer = new BoundExpressionStatement(initializer, initializerInvocation); Debug.Assert(initializerInvocation.HasAnyErrors || constructorInitializer.IsConstructorInitializer(), "Please keep this bound node in sync with BoundNodeExtensions.IsConstructorInitializer."); return constructorInitializer; } private BoundNode BindConstructorBody(ConstructorDeclarationSyntax constructor, BindingDiagnosticBag diagnostics, bool includesFieldInitializers) { ConstructorInitializerSyntax initializer = constructor.Initializer; if (initializer == null && constructor.Body == null && constructor.ExpressionBody == null) { return null; } Binder bodyBinder = this.GetBinder(constructor); Debug.Assert(bodyBinder != null); bool thisInitializer = initializer?.IsKind(SyntaxKind.ThisConstructorInitializer) == true; if (!thisInitializer && ContainingType.GetMembersUnordered().OfType<SynthesizedRecordConstructor>().Any()) { var constructorSymbol = (MethodSymbol)this.ContainingMember(); if (!constructorSymbol.IsStatic && !SynthesizedRecordCopyCtor.IsCopyConstructor(constructorSymbol)) { // Note: we check the constructor initializer of copy constructors elsewhere Error(diagnostics, ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, initializer?.ThisOrBaseKeyword ?? constructor.Identifier); } } // The `: this()` initializer is ignored when it is a default value type constructor // and we need to include field initializers into the constructor. bool skipInitializer = includesFieldInitializers && thisInitializer && ContainingType.IsDefaultValueTypeConstructor(initializer); // Using BindStatement to bind block to make sure we are reusing results of partial binding in SemanticModel return new BoundConstructorMethodBody(constructor, bodyBinder.GetDeclaredLocalsForScope(constructor), skipInitializer ? new BoundNoOpStatement(constructor, NoOpStatementFlavor.Default) : initializer == null ? null : bodyBinder.BindConstructorInitializer(initializer, diagnostics), constructor.Body == null ? null : (BoundBlock)bodyBinder.BindStatement(constructor.Body, diagnostics), constructor.ExpressionBody == null ? null : bodyBinder.BindExpressionBodyAsBlock(constructor.ExpressionBody, constructor.Body == null ? diagnostics : BindingDiagnosticBag.Discarded)); } internal virtual BoundExpressionStatement BindConstructorInitializer(ConstructorInitializerSyntax initializer, BindingDiagnosticBag diagnostics) { BoundExpression initializerInvocation = GetBinder(initializer).BindConstructorInitializer(initializer.ArgumentList, (MethodSymbol)this.ContainingMember(), diagnostics); // Base WasCompilerGenerated state off of whether constructor is implicitly declared, this will ensure proper instrumentation. Debug.Assert(!this.ContainingMember().IsImplicitlyDeclared); var constructorInitializer = new BoundExpressionStatement(initializer, initializerInvocation); Debug.Assert(initializerInvocation.HasAnyErrors || constructorInitializer.IsConstructorInitializer(), "Please keep this bound node in sync with BoundNodeExtensions.IsConstructorInitializer."); return constructorInitializer; } private BoundNode BindMethodBody(CSharpSyntaxNode declaration, BlockSyntax blockBody, ArrowExpressionClauseSyntax expressionBody, BindingDiagnosticBag diagnostics) { if (blockBody == null && expressionBody == null) { return null; } // Using BindStatement to bind block to make sure we are reusing results of partial binding in SemanticModel return new BoundNonConstructorMethodBody(declaration, blockBody == null ? null : (BoundBlock)BindStatement(blockBody, diagnostics), expressionBody == null ? null : BindExpressionBodyAsBlock(expressionBody, blockBody == null ? diagnostics : BindingDiagnosticBag.Discarded)); } internal virtual ImmutableArray<LocalSymbol> Locals { get { return ImmutableArray<LocalSymbol>.Empty; } } internal virtual ImmutableArray<LocalFunctionSymbol> LocalFunctions { get { return ImmutableArray<LocalFunctionSymbol>.Empty; } } internal virtual ImmutableArray<LabelSymbol> Labels { get { return ImmutableArray<LabelSymbol>.Empty; } } /// <summary> /// If this binder owns the scope that can declare extern aliases, a set of declared aliases should be returned (even if empty). /// Otherwise, a default instance should be returned. /// </summary> internal virtual ImmutableArray<AliasAndExternAliasDirective> ExternAliases { get { return default; } } /// <summary> /// If this binder owns the scope that can declare using aliases, a set of declared aliases should be returned (even if empty). /// Otherwise, a default instance should be returned. /// Note, only aliases syntactically declared within the enclosing declaration are included. For example, global aliases /// declared in a different compilation units are not included. /// </summary> internal virtual ImmutableArray<AliasAndUsingDirective> UsingAliases { get { return default; } } /// <summary> /// Perform a lookup for the specified method on the specified expression by attempting to invoke it /// </summary> /// <param name="receiver">The expression to perform pattern lookup on</param> /// <param name="methodName">Method to search for.</param> /// <param name="syntaxNode">The expression for which lookup is being performed</param> /// <param name="diagnostics">Populated with binding diagnostics.</param> /// <param name="result">The method symbol that was looked up, or null</param> /// <returns>A <see cref="PatternLookupResult"/> value with the outcome of the lookup</returns> internal PatternLookupResult PerformPatternMethodLookup(BoundExpression receiver, string methodName, SyntaxNode syntaxNode, BindingDiagnosticBag diagnostics, out MethodSymbol result) { var bindingDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); try { result = null; var boundAccess = BindInstanceMemberAccess( syntaxNode, syntaxNode, receiver, methodName, rightArity: 0, typeArgumentsSyntax: default, typeArgumentsWithAnnotations: default, invoked: true, indexed: false, bindingDiagnostics); if (boundAccess.Kind != BoundKind.MethodGroup) { // the thing is not a method return PatternLookupResult.NotAMethod; } // NOTE: Because we're calling this method with no arguments and we // explicitly ignore default values for params parameters // (see ParameterSymbol.IsOptional) we know that no ParameterArray // containing method can be invoked in normal form which allows // us to skip some work during the lookup. var analyzedArguments = AnalyzedArguments.GetInstance(); var patternMethodCall = BindMethodGroupInvocation( syntaxNode, syntaxNode, methodName, (BoundMethodGroup)boundAccess, analyzedArguments, bindingDiagnostics, queryClause: null, allowUnexpandedForm: false, anyApplicableCandidates: out _); analyzedArguments.Free(); if (patternMethodCall.Kind != BoundKind.Call) { return PatternLookupResult.NotCallable; } var call = (BoundCall)patternMethodCall; if (call.ResultKind == LookupResultKind.Empty) { return PatternLookupResult.NoResults; } // we have succeeded or almost succeeded to bind the method // report additional binding diagnostics that we have seen so far diagnostics.AddRange(bindingDiagnostics); var patternMethodSymbol = call.Method; if (patternMethodSymbol is ErrorMethodSymbol || patternMethodCall.HasAnyErrors) { return PatternLookupResult.ResultHasErrors; } // Success! result = patternMethodSymbol; return PatternLookupResult.Success; } finally { bindingDiagnostics.Free(); } } } }
1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Portable/Binder/Semantics/Conversions/ConversionsBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal abstract partial class ConversionsBase { private const int MaximumRecursionDepth = 50; protected readonly AssemblySymbol corLibrary; protected readonly int currentRecursionDepth; internal readonly bool IncludeNullability; /// <summary> /// An optional clone of this instance with distinct IncludeNullability. /// Used to avoid unnecessary allocations when calling WithNullability() repeatedly. /// </summary> private ConversionsBase _lazyOtherNullability; protected ConversionsBase(AssemblySymbol corLibrary, int currentRecursionDepth, bool includeNullability, ConversionsBase otherNullabilityOpt) { Debug.Assert((object)corLibrary != null); Debug.Assert(otherNullabilityOpt == null || includeNullability != otherNullabilityOpt.IncludeNullability); Debug.Assert(otherNullabilityOpt == null || currentRecursionDepth == otherNullabilityOpt.currentRecursionDepth); this.corLibrary = corLibrary; this.currentRecursionDepth = currentRecursionDepth; IncludeNullability = includeNullability; _lazyOtherNullability = otherNullabilityOpt; } /// <summary> /// Returns this instance if includeNullability is correct, and returns a /// cached clone of this instance with distinct IncludeNullability otherwise. /// </summary> internal ConversionsBase WithNullability(bool includeNullability) { if (IncludeNullability == includeNullability) { return this; } if (_lazyOtherNullability == null) { Interlocked.CompareExchange(ref _lazyOtherNullability, WithNullabilityCore(includeNullability), null); } Debug.Assert(_lazyOtherNullability.IncludeNullability == includeNullability); Debug.Assert(_lazyOtherNullability._lazyOtherNullability == this); return _lazyOtherNullability; } protected abstract ConversionsBase WithNullabilityCore(bool includeNullability); public abstract Conversion GetMethodGroupDelegateConversion(BoundMethodGroup source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); public abstract Conversion GetMethodGroupFunctionPointerConversion(BoundMethodGroup source, FunctionPointerTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); public abstract Conversion GetStackAllocConversion(BoundStackAllocArrayCreation sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); protected abstract ConversionsBase CreateInstance(int currentRecursionDepth); protected abstract Conversion GetInterpolatedStringConversion(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); internal AssemblySymbol CorLibrary { get { return corLibrary; } } /// <summary> /// Determines if the source expression is convertible to the destination type via /// any built-in or user-defined implicit conversion. /// </summary> public Conversion ClassifyImplicitConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null); Debug.Assert((object)destination != null); var sourceType = sourceExpression.Type; //PERF: identity conversion is by far the most common implicit conversion, check for that first if ((object)sourceType != null && HasIdentityConversionInternal(sourceType, destination)) { return Conversion.Identity; } Conversion conversion = ClassifyImplicitBuiltInConversionFromExpression(sourceExpression, sourceType, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } if ((object)sourceType != null) { // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(sourceType, destination); if (fastConversion.Exists) { if (fastConversion.IsImplicit) { return fastConversion; } } else { conversion = ClassifyImplicitBuiltInConversionSlow(sourceType, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } } } conversion = GetImplicitUserDefinedConversion(sourceExpression, sourceType, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } // The switch expression conversion is "lowest priority", so that if there is a conversion from the expression's // type it will be preferred over the switch expression conversion. Technically, we would want the language // specification to say that the switch expression conversion only "exists" if there is no implicit conversion // from the type, and we accomplish that by making it lowest priority. The same is true for the conditional // expression conversion. conversion = GetSwitchExpressionConversion(sourceExpression, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } return GetConditionalExpressionConversion(sourceExpression, destination, ref useSiteInfo); } /// <summary> /// Determines if the source type is convertible to the destination type via /// any built-in or user-defined implicit conversion. /// </summary> public Conversion ClassifyImplicitConversionFromType(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); //PERF: identity conversions are very common, check for that first. if (HasIdentityConversionInternal(source, destination)) { return Conversion.Identity; } // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion.IsImplicit ? fastConversion : Conversion.NoConversion; } else { Conversion conversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } } return GetImplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); } /// <summary> /// Determines if the source expression of given type is convertible to the destination type via /// any built-in or user-defined conversion. /// /// This helper is used in rare cases involving synthesized expressions where we know the type of an expression, but do not have the actual expression. /// The reason for this helper (as opposed to ClassifyConversionFromType) is that conversions from expressions could be different /// from conversions from type. For example expressions of dynamic type are implicitly convertable to any type, while dynamic type itself is not. /// </summary> public Conversion ClassifyConversionFromExpressionType(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // since we are converting from expression, we may have implicit dynamic conversion if (HasImplicitDynamicConversionFromExpression(source, destination)) { return Conversion.ImplicitDynamic; } return ClassifyConversionFromType(source, destination, ref useSiteInfo); } private static bool TryGetVoidConversion(TypeSymbol source, TypeSymbol destination, out Conversion conversion) { var sourceIsVoid = source?.SpecialType == SpecialType.System_Void; var destIsVoid = destination.SpecialType == SpecialType.System_Void; // 'void' is not supposed to be able to convert to or from anything, but in practice, // a lot of code depends on checking whether an expression of type 'void' is convertible to 'void'. // (e.g. for an expression lambda which returns void). // Therefore we allow an identity conversion between 'void' and 'void'. if (sourceIsVoid && destIsVoid) { conversion = Conversion.Identity; return true; } // If exactly one of source or destination is of type 'void' then no conversion may exist. if (sourceIsVoid || destIsVoid) { conversion = Conversion.NoConversion; return true; } conversion = default; return false; } /// <summary> /// Determines if the source expression is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source expression to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the implicit conversion or explicit depending on "forCast" /// </remarks> public Conversion ClassifyConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast = false) { Debug.Assert(sourceExpression != null); Debug.Assert((object)destination != null); if (TryGetVoidConversion(sourceExpression.Type, destination, out var conversion)) { return conversion; } if (forCast) { return ClassifyConversionFromExpressionForCast(sourceExpression, destination, ref useSiteInfo); } var result = ClassifyImplicitConversionFromExpression(sourceExpression, destination, ref useSiteInfo); if (result.Exists) { return result; } return ClassifyExplicitOnlyConversionFromExpression(sourceExpression, destination, ref useSiteInfo, forCast: false); } /// <summary> /// Determines if the source type is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source type to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the implicit conversion or explicit depending on "forCast" /// </remarks> public Conversion ClassifyConversionFromType(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast = false) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (TryGetVoidConversion(source, destination, out var voidConversion)) { return voidConversion; } if (forCast) { return ClassifyConversionFromTypeForCast(source, destination, ref useSiteInfo); } // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion; } else { Conversion conversion1 = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (conversion1.Exists) { return conversion1; } } Conversion conversion = GetImplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } conversion = ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteInfo, forCast: false); if (conversion.Exists) { return conversion; } return GetExplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); } /// <summary> /// Determines if the source expression is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source expression to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the built-in conversion. /// /// An implicit conversion exists from an expression of a dynamic type to any type. /// An explicit conversion exists from a dynamic type to any type. /// When casting we prefer the explicit conversion. /// </remarks> private Conversion ClassifyConversionFromExpressionForCast(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert((object)destination != null); Conversion implicitConversion = ClassifyImplicitConversionFromExpression(source, destination, ref useSiteInfo); if (implicitConversion.Exists && !ExplicitConversionMayDifferFromImplicit(implicitConversion)) { return implicitConversion; } Conversion explicitConversion = ClassifyExplicitOnlyConversionFromExpression(source, destination, ref useSiteInfo, forCast: true); if (explicitConversion.Exists) { return explicitConversion; } // It is possible for a user-defined conversion to be unambiguous when considered as // an implicit conversion and ambiguous when considered as an explicit conversion. // The native compiler does not check to see if a cast could be successfully bound as // an unambiguous user-defined implicit conversion; it goes right to the ambiguous // user-defined explicit conversion and produces an error. This means that in // C# 5 it is possible to have: // // Y y = new Y(); // Z z1 = y; // // succeed but // // Z z2 = (Z)y; // // fail. // // However, there is another interesting wrinkle. It is possible for both // an implicit user-defined conversion and an explicit user-defined conversion // to exist and be unambiguous. For example, if there is an implicit conversion // double-->C and an explicit conversion from int-->C, and the user casts a short // to C, then both the implicit and explicit conversions are applicable and // unambiguous. The native compiler in this case prefers the explicit conversion, // and for backwards compatibility, we match it. return implicitConversion; } /// <summary> /// Determines if the source type is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source type to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the built-in conversion. /// </remarks> private Conversion ClassifyConversionFromTypeForCast(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion; } Conversion implicitBuiltInConversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (implicitBuiltInConversion.Exists && !ExplicitConversionMayDifferFromImplicit(implicitBuiltInConversion)) { return implicitBuiltInConversion; } Conversion explicitBuiltInConversion = ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteInfo, forCast: true); if (explicitBuiltInConversion.Exists) { return explicitBuiltInConversion; } if (implicitBuiltInConversion.Exists) { return implicitBuiltInConversion; } // It is possible for a user-defined conversion to be unambiguous when considered as // an implicit conversion and ambiguous when considered as an explicit conversion. // The native compiler does not check to see if a cast could be successfully bound as // an unambiguous user-defined implicit conversion; it goes right to the ambiguous // user-defined explicit conversion and produces an error. This means that in // C# 5 it is possible to have: // // Y y = new Y(); // Z z1 = y; // // succeed but // // Z z2 = (Z)y; // // fail. var conversion = GetExplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } return GetImplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); } /// <summary> /// Attempt a quick classification of builtin conversions. As result of "no conversion" /// means that there is no built-in conversion, though there still may be a user-defined /// conversion if compiling against a custom mscorlib. /// </summary> public static Conversion FastClassifyConversion(TypeSymbol source, TypeSymbol target) { ConversionKind convKind = ConversionEasyOut.ClassifyConversion(source, target); if (convKind != ConversionKind.ImplicitNullable && convKind != ConversionKind.ExplicitNullable) { return Conversion.GetTrivialConversion(convKind); } return Conversion.MakeNullableConversion(convKind, FastClassifyConversion(source.StrippedType(), target.StrippedType())); } public Conversion ClassifyBuiltInConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion; } else { Conversion conversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } } return ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteInfo, forCast: false); } /// <summary> /// Determines if the source type is convertible to the destination type via /// any standard implicit or standard explicit conversion. /// </summary> /// <remarks> /// Not all built-in explicit conversions are standard explicit conversions. /// </remarks> public Conversion ClassifyStandardConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert((object)destination != null); // Note that the definition of explicit standard conversion does not include all explicit // reference conversions! There is a standard implicit reference conversion from // Action<Object> to Action<Exception>, thanks to contravariance. There is a standard // implicit reference conversion from Action<Object> to Action<String> for the same reason. // Therefore there is an explicit reference conversion from Action<Exception> to // Action<String>; a given Action<Exception> might be an Action<Object>, and hence // convertible to Action<String>. However, this is not a *standard* explicit conversion. The // standard explicit conversions are all the standard implicit conversions and their // opposites. Therefore Action<Object>-->Action<String> and Action<String>-->Action<Object> // are both standard conversions. But Action<String>-->Action<Exception> is not a standard // explicit conversion because neither it nor its opposite is a standard implicit // conversion. // // Similarly, there is no standard explicit conversion from double to decimal, because // there is no standard implicit conversion between the two types. // SPEC: The standard explicit conversions are all standard implicit conversions plus // SPEC: the subset of the explicit conversions for which an opposite standard implicit // SPEC: conversion exists. In other words, if a standard implicit conversion exists from // SPEC: a type A to a type B, then a standard explicit conversion exists from type A to // SPEC: type B and from type B to type A. Conversion conversion = ClassifyStandardImplicitConversion(sourceExpression, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } if ((object)source != null) { return DeriveStandardExplicitFromOppositeStandardImplicitConversion(source, destination, ref useSiteInfo); } return Conversion.NoConversion; } private Conversion ClassifyStandardImplicitConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert(sourceExpression == null || (object)sourceExpression.Type == (object)source); Debug.Assert((object)destination != null); // SPEC: The following implicit conversions are classified as standard implicit conversions: // SPEC: Identity conversions // SPEC: Implicit numeric conversions // SPEC: Implicit nullable conversions // SPEC: Implicit reference conversions // SPEC: Boxing conversions // SPEC: Implicit constant expression conversions // SPEC: Implicit conversions involving type parameters // // and in unsafe code: // // SPEC: From any pointer type to void* // // SPEC ERROR: // The specification does not say to take into account the conversion from // the *expression*, only its *type*. But the expression may not have a type // (because it is null, a method group, or a lambda), or the expression might // be convertible to the destination type via a constant numeric conversion. // For example, the native compiler allows "C c = 1;" to work if C is a class which // has an implicit conversion from byte to C, despite the fact that there is // obviously no standard implicit conversion from *int* to *byte*. // Similarly, if a struct S has an implicit conversion from string to S, then // "S s = null;" should be allowed. // // We extend the definition of standard implicit conversions to include // all of the implicit conversions that are allowed based on an expression, // with the exception of the switch expression conversion. Conversion conversion = ClassifyImplicitBuiltInConversionFromExpression(sourceExpression, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } if ((object)source != null) { return ClassifyStandardImplicitConversion(source, destination, ref useSiteInfo); } return Conversion.NoConversion; } private Conversion ClassifyStandardImplicitConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return Conversion.Identity; } if (HasImplicitNumericConversion(source, destination)) { return Conversion.ImplicitNumeric; } var nullableConversion = ClassifyImplicitNullableConversion(source, destination, ref useSiteInfo); if (nullableConversion.Exists) { return nullableConversion; } if (HasImplicitReferenceConversion(source, destination, ref useSiteInfo)) { return Conversion.ImplicitReference; } if (HasBoxingConversion(source, destination, ref useSiteInfo)) { return Conversion.Boxing; } if (HasImplicitPointerToVoidConversion(source, destination)) { return Conversion.PointerToVoid; } if (HasImplicitPointerConversion(source, destination, ref useSiteInfo)) { return Conversion.ImplicitPointer; } var tupleConversion = ClassifyImplicitTupleConversion(source, destination, ref useSiteInfo); if (tupleConversion.Exists) { return tupleConversion; } return Conversion.NoConversion; } private Conversion ClassifyImplicitBuiltInConversionSlow(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsVoidType() || destination.IsVoidType()) { return Conversion.NoConversion; } Conversion conversion = ClassifyStandardImplicitConversion(source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } return Conversion.NoConversion; } private Conversion GetImplicitUserDefinedConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var conversionResult = AnalyzeImplicitUserDefinedConversions(sourceExpression, source, destination, ref useSiteInfo); return new Conversion(conversionResult, isImplicit: true); } private Conversion ClassifyExplicitBuiltInOnlyConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsVoidType() || destination.IsVoidType()) { return Conversion.NoConversion; } // The call to HasExplicitNumericConversion isn't necessary, because it is always tested // already by the "FastConversion" code. Debug.Assert(!HasExplicitNumericConversion(source, destination)); //if (HasExplicitNumericConversion(source, specialTypeSource, destination, specialTypeDest)) //{ // return Conversion.ExplicitNumeric; //} if (HasSpecialIntPtrConversion(source, destination)) { return Conversion.IntPtr; } if (HasExplicitEnumerationConversion(source, destination)) { return Conversion.ExplicitEnumeration; } var nullableConversion = ClassifyExplicitNullableConversion(source, destination, ref useSiteInfo, forCast); if (nullableConversion.Exists) { return nullableConversion; } if (HasExplicitReferenceConversion(source, destination, ref useSiteInfo)) { return (source.Kind == SymbolKind.DynamicType) ? Conversion.ExplicitDynamic : Conversion.ExplicitReference; } if (HasUnboxingConversion(source, destination, ref useSiteInfo)) { return Conversion.Unboxing; } var tupleConversion = ClassifyExplicitTupleConversion(source, destination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return tupleConversion; } if (HasPointerToPointerConversion(source, destination)) { return Conversion.PointerToPointer; } if (HasPointerToIntegerConversion(source, destination)) { return Conversion.PointerToInteger; } if (HasIntegerToPointerConversion(source, destination)) { return Conversion.IntegerToPointer; } if (HasExplicitDynamicConversion(source, destination)) { return Conversion.ExplicitDynamic; } return Conversion.NoConversion; } private Conversion GetExplicitUserDefinedConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { UserDefinedConversionResult conversionResult = AnalyzeExplicitUserDefinedConversions(sourceExpression, source, destination, ref useSiteInfo); return new Conversion(conversionResult, isImplicit: false); } private Conversion DeriveStandardExplicitFromOppositeStandardImplicitConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var oppositeConversion = ClassifyStandardImplicitConversion(destination, source, ref useSiteInfo); Conversion impliedExplicitConversion; switch (oppositeConversion.Kind) { case ConversionKind.Identity: impliedExplicitConversion = Conversion.Identity; break; case ConversionKind.ImplicitNumeric: impliedExplicitConversion = Conversion.ExplicitNumeric; break; case ConversionKind.ImplicitReference: impliedExplicitConversion = Conversion.ExplicitReference; break; case ConversionKind.Boxing: impliedExplicitConversion = Conversion.Unboxing; break; case ConversionKind.NoConversion: impliedExplicitConversion = Conversion.NoConversion; break; case ConversionKind.ImplicitPointerToVoid: impliedExplicitConversion = Conversion.PointerToPointer; break; case ConversionKind.ImplicitTuple: // only implicit tuple conversions are standard conversions, // having implicit conversion in the other direction does not help here. impliedExplicitConversion = Conversion.NoConversion; break; case ConversionKind.ImplicitNullable: var strippedSource = source.StrippedType(); var strippedDestination = destination.StrippedType(); var underlyingConversion = DeriveStandardExplicitFromOppositeStandardImplicitConversion(strippedSource, strippedDestination, ref useSiteInfo); // the opposite underlying conversion may not exist // for example if underlying conversion is implicit tuple impliedExplicitConversion = underlyingConversion.Exists ? Conversion.MakeNullableConversion(ConversionKind.ExplicitNullable, underlyingConversion) : Conversion.NoConversion; break; default: throw ExceptionUtilities.UnexpectedValue(oppositeConversion.Kind); } return impliedExplicitConversion; } /// <summary> /// IsBaseInterface returns true if baseType is on the base interface list of derivedType or /// any base class of derivedType. It may be on the base interface list either directly or /// indirectly. /// * baseType must be an interface. /// * type parameters do not have base interfaces. (They have an "effective interface list".) /// * an interface is not a base of itself. /// * this does not check for variance conversions; if a type inherits from /// IEnumerable&lt;string> then IEnumerable&lt;object> is not a base interface. /// </summary> public bool IsBaseInterface(TypeSymbol baseType, TypeSymbol derivedType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)baseType != null); Debug.Assert((object)derivedType != null); if (!baseType.IsInterfaceType()) { return false; } var d = derivedType as NamedTypeSymbol; if ((object)d == null) { return false; } foreach (var iface in d.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(iface, baseType)) { return true; } } return false; } // IsBaseClass returns true if and only if baseType is a base class of derivedType, period. // // * interfaces do not have base classes. (Structs, enums and classes other than object do.) // * a class is not a base class of itself // * type parameters do not have base classes. (They have "effective base classes".) // * all base classes must be classes // * dynamics are removed; if we have class D : B<dynamic> then B<object> is a // base class of D. However, dynamic is never a base class of anything. public bool IsBaseClass(TypeSymbol derivedType, TypeSymbol baseType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)derivedType != null); Debug.Assert((object)baseType != null); // A base class has got to be a class. The derived type might be a struct, enum, or delegate. if (!baseType.IsClassType()) { return false; } for (TypeSymbol b = derivedType.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); (object)b != null; b = b.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(b, baseType)) { return true; } } return false; } /// <summary> /// returns true when implicit conversion is not necessarily the same as explicit conversion /// </summary> private static bool ExplicitConversionMayDifferFromImplicit(Conversion implicitConversion) { switch (implicitConversion.Kind) { case ConversionKind.ImplicitUserDefined: case ConversionKind.ImplicitDynamic: case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitTupleLiteral: case ConversionKind.ImplicitNullable: case ConversionKind.ConditionalExpression: return true; default: return false; } } private Conversion ClassifyImplicitBuiltInConversionFromExpression(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert(sourceExpression == null || (object)sourceExpression.Type == (object)source); Debug.Assert((object)destination != null); if (HasImplicitDynamicConversionFromExpression(source, destination)) { return Conversion.ImplicitDynamic; } // The following conversions only exist for certain form of expressions, // if we have no expression none if them is applicable. if (sourceExpression == null) { return Conversion.NoConversion; } if (HasImplicitEnumerationConversion(sourceExpression, destination)) { return Conversion.ImplicitEnumeration; } var constantConversion = ClassifyImplicitConstantExpressionConversion(sourceExpression, destination); if (constantConversion.Exists) { return constantConversion; } switch (sourceExpression.Kind) { case BoundKind.Literal: var nullLiteralConversion = ClassifyNullLiteralConversion(sourceExpression, destination); if (nullLiteralConversion.Exists) { return nullLiteralConversion; } break; case BoundKind.DefaultLiteral: return Conversion.DefaultLiteral; case BoundKind.ExpressionWithNullability: { var innerExpression = ((BoundExpressionWithNullability)sourceExpression).Expression; var innerConversion = ClassifyImplicitBuiltInConversionFromExpression(innerExpression, innerExpression.Type, destination, ref useSiteInfo); if (innerConversion.Exists) { return innerConversion; } break; } case BoundKind.TupleLiteral: var tupleConversion = ClassifyImplicitTupleLiteralConversion((BoundTupleLiteral)sourceExpression, destination, ref useSiteInfo); if (tupleConversion.Exists) { return tupleConversion; } break; case BoundKind.UnboundLambda: if (HasAnonymousFunctionConversion(sourceExpression, destination)) { return Conversion.AnonymousFunction; } break; case BoundKind.MethodGroup: Conversion methodGroupConversion = GetMethodGroupDelegateConversion((BoundMethodGroup)sourceExpression, destination, ref useSiteInfo); if (methodGroupConversion.Exists) { return methodGroupConversion; } break; case BoundKind.UnconvertedInterpolatedString: case BoundKind.BinaryOperator when ((BoundBinaryOperator)sourceExpression).IsUnconvertedInterpolatedStringAddition: Conversion interpolatedStringConversion = GetInterpolatedStringConversion(sourceExpression, destination, ref useSiteInfo); if (interpolatedStringConversion.Exists) { return interpolatedStringConversion; } break; case BoundKind.StackAllocArrayCreation: var stackAllocConversion = GetStackAllocConversion((BoundStackAllocArrayCreation)sourceExpression, destination, ref useSiteInfo); if (stackAllocConversion.Exists) { return stackAllocConversion; } break; case BoundKind.UnconvertedAddressOfOperator when destination is FunctionPointerTypeSymbol funcPtrType: var addressOfConversion = GetMethodGroupFunctionPointerConversion(((BoundUnconvertedAddressOfOperator)sourceExpression).Operand, funcPtrType, ref useSiteInfo); if (addressOfConversion.Exists) { return addressOfConversion; } break; case BoundKind.ThrowExpression: return Conversion.ImplicitThrow; case BoundKind.UnconvertedObjectCreationExpression: return Conversion.ObjectCreation; } return Conversion.NoConversion; } private Conversion GetSwitchExpressionConversion(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (source) { case BoundConvertedSwitchExpression _: // It has already been subjected to a switch expression conversion. return Conversion.NoConversion; case BoundUnconvertedSwitchExpression switchExpression: var innerConversions = ArrayBuilder<Conversion>.GetInstance(switchExpression.SwitchArms.Length); foreach (var arm in switchExpression.SwitchArms) { var nestedConversion = this.ClassifyImplicitConversionFromExpression(arm.Value, destination, ref useSiteInfo); if (!nestedConversion.Exists) { innerConversions.Free(); return Conversion.NoConversion; } innerConversions.Add(nestedConversion); } return Conversion.MakeSwitchExpression(innerConversions.ToImmutableAndFree()); default: return Conversion.NoConversion; } } private Conversion GetConditionalExpressionConversion(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!(source is BoundUnconvertedConditionalOperator conditionalOperator)) return Conversion.NoConversion; var trueConversion = this.ClassifyImplicitConversionFromExpression(conditionalOperator.Consequence, destination, ref useSiteInfo); if (!trueConversion.Exists) return Conversion.NoConversion; var falseConversion = this.ClassifyImplicitConversionFromExpression(conditionalOperator.Alternative, destination, ref useSiteInfo); if (!falseConversion.Exists) return Conversion.NoConversion; return Conversion.MakeConditionalExpression(ImmutableArray.Create(trueConversion, falseConversion)); } private static Conversion ClassifyNullLiteralConversion(BoundExpression source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!source.IsLiteralNull()) { return Conversion.NoConversion; } // SPEC: An implicit conversion exists from the null literal to any nullable type. if (destination.IsNullableType()) { // The spec defines a "null literal conversion" specifically as a conversion from // null to nullable type. return Conversion.NullLiteral; } // SPEC: An implicit conversion exists from the null literal to any reference type. // SPEC: An implicit conversion exists from the null literal to type parameter T, // SPEC: provided T is known to be a reference type. [...] The conversion [is] classified // SPEC: as implicit reference conversion. if (destination.IsReferenceType) { return Conversion.ImplicitReference; } // SPEC: The set of implicit conversions is extended to include... // SPEC: ... from the null literal to any pointer type. if (destination.IsPointerOrFunctionPointer()) { return Conversion.NullToPointer; } return Conversion.NoConversion; } private static Conversion ClassifyImplicitConstantExpressionConversion(BoundExpression source, TypeSymbol destination) { if (HasImplicitConstantExpressionConversion(source, destination)) { return Conversion.ImplicitConstant; } // strip nullable from the destination // // the following should work and it is an ImplicitNullable conversion // int? x = 1; if (destination.Kind == SymbolKind.NamedType) { var nt = (NamedTypeSymbol)destination; if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T && HasImplicitConstantExpressionConversion(source, nt.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type)) { return new Conversion(ConversionKind.ImplicitNullable, Conversion.ImplicitConstantUnderlying); } } return Conversion.NoConversion; } private Conversion ClassifyImplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var tupleConversion = GetImplicitTupleLiteralConversion(source, destination, ref useSiteInfo); if (tupleConversion.Exists) { return tupleConversion; } // strip nullable from the destination // // the following should work and it is an ImplicitNullable conversion // (int, double)? x = (1,2); if (destination.Kind == SymbolKind.NamedType) { var nt = (NamedTypeSymbol)destination; if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T) { var underlyingTupleConversion = GetImplicitTupleLiteralConversion(source, nt.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type, ref useSiteInfo); if (underlyingTupleConversion.Exists) { return new Conversion(ConversionKind.ImplicitNullable, ImmutableArray.Create(underlyingTupleConversion)); } } } return Conversion.NoConversion; } private Conversion ClassifyExplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { var tupleConversion = GetExplicitTupleLiteralConversion(source, destination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return tupleConversion; } // strip nullable from the destination // // the following should work and it is an ExplicitNullable conversion // var x = ((byte, string)?)(1,null); if (destination.Kind == SymbolKind.NamedType) { var nt = (NamedTypeSymbol)destination; if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T) { var underlyingTupleConversion = GetExplicitTupleLiteralConversion(source, nt.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type, ref useSiteInfo, forCast); if (underlyingTupleConversion.Exists) { return new Conversion(ConversionKind.ExplicitNullable, ImmutableArray.Create(underlyingTupleConversion)); } } } return Conversion.NoConversion; } internal static bool HasImplicitConstantExpressionConversion(BoundExpression source, TypeSymbol destination) { var constantValue = source.ConstantValue; if (constantValue == null || (object)source.Type == null) { return false; } // An implicit constant expression conversion permits the following conversions: // A constant-expression of type int can be converted to type sbyte, byte, short, // ushort, uint, or ulong, provided the value of the constant-expression is within the // range of the destination type. var specialSource = source.Type.GetSpecialTypeSafe(); if (specialSource == SpecialType.System_Int32) { //if the constant value could not be computed, be generous and assume the conversion will work int value = constantValue.IsBad ? 0 : constantValue.Int32Value; switch (destination.GetSpecialTypeSafe()) { case SpecialType.System_Byte: return byte.MinValue <= value && value <= byte.MaxValue; case SpecialType.System_SByte: return sbyte.MinValue <= value && value <= sbyte.MaxValue; case SpecialType.System_Int16: return short.MinValue <= value && value <= short.MaxValue; case SpecialType.System_IntPtr when destination.IsNativeIntegerType: return true; case SpecialType.System_UInt32: case SpecialType.System_UIntPtr when destination.IsNativeIntegerType: return uint.MinValue <= value; case SpecialType.System_UInt64: return (int)ulong.MinValue <= value; case SpecialType.System_UInt16: return ushort.MinValue <= value && value <= ushort.MaxValue; default: return false; } } else if (specialSource == SpecialType.System_Int64 && destination.GetSpecialTypeSafe() == SpecialType.System_UInt64 && (constantValue.IsBad || 0 <= constantValue.Int64Value)) { // A constant-expression of type long can be converted to type ulong, provided the // value of the constant-expression is not negative. return true; } return false; } private Conversion ClassifyExplicitOnlyConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { Debug.Assert(sourceExpression != null); Debug.Assert((object)destination != null); var sourceType = sourceExpression.Type; // NB: need to check for explicit tuple literal conversion before checking for explicit conversion from type // The same literal may have both explicit tuple conversion and explicit tuple literal conversion to the target type. // They are, however, observably different conversions via the order of argument evaluations and element-wise conversions if (sourceExpression.Kind == BoundKind.TupleLiteral) { Conversion tupleConversion = ClassifyExplicitTupleLiteralConversion((BoundTupleLiteral)sourceExpression, destination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return tupleConversion; } } if ((object)sourceType != null) { // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(sourceType, destination); if (fastConversion.Exists) { return fastConversion; } else { var conversion = ClassifyExplicitBuiltInOnlyConversion(sourceType, destination, ref useSiteInfo, forCast); if (conversion.Exists) { return conversion; } } } return GetExplicitUserDefinedConversion(sourceExpression, sourceType, destination, ref useSiteInfo); } #nullable enable private static bool HasImplicitEnumerationConversion(BoundExpression source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: An implicit enumeration conversion permits the decimal-integer-literal 0 to be converted to any enum-type // SPEC: and to any nullable-type whose underlying type is an enum-type. // // For historical reasons we actually allow a conversion from any *numeric constant // zero* to be converted to any enum type, not just the literal integer zero. bool validType = destination.IsEnumType() || destination.IsNullableType() && destination.GetNullableUnderlyingType().IsEnumType(); if (!validType) { return false; } var sourceConstantValue = source.ConstantValue; return sourceConstantValue != null && source.Type is object && IsNumericType(source.Type) && IsConstantNumericZero(sourceConstantValue); } private static LambdaConversionResult IsAnonymousFunctionCompatibleWithDelegate(UnboundLambda anonymousFunction, TypeSymbol type, bool isTargetExpressionTree) { Debug.Assert((object)anonymousFunction != null); Debug.Assert((object)type != null); // SPEC: An anonymous-method-expression or lambda-expression is classified as an anonymous function. // SPEC: The expression does not have a type but can be implicitly converted to a compatible delegate // SPEC: type or expression tree type. Specifically, a delegate type D is compatible with an // SPEC: anonymous function F provided: var delegateType = (NamedTypeSymbol)type; var invokeMethod = delegateType.DelegateInvokeMethod; if ((object)invokeMethod == null || invokeMethod.HasUseSiteError) { return LambdaConversionResult.BadTargetType; } if (anonymousFunction.HasExplicitReturnType(out var refKind, out var returnType)) { if (invokeMethod.RefKind != refKind || !invokeMethod.ReturnType.Equals(returnType.Type, TypeCompareKind.AllIgnoreOptions)) { return LambdaConversionResult.MismatchedReturnType; } } var delegateParameters = invokeMethod.Parameters; // SPEC: If F contains an anonymous-function-signature, then D and F have the same number of parameters. // SPEC: If F does not contain an anonymous-function-signature, then D may have zero or more parameters // SPEC: of any type, as long as no parameter of D has the out parameter modifier. if (anonymousFunction.HasSignature) { if (anonymousFunction.ParameterCount != invokeMethod.ParameterCount) { return LambdaConversionResult.BadParameterCount; } // SPEC: If F has an explicitly typed parameter list, each parameter in D has the same type // SPEC: and modifiers as the corresponding parameter in F. // SPEC: If F has an implicitly typed parameter list, D has no ref or out parameters. if (anonymousFunction.HasExplicitlyTypedParameterList) { for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].RefKind != anonymousFunction.RefKind(p) || !delegateParameters[p].Type.Equals(anonymousFunction.ParameterType(p), TypeCompareKind.AllIgnoreOptions)) { return LambdaConversionResult.MismatchedParameterType; } } } else { for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].RefKind != RefKind.None) { return LambdaConversionResult.RefInImplicitlyTypedLambda; } } // In C# it is not possible to make a delegate type // such that one of its parameter types is a static type. But static types are // in metadata just sealed abstract types; there is nothing stopping someone in // another language from creating a delegate with a static type for a parameter, // though the only argument you could pass for that parameter is null. // // In the native compiler we forbid conversion of an anonymous function that has // an implicitly-typed parameter list to a delegate type that has a static type // for a formal parameter type. However, we do *not* forbid it for an explicitly- // typed lambda (because we already require that the explicitly typed parameter not // be static) and we do not forbid it for an anonymous method with the entire // parameter list missing (because the body cannot possibly have a parameter that // is of static type, even though this means that we will be generating a hidden // method with a parameter of static type.) // // We also allow more exotic situations to work in the native compiler. For example, // though it is not possible to convert x=>{} to Action<GC>, it is possible to convert // it to Action<List<GC>> should there be a language that allows you to construct // a variable of that type. // // We might consider beefing up this rule to disallow a conversion of *any* anonymous // function to *any* delegate that has a static type *anywhere* in the parameter list. for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].TypeWithAnnotations.IsStatic) { return LambdaConversionResult.StaticTypeInImplicitlyTypedLambda; } } } } else { for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].RefKind == RefKind.Out) { return LambdaConversionResult.MissingSignatureWithOutParameter; } } } // Ensure the body can be converted to that delegate type var bound = anonymousFunction.Bind(delegateType, isTargetExpressionTree); if (ErrorFacts.PreventsSuccessfulDelegateConversion(bound.Diagnostics.Diagnostics)) { return LambdaConversionResult.BindingFailed; } return LambdaConversionResult.Success; } private static LambdaConversionResult IsAnonymousFunctionCompatibleWithExpressionTree(UnboundLambda anonymousFunction, NamedTypeSymbol type) { Debug.Assert((object)anonymousFunction != null); Debug.Assert((object)type != null); Debug.Assert(type.IsGenericOrNonGenericExpressionType(out _)); // SPEC OMISSION: // // The C# 3 spec said that anonymous methods and statement lambdas are *convertible* to expression tree // types if the anonymous method/statement lambda is convertible to its delegate type; however, actually // *using* such a conversion is an error. However, that is not what we implemented. In C# 3 we implemented // that an anonymous method is *not convertible* to an expression tree type, period. (Statement lambdas // used the rule described in the spec.) // // This appears to be a spec omission; the intention is to make old-style anonymous methods not // convertible to expression trees. var delegateType = type.Arity == 0 ? null : type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type; if (delegateType is { } && !delegateType.IsDelegateType()) { return LambdaConversionResult.ExpressionTreeMustHaveDelegateTypeArgument; } if (anonymousFunction.Syntax.Kind() == SyntaxKind.AnonymousMethodExpression) { return LambdaConversionResult.ExpressionTreeFromAnonymousMethod; } if (delegateType is null) { return LambdaConversionResult.Success; } return IsAnonymousFunctionCompatibleWithDelegate(anonymousFunction, delegateType, isTargetExpressionTree: true); } public static LambdaConversionResult IsAnonymousFunctionCompatibleWithType(UnboundLambda anonymousFunction, TypeSymbol type) { Debug.Assert((object)anonymousFunction != null); Debug.Assert((object)type != null); if (type.SpecialType == SpecialType.System_Delegate) { if (IsFeatureInferredDelegateTypeEnabled(anonymousFunction)) { return LambdaConversionResult.Success; } } else if (type.IsDelegateType()) { return IsAnonymousFunctionCompatibleWithDelegate(anonymousFunction, type, isTargetExpressionTree: false); } else if (type.IsGenericOrNonGenericExpressionType(out bool isGenericType)) { if (isGenericType || IsFeatureInferredDelegateTypeEnabled(anonymousFunction)) { return IsAnonymousFunctionCompatibleWithExpressionTree(anonymousFunction, (NamedTypeSymbol)type); } } return LambdaConversionResult.BadTargetType; } internal static bool IsFeatureInferredDelegateTypeEnabled(BoundExpression expr) { return expr.Syntax.IsFeatureEnabled(MessageID.IDS_FeatureInferredDelegateType); } private static bool HasAnonymousFunctionConversion(BoundExpression source, TypeSymbol destination) { Debug.Assert(source != null); Debug.Assert((object)destination != null); if (source.Kind != BoundKind.UnboundLambda) { return false; } return IsAnonymousFunctionCompatibleWithType((UnboundLambda)source, destination) == LambdaConversionResult.Success; } #nullable disable internal Conversion ClassifyImplicitUserDefinedConversionForV6SwitchGoverningType(TypeSymbol sourceType, out TypeSymbol switchGoverningType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The governing type of a switch statement is established by the switch expression. // SPEC: 1) If the type of the switch expression is sbyte, byte, short, ushort, int, uint, // SPEC: long, ulong, bool, char, string, or an enum-type, or if it is the nullable type // SPEC: corresponding to one of these types, then that is the governing type of the switch statement. // SPEC: 2) Otherwise, exactly one user-defined implicit conversion (§6.4) must exist from the // SPEC: type of the switch expression to one of the following possible governing types: // SPEC: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type // SPEC: corresponding to one of those types // NOTE: We should be called only if (1) is false for source type. Debug.Assert((object)sourceType != null); Debug.Assert(!sourceType.IsValidV6SwitchGoverningType()); UserDefinedConversionResult result = AnalyzeImplicitUserDefinedConversionForV6SwitchGoverningType(sourceType, ref useSiteInfo); if (result.Kind == UserDefinedConversionResultKind.Valid) { UserDefinedConversionAnalysis analysis = result.Results[result.Best]; switchGoverningType = analysis.ToType; Debug.Assert(switchGoverningType.IsValidV6SwitchGoverningType(isTargetTypeOfUserDefinedOp: true)); } else { switchGoverningType = null; } return new Conversion(result, isImplicit: true); } internal Conversion GetCallerLineNumberConversion(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var greenNode = new Syntax.InternalSyntax.LiteralExpressionSyntax(SyntaxKind.NumericLiteralExpression, new Syntax.InternalSyntax.SyntaxToken(SyntaxKind.NumericLiteralToken)); var syntaxNode = new LiteralExpressionSyntax(greenNode, null, 0); TypeSymbol expectedAttributeType = corLibrary.GetSpecialType(SpecialType.System_Int32); BoundLiteral intMaxValueLiteral = new BoundLiteral(syntaxNode, ConstantValue.Create(int.MaxValue), expectedAttributeType); return ClassifyStandardImplicitConversion(intMaxValueLiteral, expectedAttributeType, destination, ref useSiteInfo); } internal bool HasCallerLineNumberConversion(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return GetCallerLineNumberConversion(destination, ref useSiteInfo).Exists; } internal bool HasCallerInfoStringConversion(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { TypeSymbol expectedAttributeType = corLibrary.GetSpecialType(SpecialType.System_String); Conversion conversion = ClassifyStandardImplicitConversion(expectedAttributeType, destination, ref useSiteInfo); return conversion.Exists; } public static bool HasIdentityConversion(TypeSymbol type1, TypeSymbol type2) { return HasIdentityConversionInternal(type1, type2, includeNullability: false); } private static bool HasIdentityConversionInternal(TypeSymbol type1, TypeSymbol type2, bool includeNullability) { // Spec (6.1.1): // An identity conversion converts from any type to the same type. This conversion exists // such that an entity that already has a required type can be said to be convertible to // that type. // // Because object and dynamic are considered equivalent there is an identity conversion // between object and dynamic, and between constructed types that are the same when replacing // all occurrences of dynamic with object. Debug.Assert((object)type1 != null); Debug.Assert((object)type2 != null); // Note, when we are paying attention to nullability, we ignore oblivious mismatch. // See TypeCompareKind.ObliviousNullableModifierMatchesAny var compareKind = includeNullability ? TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes : TypeCompareKind.AllIgnoreOptions; return type1.Equals(type2, compareKind); } private bool HasIdentityConversionInternal(TypeSymbol type1, TypeSymbol type2) { return HasIdentityConversionInternal(type1, type2, IncludeNullability); } /// <summary> /// Returns true if: /// - Either type has no nullability information (oblivious). /// - Both types cannot have different nullability at the same time, /// including the case of type parameters that by themselves can represent nullable and not nullable reference types. /// </summary> internal bool HasTopLevelNullabilityIdentityConversion(TypeWithAnnotations source, TypeWithAnnotations destination) { if (!IncludeNullability) { return true; } if (source.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsOblivious()) { return true; } var sourceIsPossiblyNullableTypeParameter = IsPossiblyNullableTypeTypeParameter(source); var destinationIsPossiblyNullableTypeParameter = IsPossiblyNullableTypeTypeParameter(destination); if (sourceIsPossiblyNullableTypeParameter && !destinationIsPossiblyNullableTypeParameter) { return destination.NullableAnnotation.IsAnnotated(); } if (destinationIsPossiblyNullableTypeParameter && !sourceIsPossiblyNullableTypeParameter) { return source.NullableAnnotation.IsAnnotated(); } return source.NullableAnnotation.IsAnnotated() == destination.NullableAnnotation.IsAnnotated(); } /// <summary> /// Returns false if source type can be nullable at the same time when destination type can be not nullable, /// including the case of type parameters that by themselves can represent nullable and not nullable reference types. /// When either type has no nullability information (oblivious), this method returns true. /// </summary> internal bool HasTopLevelNullabilityImplicitConversion(TypeWithAnnotations source, TypeWithAnnotations destination) { if (!IncludeNullability) { return true; } if (source.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsAnnotated()) { return true; } if (IsPossiblyNullableTypeTypeParameter(source) && !IsPossiblyNullableTypeTypeParameter(destination)) { return false; } return !source.NullableAnnotation.IsAnnotated(); } private static bool IsPossiblyNullableTypeTypeParameter(in TypeWithAnnotations typeWithAnnotations) { var type = typeWithAnnotations.Type; return type is object && (type.IsPossiblyNullableReferenceTypeTypeParameter() || type.IsNullableTypeOrTypeParameter()); } /// <summary> /// Returns false if the source does not have an implicit conversion to the destination /// because of either incompatible top level or nested nullability. /// </summary> public bool HasAnyNullabilityImplicitConversion(TypeWithAnnotations source, TypeWithAnnotations destination) { Debug.Assert(IncludeNullability); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return HasTopLevelNullabilityImplicitConversion(source, destination) && ClassifyImplicitConversionFromType(source.Type, destination.Type, ref discardedUseSiteInfo).Kind != ConversionKind.NoConversion; } public static bool HasIdentityConversionToAny<T>(T type, ArrayBuilder<T> targetTypes) where T : TypeSymbol { foreach (var targetType in targetTypes) { if (HasIdentityConversionInternal(type, targetType, includeNullability: false)) { return true; } } return false; } public Conversion ConvertExtensionMethodThisArg(TypeSymbol parameterType, TypeSymbol thisType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)thisType != null); var conversion = this.ClassifyImplicitExtensionMethodThisArgConversion(null, thisType, parameterType, ref useSiteInfo); return IsValidExtensionMethodThisArgConversion(conversion) ? conversion : Conversion.NoConversion; } // Spec 7.6.5.2: "An extension method ... is eligible if ... [an] implicit identity, reference, // or boxing conversion exists from expr to the type of the first parameter" public Conversion ClassifyImplicitExtensionMethodThisArgConversion(BoundExpression sourceExpressionOpt, TypeSymbol sourceType, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpressionOpt == null || (object)sourceExpressionOpt.Type == sourceType); Debug.Assert((object)destination != null); if ((object)sourceType != null) { if (HasIdentityConversionInternal(sourceType, destination)) { return Conversion.Identity; } if (HasBoxingConversion(sourceType, destination, ref useSiteInfo)) { return Conversion.Boxing; } if (HasImplicitReferenceConversion(sourceType, destination, ref useSiteInfo)) { return Conversion.ImplicitReference; } } if (sourceExpressionOpt?.Kind == BoundKind.TupleLiteral) { // GetTupleLiteralConversion is not used with IncludeNullability currently. // If that changes, the delegate below will need to consider top-level nullability. Debug.Assert(!IncludeNullability); var tupleConversion = GetTupleLiteralConversion( (BoundTupleLiteral)sourceExpressionOpt, destination, ref useSiteInfo, ConversionKind.ImplicitTupleLiteral, (ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => conversions.ClassifyImplicitExtensionMethodThisArgConversion(s, s.Type, d.Type, ref u), arg: false); if (tupleConversion.Exists) { return tupleConversion; } } if ((object)sourceType != null) { var tupleConversion = ClassifyTupleConversion( sourceType, destination, ref useSiteInfo, ConversionKind.ImplicitTuple, (ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => { if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) { return Conversion.NoConversion; } return conversions.ClassifyImplicitExtensionMethodThisArgConversion(null, s.Type, d.Type, ref u); }, arg: false); if (tupleConversion.Exists) { return tupleConversion; } } return Conversion.NoConversion; } // It should be possible to remove IsValidExtensionMethodThisArgConversion // since ClassifyImplicitExtensionMethodThisArgConversion should only // return valid conversions. https://github.com/dotnet/roslyn/issues/19622 // Spec 7.6.5.2: "An extension method ... is eligible if ... [an] implicit identity, reference, // or boxing conversion exists from expr to the type of the first parameter" public static bool IsValidExtensionMethodThisArgConversion(Conversion conversion) { switch (conversion.Kind) { case ConversionKind.Identity: case ConversionKind.Boxing: case ConversionKind.ImplicitReference: return true; case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitTupleLiteral: // check if all element conversions satisfy the requirement foreach (var elementConversion in conversion.UnderlyingConversions) { if (!IsValidExtensionMethodThisArgConversion(elementConversion)) { return false; } } return true; default: // Caller should have not have calculated another conversion. Debug.Assert(conversion.Kind == ConversionKind.NoConversion); return false; } } private const bool F = false; private const bool T = true; // Notice that there is no implicit numeric conversion from a type to itself. That's an // identity conversion. private static readonly bool[,] s_implicitNumericConversions = { // to sb b s us i ui l ul c f d m // from /* sb */ { F, F, T, F, T, F, T, F, F, T, T, T }, /* b */ { F, F, T, T, T, T, T, T, F, T, T, T }, /* s */ { F, F, F, F, T, F, T, F, F, T, T, T }, /* us */ { F, F, F, F, T, T, T, T, F, T, T, T }, /* i */ { F, F, F, F, F, F, T, F, F, T, T, T }, /* ui */ { F, F, F, F, F, F, T, T, F, T, T, T }, /* l */ { F, F, F, F, F, F, F, F, F, T, T, T }, /* ul */ { F, F, F, F, F, F, F, F, F, T, T, T }, /* c */ { F, F, F, T, T, T, T, T, F, T, T, T }, /* f */ { F, F, F, F, F, F, F, F, F, F, T, F }, /* d */ { F, F, F, F, F, F, F, F, F, F, F, F }, /* m */ { F, F, F, F, F, F, F, F, F, F, F, F } }; private static readonly bool[,] s_explicitNumericConversions = { // to sb b s us i ui l ul c f d m // from /* sb */ { F, T, F, T, F, T, F, T, T, F, F, F }, /* b */ { T, F, F, F, F, F, F, F, T, F, F, F }, /* s */ { T, T, F, T, F, T, F, T, T, F, F, F }, /* us */ { T, T, T, F, F, F, F, F, T, F, F, F }, /* i */ { T, T, T, T, F, T, F, T, T, F, F, F }, /* ui */ { T, T, T, T, T, F, F, F, T, F, F, F }, /* l */ { T, T, T, T, T, T, F, T, T, F, F, F }, /* ul */ { T, T, T, T, T, T, T, F, T, F, F, F }, /* c */ { T, T, T, F, F, F, F, F, F, F, F, F }, /* f */ { T, T, T, T, T, T, T, T, T, F, F, T }, /* d */ { T, T, T, T, T, T, T, T, T, T, F, T }, /* m */ { T, T, T, T, T, T, T, T, T, T, T, F } }; private static int GetNumericTypeIndex(SpecialType specialType) { switch (specialType) { case SpecialType.System_SByte: return 0; case SpecialType.System_Byte: return 1; case SpecialType.System_Int16: return 2; case SpecialType.System_UInt16: return 3; case SpecialType.System_Int32: return 4; case SpecialType.System_UInt32: return 5; case SpecialType.System_Int64: return 6; case SpecialType.System_UInt64: return 7; case SpecialType.System_Char: return 8; case SpecialType.System_Single: return 9; case SpecialType.System_Double: return 10; case SpecialType.System_Decimal: return 11; default: return -1; } } #nullable enable private static bool HasImplicitNumericConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); int sourceIndex = GetNumericTypeIndex(source.SpecialType); if (sourceIndex < 0) { return false; } int destinationIndex = GetNumericTypeIndex(destination.SpecialType); if (destinationIndex < 0) { return false; } return s_implicitNumericConversions[sourceIndex, destinationIndex]; } private static bool HasExplicitNumericConversion(TypeSymbol source, TypeSymbol destination) { // SPEC: The explicit numeric conversions are the conversions from a numeric-type to another // SPEC: numeric-type for which an implicit numeric conversion does not already exist. Debug.Assert((object)source != null); Debug.Assert((object)destination != null); int sourceIndex = GetNumericTypeIndex(source.SpecialType); if (sourceIndex < 0) { return false; } int destinationIndex = GetNumericTypeIndex(destination.SpecialType); if (destinationIndex < 0) { return false; } return s_explicitNumericConversions[sourceIndex, destinationIndex]; } private static bool IsConstantNumericZero(ConstantValue value) { switch (value.Discriminator) { case ConstantValueTypeDiscriminator.SByte: return value.SByteValue == 0; case ConstantValueTypeDiscriminator.Byte: return value.ByteValue == 0; case ConstantValueTypeDiscriminator.Int16: return value.Int16Value == 0; case ConstantValueTypeDiscriminator.Int32: case ConstantValueTypeDiscriminator.NInt: return value.Int32Value == 0; case ConstantValueTypeDiscriminator.Int64: return value.Int64Value == 0; case ConstantValueTypeDiscriminator.UInt16: return value.UInt16Value == 0; case ConstantValueTypeDiscriminator.UInt32: case ConstantValueTypeDiscriminator.NUInt: return value.UInt32Value == 0; case ConstantValueTypeDiscriminator.UInt64: return value.UInt64Value == 0; case ConstantValueTypeDiscriminator.Single: case ConstantValueTypeDiscriminator.Double: return value.DoubleValue == 0; case ConstantValueTypeDiscriminator.Decimal: return value.DecimalValue == 0; } return false; } private static bool IsNumericType(TypeSymbol type) { switch (type.SpecialType) { case SpecialType.System_Char: case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: case SpecialType.System_IntPtr when type.IsNativeIntegerType: case SpecialType.System_UIntPtr when type.IsNativeIntegerType: return true; default: return false; } } private static bool HasSpecialIntPtrConversion(TypeSymbol source, TypeSymbol target) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); // There are only a total of twelve user-defined explicit conversions on IntPtr and UIntPtr: // // IntPtr <---> int // IntPtr <---> long // IntPtr <---> void* // UIntPtr <---> uint // UIntPtr <---> ulong // UIntPtr <---> void* // // The specification says that you can put any *standard* implicit or explicit conversion // on "either side" of a user-defined explicit conversion, so the specification allows, say, // UIntPtr --> byte because the conversion UIntPtr --> uint is user-defined and the // conversion uint --> byte is "standard". It is "standard" because the conversion // byte --> uint is an implicit numeric conversion. // This means that certain conversions should be illegal. For example, IntPtr --> ulong // should be illegal because none of int --> ulong, long --> ulong and void* --> ulong // are "standard" conversions. // Similarly, some conversions involving IntPtr should be illegal because they are // ambiguous. byte --> IntPtr?, for example, is ambiguous. (There are four possible // UD operators: int --> IntPtr and long --> IntPtr, and their lifted versions. The // best possible source type is int, the best possible target type is IntPtr?, and // there is an ambiguity between the unlifted int --> IntPtr, and the lifted // int? --> IntPtr? conversions.) // In practice, the native compiler, and hence, the Roslyn compiler, allows all // these conversions. Any conversion from a numeric type to IntPtr, or from an IntPtr // to a numeric type, is allowed. Also, any conversion from a pointer type to IntPtr // or vice versa is allowed. var s0 = source.StrippedType(); var t0 = target.StrippedType(); TypeSymbol otherType; if (isIntPtrOrUIntPtr(s0)) { otherType = t0; } else if (isIntPtrOrUIntPtr(t0)) { otherType = s0; } else { return false; } if (otherType.IsPointerOrFunctionPointer()) { return true; } if (otherType.TypeKind == TypeKind.Enum) { return true; } switch (otherType.SpecialType) { case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Char: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Double: case SpecialType.System_Single: case SpecialType.System_Decimal: return true; } return false; static bool isIntPtrOrUIntPtr(TypeSymbol type) => (type.SpecialType == SpecialType.System_IntPtr || type.SpecialType == SpecialType.System_UIntPtr) && !type.IsNativeIntegerType; } private static bool HasExplicitEnumerationConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: The explicit enumeration conversions are: // SPEC: From sbyte, byte, short, ushort, int, uint, long, ulong, nint, nuint, char, float, double, or decimal to any enum-type. // SPEC: From any enum-type to sbyte, byte, short, ushort, int, uint, long, ulong, nint, nuint, char, float, double, or decimal. // SPEC: From any enum-type to any other enum-type. if (IsNumericType(source) && destination.IsEnumType()) { return true; } if (IsNumericType(destination) && source.IsEnumType()) { return true; } if (source.IsEnumType() && destination.IsEnumType()) { return true; } return false; } #nullable disable private Conversion ClassifyImplicitNullableConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: Predefined implicit conversions that operate on non-nullable value types can also be used with // SPEC: nullable forms of those types. For each of the predefined implicit identity, numeric and tuple conversions // SPEC: that convert from a non-nullable value type S to a non-nullable value type T, the following implicit // SPEC: nullable conversions exist: // SPEC: * An implicit conversion from S? to T?. // SPEC: * An implicit conversion from S to T?. if (!destination.IsNullableType()) { return Conversion.NoConversion; } TypeSymbol unwrappedDestination = destination.GetNullableUnderlyingType(); TypeSymbol unwrappedSource = source.StrippedType(); if (!unwrappedSource.IsValueType) { return Conversion.NoConversion; } if (HasIdentityConversionInternal(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ImplicitNullable, Conversion.IdentityUnderlying); } if (HasImplicitNumericConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ImplicitNullable, Conversion.ImplicitNumericUnderlying); } var tupleConversion = ClassifyImplicitTupleConversion(unwrappedSource, unwrappedDestination, ref useSiteInfo); if (tupleConversion.Exists) { return new Conversion(ConversionKind.ImplicitNullable, ImmutableArray.Create(tupleConversion)); } return Conversion.NoConversion; } private delegate Conversion ClassifyConversionFromExpressionDelegate(ConversionsBase conversions, BoundExpression sourceExpression, TypeWithAnnotations destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool arg); private delegate Conversion ClassifyConversionFromTypeDelegate(ConversionsBase conversions, TypeWithAnnotations source, TypeWithAnnotations destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool arg); private Conversion GetImplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // GetTupleLiteralConversion is not used with IncludeNullability currently. // If that changes, the delegate below will need to consider top-level nullability. Debug.Assert(!IncludeNullability); return GetTupleLiteralConversion( source, destination, ref useSiteInfo, ConversionKind.ImplicitTupleLiteral, (ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => conversions.ClassifyImplicitConversionFromExpression(s, d.Type, ref u), arg: false); } private Conversion GetExplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { // GetTupleLiteralConversion is not used with IncludeNullability currently. // If that changes, the delegate below will need to consider top-level nullability. Debug.Assert(!IncludeNullability); return GetTupleLiteralConversion( source, destination, ref useSiteInfo, ConversionKind.ExplicitTupleLiteral, (ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => conversions.ClassifyConversionFromExpression(s, d.Type, ref u, a), forCast); } private Conversion GetTupleLiteralConversion( BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConversionKind kind, ClassifyConversionFromExpressionDelegate classifyConversion, bool arg) { var arguments = source.Arguments; // check if the type is actually compatible type for a tuple of given cardinality if (!destination.IsTupleTypeOfCardinality(arguments.Length)) { return Conversion.NoConversion; } var targetElementTypes = destination.TupleElementTypesWithAnnotations; Debug.Assert(arguments.Length == targetElementTypes.Length); // check arguments against flattened list of target element types var argumentConversions = ArrayBuilder<Conversion>.GetInstance(arguments.Length); for (int i = 0; i < arguments.Length; i++) { var argument = arguments[i]; var result = classifyConversion(this, argument, targetElementTypes[i], ref useSiteInfo, arg); if (!result.Exists) { argumentConversions.Free(); return Conversion.NoConversion; } argumentConversions.Add(result); } return new Conversion(kind, argumentConversions.ToImmutableAndFree()); } private Conversion ClassifyImplicitTupleConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ClassifyTupleConversion( source, destination, ref useSiteInfo, ConversionKind.ImplicitTuple, (ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => { if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) { return Conversion.NoConversion; } return conversions.ClassifyImplicitConversionFromType(s.Type, d.Type, ref u); }, arg: false); } private Conversion ClassifyExplicitTupleConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { return ClassifyTupleConversion( source, destination, ref useSiteInfo, ConversionKind.ExplicitTuple, (ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => { if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) { return Conversion.NoConversion; } return conversions.ClassifyConversionFromType(s.Type, d.Type, ref u, a); }, forCast); } private Conversion ClassifyTupleConversion( TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConversionKind kind, ClassifyConversionFromTypeDelegate classifyConversion, bool arg) { ImmutableArray<TypeWithAnnotations> sourceTypes; ImmutableArray<TypeWithAnnotations> destTypes; if (!source.TryGetElementTypesWithAnnotationsIfTupleType(out sourceTypes) || !destination.TryGetElementTypesWithAnnotationsIfTupleType(out destTypes) || sourceTypes.Length != destTypes.Length) { return Conversion.NoConversion; } var nestedConversions = ArrayBuilder<Conversion>.GetInstance(sourceTypes.Length); for (int i = 0; i < sourceTypes.Length; i++) { var conversion = classifyConversion(this, sourceTypes[i], destTypes[i], ref useSiteInfo, arg); if (!conversion.Exists) { nestedConversions.Free(); return Conversion.NoConversion; } nestedConversions.Add(conversion); } return new Conversion(kind, nestedConversions.ToImmutableAndFree()); } private Conversion ClassifyExplicitNullableConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: Explicit nullable conversions permit predefined explicit conversions that operate on // SPEC: non-nullable value types to also be used with nullable forms of those types. For // SPEC: each of the predefined explicit conversions that convert from a non-nullable value type // SPEC: S to a non-nullable value type T, the following nullable conversions exist: // SPEC: An explicit conversion from S? to T?. // SPEC: An explicit conversion from S to T?. // SPEC: An explicit conversion from S? to T. if (!source.IsNullableType() && !destination.IsNullableType()) { return Conversion.NoConversion; } TypeSymbol unwrappedSource = source.StrippedType(); TypeSymbol unwrappedDestination = destination.StrippedType(); if (HasIdentityConversionInternal(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.IdentityUnderlying); } if (HasImplicitNumericConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.ImplicitNumericUnderlying); } if (HasExplicitNumericConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.ExplicitNumericUnderlying); } var tupleConversion = ClassifyExplicitTupleConversion(unwrappedSource, unwrappedDestination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return new Conversion(ConversionKind.ExplicitNullable, ImmutableArray.Create(tupleConversion)); } if (HasExplicitEnumerationConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.ExplicitEnumerationUnderlying); } if (HasPointerToIntegerConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.PointerToIntegerUnderlying); } return Conversion.NoConversion; } private bool HasCovariantArrayConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); var s = source as ArrayTypeSymbol; var d = destination as ArrayTypeSymbol; if ((object)s == null || (object)d == null) { return false; } // * S and T differ only in element type. In other words, S and T have the same number of dimensions. if (!s.HasSameShapeAs(d)) { return false; } // * Both SE and TE are reference types. // * An implicit reference conversion exists from SE to TE. return HasImplicitReferenceConversion(s.ElementTypeWithAnnotations, d.ElementTypeWithAnnotations, ref useSiteInfo); } public bool HasIdentityOrImplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return true; } return HasImplicitReferenceConversion(source, destination, ref useSiteInfo); } private static bool HasImplicitDynamicConversionFromExpression(TypeSymbol expressionType, TypeSymbol destination) { // Spec (§6.1.8) // An implicit dynamic conversion exists from an expression of type dynamic to any type T. Debug.Assert((object)destination != null); return expressionType?.Kind == SymbolKind.DynamicType && !destination.IsPointerOrFunctionPointer(); } private static bool HasExplicitDynamicConversion(TypeSymbol source, TypeSymbol destination) { // SPEC: An explicit dynamic conversion exists from an expression of [sic] type dynamic to any type T. // ISSUE: The "an expression of" part of the spec is probably an error; see https://github.com/dotnet/csharplang/issues/132 Debug.Assert((object)source != null); Debug.Assert((object)destination != null); return source.Kind == SymbolKind.DynamicType && !destination.IsPointerOrFunctionPointer(); } private bool HasArrayConversionToInterface(ArrayTypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!source.IsSZArray) { return false; } if (!destination.IsInterfaceType()) { return false; } // The specification says that there is a conversion: // * From a single-dimensional array type S[] to IList<T> and its base // interfaces, provided that there is an implicit identity or reference // conversion from S to T. // // Newer versions of the framework also have arrays be convertible to // IReadOnlyList<T> and IReadOnlyCollection<T>; we honor that as well. // // Therefore we must check for: // // IList<T> // ICollection<T> // IEnumerable<T> // IEnumerable // IReadOnlyList<T> // IReadOnlyCollection<T> if (destination.SpecialType == SpecialType.System_Collections_IEnumerable) { return true; } NamedTypeSymbol destinationAgg = (NamedTypeSymbol)destination; if (destinationAgg.AllTypeArgumentCount() != 1) { return false; } if (!destinationAgg.IsPossibleArrayGenericInterface()) { return false; } TypeWithAnnotations elementType = source.ElementTypeWithAnnotations; TypeWithAnnotations argument0 = destinationAgg.TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo); if (IncludeNullability && !HasTopLevelNullabilityImplicitConversion(elementType, argument0)) { return false; } return HasIdentityOrImplicitReferenceConversion(elementType.Type, argument0.Type, ref useSiteInfo); } private bool HasImplicitReferenceConversion(TypeWithAnnotations source, TypeWithAnnotations destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (IncludeNullability) { if (!HasTopLevelNullabilityImplicitConversion(source, destination)) { return false; } // Check for identity conversion of underlying types if the top-level nullability is distinct. // (An identity conversion where nullability matches is not considered an implicit reference conversion.) if (source.NullableAnnotation != destination.NullableAnnotation && HasIdentityConversionInternal(source.Type, destination.Type, includeNullability: true)) { return true; } } return HasImplicitReferenceConversion(source.Type, destination.Type, ref useSiteInfo); } internal bool HasImplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsErrorType()) { return false; } if (!source.IsReferenceType) { return false; } // SPEC: The implicit reference conversions are: // SPEC: UNDONE: From any reference-type to a reference-type T if it has an implicit identity // SPEC: UNDONE: or reference conversion to a reference-type T0 and T0 has an identity conversion to T. // UNDONE: Is the right thing to do here to strip dynamic off and check for convertibility? // SPEC: From any reference type to object and dynamic. if (destination.SpecialType == SpecialType.System_Object || destination.Kind == SymbolKind.DynamicType) { return true; } switch (source.TypeKind) { case TypeKind.Class: // SPEC: From any class type S to any class type T provided S is derived from T. if (destination.IsClassType() && IsBaseClass(source, destination, ref useSiteInfo)) { return true; } return HasImplicitConversionToInterface(source, destination, ref useSiteInfo); case TypeKind.Interface: // SPEC: From any interface-type S to any interface-type T, provided S is derived from T. // NOTE: This handles variance conversions return HasImplicitConversionToInterface(source, destination, ref useSiteInfo); case TypeKind.Delegate: // SPEC: From any delegate-type to System.Delegate and the interfaces it implements. // NOTE: This handles variance conversions. return HasImplicitConversionFromDelegate(source, destination, ref useSiteInfo); case TypeKind.TypeParameter: return HasImplicitReferenceTypeParameterConversion((TypeParameterSymbol)source, destination, ref useSiteInfo); case TypeKind.Array: // SPEC: From an array-type S ... to an array-type T, provided ... // SPEC: From any array-type to System.Array and the interfaces it implements. // SPEC: From a single-dimensional array type S[] to IList<T>, provided ... return HasImplicitConversionFromArray(source, destination, ref useSiteInfo); } // UNDONE: Implicit conversions involving type parameters that are known to be reference types. return false; } private bool HasImplicitConversionToInterface(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!destination.IsInterfaceType()) { return false; } // * From any class type S to any interface type T provided S implements an interface // convertible to T. if (source.IsClassType()) { return HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo); } // * From any interface type S to any interface type T provided S implements an interface // convertible to T. // * From any interface type S to any interface type T provided S is not T and S is // an interface convertible to T. if (source.IsInterfaceType()) { if (HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) { return true; } if (!HasIdentityConversionInternal(source, destination) && HasInterfaceVarianceConversion(source, destination, ref useSiteInfo)) { return true; } } return false; } private bool HasImplicitConversionFromArray(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { ArrayTypeSymbol s = source as ArrayTypeSymbol; if ((object)s == null) { return false; } // * From an array type S with an element type SE to an array type T with element type TE // provided that all of the following are true: // * S and T differ only in element type. In other words, S and T have the same number of dimensions. // * Both SE and TE are reference types. // * An implicit reference conversion exists from SE to TE. if (HasCovariantArrayConversion(source, destination, ref useSiteInfo)) { return true; } // * From any array type to System.Array or any interface implemented by System.Array. if (destination.GetSpecialTypeSafe() == SpecialType.System_Array) { return true; } if (IsBaseInterface(destination, this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Array), ref useSiteInfo)) { return true; } // * From a single-dimensional array type S[] to IList<T> and its base // interfaces, provided that there is an implicit identity or reference // conversion from S to T. if (HasArrayConversionToInterface(s, destination, ref useSiteInfo)) { return true; } return false; } private bool HasImplicitConversionFromDelegate(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!source.IsDelegateType()) { return false; } // * From any delegate type to System.Delegate // // SPEC OMISSION: // // The spec should actually say // // * From any delegate type to System.Delegate // * From any delegate type to System.MulticastDelegate // * From any delegate type to any interface implemented by System.MulticastDelegate var specialDestination = destination.GetSpecialTypeSafe(); if (specialDestination == SpecialType.System_MulticastDelegate || specialDestination == SpecialType.System_Delegate || IsBaseInterface(destination, this.corLibrary.GetDeclaredSpecialType(SpecialType.System_MulticastDelegate), ref useSiteInfo)) { return true; } // * From any delegate type S to a delegate type T provided S is not T and // S is a delegate convertible to T if (HasDelegateVarianceConversion(source, destination, ref useSiteInfo)) { return true; } return false; } public bool HasImplicitTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (HasImplicitReferenceTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } if (HasImplicitBoxingTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } if ((destination.TypeKind == TypeKind.TypeParameter) && source.DependsOn((TypeParameterSymbol)destination)) { return true; } return false; } private bool HasImplicitReferenceTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsValueType) { return false; // Not a reference conversion. } // The following implicit conversions exist for a given type parameter T: // // * From T to its effective base class C. // * From T to any base class of C. // * From T to any interface implemented by C (or any interface variance-compatible with such) if (HasImplicitEffectiveBaseConversion(source, destination, ref useSiteInfo)) { return true; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I (or any interface variance-compatible with such) if (HasImplicitEffectiveInterfaceSetConversion(source, destination, ref useSiteInfo)) { return true; } // * From T to a type parameter U, provided T depends on U. if ((destination.TypeKind == TypeKind.TypeParameter) && source.DependsOn((TypeParameterSymbol)destination)) { return true; } return false; } // Spec 6.1.10: Implicit conversions involving type parameters private bool HasImplicitEffectiveBaseConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // * From T to its effective base class C. var effectiveBaseClass = source.EffectiveBaseClass(ref useSiteInfo); if (HasIdentityConversionInternal(effectiveBaseClass, destination)) { return true; } // * From T to any base class of C. if (IsBaseClass(effectiveBaseClass, destination, ref useSiteInfo)) { return true; } // * From T to any interface implemented by C (or any interface variance-compatible with such) if (HasAnyBaseInterfaceConversion(effectiveBaseClass, destination, ref useSiteInfo)) { return true; } return false; } private bool HasImplicitEffectiveInterfaceSetConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!destination.IsInterfaceType()) { return false; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I (or any interface variance-compatible with such) foreach (var i in source.AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasInterfaceVarianceConversion(i, destination, ref useSiteInfo)) { return true; } } return false; } private bool HasAnyBaseInterfaceConversion(TypeSymbol derivedType, TypeSymbol baseType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)derivedType != null); Debug.Assert((object)baseType != null); if (!baseType.IsInterfaceType()) { return false; } var d = derivedType as NamedTypeSymbol; if ((object)d == null) { return false; } foreach (var i in d.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasInterfaceVarianceConversion(i, baseType, ref useSiteInfo)) { return true; } } return false; } //////////////////////////////////////////////////////////////////////////////// // The rules for variant interface and delegate conversions are the same: // // An interface/delegate type S is convertible to an interface/delegate type T // if and only if T is U<S1, ... Sn> and T is U<T1, ... Tn> such that for all // parameters of U: // // * if the ith parameter of U is invariant then Si is exactly equal to Ti. // * if the ith parameter of U is covariant then either Si is exactly equal // to Ti, or there is an implicit reference conversion from Si to Ti. // * if the ith parameter of U is contravariant then either Si is exactly // equal to Ti, or there is an implicit reference conversion from Ti to Si. private bool HasInterfaceVarianceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); NamedTypeSymbol s = source as NamedTypeSymbol; NamedTypeSymbol d = destination as NamedTypeSymbol; if ((object)s == null || (object)d == null) { return false; } if (!s.IsInterfaceType() || !d.IsInterfaceType()) { return false; } return HasVariantConversion(s, d, ref useSiteInfo); } private bool HasDelegateVarianceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); NamedTypeSymbol s = source as NamedTypeSymbol; NamedTypeSymbol d = destination as NamedTypeSymbol; if ((object)s == null || (object)d == null) { return false; } if (!s.IsDelegateType() || !d.IsDelegateType()) { return false; } return HasVariantConversion(s, d, ref useSiteInfo); } private bool HasVariantConversion(NamedTypeSymbol source, NamedTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // We check for overflows in HasVariantConversion, because they are only an issue // in the presence of contravariant type parameters, which are not involved in // most conversions. // See VarianceTests for examples (e.g. TestVarianceConversionCycle, // TestVarianceConversionInfiniteExpansion). // // CONSIDER: A more rigorous solution would mimic the CLI approach, which uses // a combination of requiring finite instantiation closures (see section 9.2 of // the CLI spec) and records previous conversion steps to check for cycles. if (currentRecursionDepth >= MaximumRecursionDepth) { // NOTE: The spec doesn't really address what happens if there's an overflow // in our conversion check. It's sort of implied that the conversion "proof" // should be finite, so we'll just say that no conversion is possible. return false; } // Do a quick check up front to avoid instantiating a new Conversions object, // if possible. var quickResult = HasVariantConversionQuick(source, destination); if (quickResult.HasValue()) { return quickResult.Value(); } return this.CreateInstance(currentRecursionDepth + 1). HasVariantConversionNoCycleCheck(source, destination, ref useSiteInfo); } private ThreeState HasVariantConversionQuick(NamedTypeSymbol source, NamedTypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return ThreeState.True; } NamedTypeSymbol typeSymbol = source.OriginalDefinition; if (!TypeSymbol.Equals(typeSymbol, destination.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { return ThreeState.False; } return ThreeState.Unknown; } private bool HasVariantConversionNoCycleCheck(NamedTypeSymbol source, NamedTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); var typeParameters = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var destinationTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); try { source.OriginalDefinition.GetAllTypeArguments(typeParameters, ref useSiteInfo); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); destination.GetAllTypeArguments(destinationTypeArguments, ref useSiteInfo); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, destination.OriginalDefinition, TypeCompareKind.AllIgnoreOptions)); Debug.Assert(typeParameters.Count == sourceTypeArguments.Count); Debug.Assert(typeParameters.Count == destinationTypeArguments.Count); for (int paramIndex = 0; paramIndex < typeParameters.Count; ++paramIndex) { var sourceTypeArgument = sourceTypeArguments[paramIndex]; var destinationTypeArgument = destinationTypeArguments[paramIndex]; // If they're identical then this one is automatically good, so skip it. if (HasIdentityConversionInternal(sourceTypeArgument.Type, destinationTypeArgument.Type) && HasTopLevelNullabilityIdentityConversion(sourceTypeArgument, destinationTypeArgument)) { continue; } TypeParameterSymbol typeParameterSymbol = (TypeParameterSymbol)typeParameters[paramIndex].Type; switch (typeParameterSymbol.Variance) { case VarianceKind.None: // System.IEquatable<T> is invariant for back compat reasons (dynamic type checks could start // to succeed where they previously failed, creating different runtime behavior), but the uses // require treatment specifically of nullability as contravariant, so we special case the // behavior here. Normally we use GetWellKnownType for these kinds of checks, but in this // case we don't want just the canonical IEquatable to be special-cased, we want all definitions // to be treated as contravariant, in case there are other definitions in metadata that were // compiled with that expectation. if (isTypeIEquatable(destination.OriginalDefinition) && TypeSymbol.Equals(destinationTypeArgument.Type, sourceTypeArgument.Type, TypeCompareKind.AllNullableIgnoreOptions) && HasAnyNullabilityImplicitConversion(destinationTypeArgument, sourceTypeArgument)) { return true; } return false; case VarianceKind.Out: if (!HasImplicitReferenceConversion(sourceTypeArgument, destinationTypeArgument, ref useSiteInfo)) { return false; } break; case VarianceKind.In: if (!HasImplicitReferenceConversion(destinationTypeArgument, sourceTypeArgument, ref useSiteInfo)) { return false; } break; default: throw ExceptionUtilities.UnexpectedValue(typeParameterSymbol.Variance); } } } finally { typeParameters.Free(); sourceTypeArguments.Free(); destinationTypeArguments.Free(); } return true; static bool isTypeIEquatable(NamedTypeSymbol type) { return type is { IsInterface: true, Name: "IEquatable", ContainingNamespace: { Name: "System", ContainingNamespace: { IsGlobalNamespace: true } }, ContainingSymbol: { Kind: SymbolKind.Namespace }, TypeParameters: { Length: 1 } }; } } // Spec 6.1.10 private bool HasImplicitBoxingTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsReferenceType) { return false; // Not a boxing conversion; both source and destination are references. } // The following implicit conversions exist for a given type parameter T: // // * From T to its effective base class C. // * From T to any base class of C. // * From T to any interface implemented by C (or any interface variance-compatible with such) if (HasImplicitEffectiveBaseConversion(source, destination, ref useSiteInfo)) { return true; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I (or any interface variance-compatible with such) if (HasImplicitEffectiveInterfaceSetConversion(source, destination, ref useSiteInfo)) { return true; } // SPEC: From T to a type parameter U, provided T depends on U if ((destination.TypeKind == TypeKind.TypeParameter) && source.DependsOn((TypeParameterSymbol)destination)) { return true; } // SPEC: From T to a reference type I if it has an implicit conversion to a reference // SPEC: type S0 and S0 has an identity conversion to S. At run-time the conversion // SPEC: is executed the same way as the conversion to S0. // REVIEW: If T is not known to be a reference type then the only way this clause can // REVIEW: come into effect is if the target type is dynamic. Is that correct? if (destination.Kind == SymbolKind.DynamicType) { return true; } return false; } public bool HasBoxingConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // Certain type parameter conversions are classified as boxing conversions. if ((source.TypeKind == TypeKind.TypeParameter) && HasImplicitBoxingTypeParameterConversion((TypeParameterSymbol)source, destination, ref useSiteInfo)) { return true; } // The rest of the boxing conversions only operate when going from a value type to a // reference type. if (!source.IsValueType || !destination.IsReferenceType) { return false; } // A boxing conversion exists from a nullable type to a reference type if and only if a // boxing conversion exists from the underlying type. if (source.IsNullableType()) { return HasBoxingConversion(source.GetNullableUnderlyingType(), destination, ref useSiteInfo); } // A boxing conversion exists from any non-nullable value type to object and dynamic, to // System.ValueType, and to any interface type variance-compatible with one implemented // by the non-nullable value type. // Furthermore, an enum type can be converted to the type System.Enum. // We set the base class of the structs to System.ValueType, System.Enum, etc, so we can // just check here. // There are a couple of exceptions. The very special types ArgIterator, ArgumentHandle and // TypedReference are not boxable: if (source.IsRestrictedType()) { return false; } if (destination.Kind == SymbolKind.DynamicType) { return !source.IsPointerOrFunctionPointer(); } if (IsBaseClass(source, destination, ref useSiteInfo)) { return true; } if (HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) { return true; } return false; } internal static bool HasImplicitPointerToVoidConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: The set of implicit conversions is extended to include... // SPEC: ... from any pointer type to the type void*. return source.IsPointerOrFunctionPointer() && destination is PointerTypeSymbol { PointedAtType: { SpecialType: SpecialType.System_Void } }; } #nullable enable internal bool HasImplicitPointerConversion(TypeSymbol? source, TypeSymbol? destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!(source is FunctionPointerTypeSymbol { Signature: { } sourceSig }) || !(destination is FunctionPointerTypeSymbol { Signature: { } destinationSig })) { return false; } if (sourceSig.ParameterCount != destinationSig.ParameterCount || sourceSig.CallingConvention != destinationSig.CallingConvention) { return false; } if (sourceSig.CallingConvention == Cci.CallingConvention.Unmanaged && !sourceSig.GetCallingConventionModifiers().SetEquals(destinationSig.GetCallingConventionModifiers())) { return false; } for (int i = 0; i < sourceSig.ParameterCount; i++) { var sourceParam = sourceSig.Parameters[i]; var destinationParam = destinationSig.Parameters[i]; if (sourceParam.RefKind != destinationParam.RefKind) { return false; } if (!hasConversion(sourceParam.RefKind, destinationSig.Parameters[i].TypeWithAnnotations, sourceSig.Parameters[i].TypeWithAnnotations, ref useSiteInfo)) { return false; } } return sourceSig.RefKind == destinationSig.RefKind && hasConversion(sourceSig.RefKind, sourceSig.ReturnTypeWithAnnotations, destinationSig.ReturnTypeWithAnnotations, ref useSiteInfo); bool hasConversion(RefKind refKind, TypeWithAnnotations sourceType, TypeWithAnnotations destinationType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (refKind) { case RefKind.None: return (!IncludeNullability || HasTopLevelNullabilityImplicitConversion(sourceType, destinationType)) && (HasIdentityOrImplicitReferenceConversion(sourceType.Type, destinationType.Type, ref useSiteInfo) || HasImplicitPointerToVoidConversion(sourceType.Type, destinationType.Type) || HasImplicitPointerConversion(sourceType.Type, destinationType.Type, ref useSiteInfo)); default: return (!IncludeNullability || HasTopLevelNullabilityIdentityConversion(sourceType, destinationType)) && HasIdentityConversion(sourceType.Type, destinationType.Type); } } } #nullable disable private bool HasIdentityOrReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return true; } if (HasImplicitReferenceConversion(source, destination, ref useSiteInfo)) { return true; } if (HasExplicitReferenceConversion(source, destination, ref useSiteInfo)) { return true; } return false; } private bool HasExplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: The explicit reference conversions are: // SPEC: From object and dynamic to any other reference type. if (source.SpecialType == SpecialType.System_Object) { if (destination.IsReferenceType) { return true; } } else if (source.Kind == SymbolKind.DynamicType && destination.IsReferenceType) { return true; } // SPEC: From any class-type S to any class-type T, provided S is a base class of T. if (destination.IsClassType() && IsBaseClass(destination, source, ref useSiteInfo)) { return true; } // SPEC: From any class-type S to any interface-type T, provided S is not sealed and provided S does not implement T. // ISSUE: class C : IEnumerable<Mammal> { } converting this to IEnumerable<Animal> is not an explicit conversion, // ISSUE: it is an implicit conversion. if (source.IsClassType() && destination.IsInterfaceType() && !source.IsSealed && !HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) { return true; } // SPEC: From any interface-type S to any class-type T, provided T is not sealed or provided T implements S. // ISSUE: What if T is sealed and implements an interface variance-convertible to S? // ISSUE: eg, sealed class C : IEnum<Mammal> { ... } you should be able to cast an IEnum<Animal> to C. if (source.IsInterfaceType() && destination.IsClassType() && (!destination.IsSealed || HasAnyBaseInterfaceConversion(destination, source, ref useSiteInfo))) { return true; } // SPEC: From any interface-type S to any interface-type T, provided S is not derived from T. // ISSUE: This does not rule out identity conversions, which ought not to be classified as // ISSUE: explicit reference conversions. // ISSUE: IEnumerable<Mammal> and IEnumerable<Animal> do not derive from each other but this is // ISSUE: not an explicit reference conversion, this is an implicit reference conversion. if (source.IsInterfaceType() && destination.IsInterfaceType() && !HasImplicitConversionToInterface(source, destination, ref useSiteInfo)) { return true; } // SPEC: UNDONE: From a reference type to a reference type T if it has an explicit reference conversion to a reference type T0 and T0 has an identity conversion T. // SPEC: UNDONE: From a reference type to an interface or delegate type T if it has an explicit reference conversion to an interface or delegate type T0 and either T0 is variance-convertible to T or T is variance-convertible to T0 (§13.1.3.2). if (HasExplicitArrayConversion(source, destination, ref useSiteInfo)) { return true; } if (HasExplicitDelegateConversion(source, destination, ref useSiteInfo)) { return true; } if (HasExplicitReferenceTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } return false; } // Spec 6.2.7 Explicit conversions involving type parameters private bool HasExplicitReferenceTypeParameterConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); TypeParameterSymbol s = source as TypeParameterSymbol; TypeParameterSymbol t = destination as TypeParameterSymbol; // SPEC: The following explicit conversions exist for a given type parameter T: // SPEC: If T is known to be a reference type, the conversions are all classified as explicit reference conversions. // SPEC: If T is not known to be a reference type, the conversions are classified as unboxing conversions. // SPEC: From the effective base class C of T to T and from any base class of C to T. if ((object)t != null && t.IsReferenceType) { for (var type = t.EffectiveBaseClass(ref useSiteInfo); (object)type != null; type = type.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(type, source)) { return true; } } } // SPEC: From any interface type to T. if ((object)t != null && source.IsInterfaceType() && t.IsReferenceType) { return true; } // SPEC: From T to any interface-type I provided there is not already an implicit conversion from T to I. if ((object)s != null && s.IsReferenceType && destination.IsInterfaceType() && !HasImplicitReferenceTypeParameterConversion(s, destination, ref useSiteInfo)) { return true; } // SPEC: From a type parameter U to T, provided T depends on U (§10.1.5) if ((object)s != null && (object)t != null && t.IsReferenceType && t.DependsOn(s)) { return true; } return false; } // Spec 6.2.7 Explicit conversions involving type parameters private bool HasUnboxingTypeParameterConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); TypeParameterSymbol s = source as TypeParameterSymbol; TypeParameterSymbol t = destination as TypeParameterSymbol; // SPEC: The following explicit conversions exist for a given type parameter T: // SPEC: If T is known to be a reference type, the conversions are all classified as explicit reference conversions. // SPEC: If T is not known to be a reference type, the conversions are classified as unboxing conversions. // SPEC: From the effective base class C of T to T and from any base class of C to T. if ((object)t != null && !t.IsReferenceType) { for (var type = t.EffectiveBaseClass(ref useSiteInfo); (object)type != null; type = type.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (TypeSymbol.Equals(type, source, TypeCompareKind.ConsiderEverything2)) { return true; } } } // SPEC: From any interface type to T. if (source.IsInterfaceType() && (object)t != null && !t.IsReferenceType) { return true; } // SPEC: From T to any interface-type I provided there is not already an implicit conversion from T to I. if ((object)s != null && !s.IsReferenceType && destination.IsInterfaceType() && !HasImplicitReferenceTypeParameterConversion(s, destination, ref useSiteInfo)) { return true; } // SPEC: From a type parameter U to T, provided T depends on U (§10.1.5) if ((object)s != null && (object)t != null && !t.IsReferenceType && t.DependsOn(s)) { return true; } return false; } private bool HasExplicitDelegateConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: From System.Delegate and the interfaces it implements to any delegate-type. // We also support System.MulticastDelegate in the implementation, in spite of it not being mentioned in the spec. if (destination.IsDelegateType()) { if (source.SpecialType == SpecialType.System_Delegate || source.SpecialType == SpecialType.System_MulticastDelegate) { return true; } if (HasImplicitConversionToInterface(this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Delegate), source, ref useSiteInfo)) { return true; } } // SPEC: From D<S1...Sn> to a D<T1...Tn> where D<X1...Xn> is a generic delegate type, D<S1...Sn> is not compatible with or identical to D<T1...Tn>, // SPEC: and for each type parameter Xi of D the following holds: // SPEC: If Xi is invariant, then Si is identical to Ti. // SPEC: If Xi is covariant, then there is an implicit or explicit identity or reference conversion from Si to Ti. // SPECL If Xi is contravariant, then Si and Ti are either identical or both reference types. if (!source.IsDelegateType() || !destination.IsDelegateType()) { return false; } if (!TypeSymbol.Equals(source.OriginalDefinition, destination.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { return false; } var sourceType = (NamedTypeSymbol)source; var destinationType = (NamedTypeSymbol)destination; var original = sourceType.OriginalDefinition; if (HasIdentityConversionInternal(source, destination)) { return false; } if (HasDelegateVarianceConversion(source, destination, ref useSiteInfo)) { return false; } var sourceTypeArguments = sourceType.TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo); var destinationTypeArguments = destinationType.TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo); for (int i = 0; i < sourceTypeArguments.Length; ++i) { var sourceArg = sourceTypeArguments[i].Type; var destinationArg = destinationTypeArguments[i].Type; switch (original.TypeParameters[i].Variance) { case VarianceKind.None: if (!HasIdentityConversionInternal(sourceArg, destinationArg)) { return false; } break; case VarianceKind.Out: if (!HasIdentityOrReferenceConversion(sourceArg, destinationArg, ref useSiteInfo)) { return false; } break; case VarianceKind.In: bool hasIdentityConversion = HasIdentityConversionInternal(sourceArg, destinationArg); bool bothAreReferenceTypes = sourceArg.IsReferenceType && destinationArg.IsReferenceType; if (!(hasIdentityConversion || bothAreReferenceTypes)) { return false; } break; } } return true; } private bool HasExplicitArrayConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); var sourceArray = source as ArrayTypeSymbol; var destinationArray = destination as ArrayTypeSymbol; // SPEC: From an array-type S with an element type SE to an array-type T with an element type TE, provided all of the following are true: // SPEC: S and T differ only in element type. (In other words, S and T have the same number of dimensions.) // SPEC: Both SE and TE are reference-types. // SPEC: An explicit reference conversion exists from SE to TE. if ((object)sourceArray != null && (object)destinationArray != null) { // HasExplicitReferenceConversion checks that SE and TE are reference types so // there's no need for that check here. Moreover, it's not as simple as checking // IsReferenceType, at least not in the case of type parameters, since SE will be // considered a reference type implicitly in the case of "where TE : class, SE" even // though SE.IsReferenceType may be false. Again, HasExplicitReferenceConversion // already handles these cases. return sourceArray.HasSameShapeAs(destinationArray) && HasExplicitReferenceConversion(sourceArray.ElementType, destinationArray.ElementType, ref useSiteInfo); } // SPEC: From System.Array and the interfaces it implements to any array-type. if ((object)destinationArray != null) { if (source.SpecialType == SpecialType.System_Array) { return true; } foreach (var iface in this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Array).AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(iface, source)) { return true; } } } // SPEC: From a single-dimensional array type S[] to System.Collections.Generic.IList<T> and its base interfaces // SPEC: provided that there is an explicit reference conversion from S to T. // The framework now also allows arrays to be converted to IReadOnlyList<T> and IReadOnlyCollection<T>; we // honor that as well. if ((object)sourceArray != null && sourceArray.IsSZArray && destination.IsPossibleArrayGenericInterface()) { if (HasExplicitReferenceConversion(sourceArray.ElementType, ((NamedTypeSymbol)destination).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo).Type, ref useSiteInfo)) { return true; } } // SPEC: From System.Collections.Generic.IList<S> and its base interfaces to a single-dimensional array type T[], // provided that there is an explicit identity or reference conversion from S to T. // Similarly, we honor IReadOnlyList<S> and IReadOnlyCollection<S> in the same way. if ((object)destinationArray != null && destinationArray.IsSZArray) { var specialDefinition = ((TypeSymbol)source.OriginalDefinition).SpecialType; if (specialDefinition == SpecialType.System_Collections_Generic_IList_T || specialDefinition == SpecialType.System_Collections_Generic_ICollection_T || specialDefinition == SpecialType.System_Collections_Generic_IEnumerable_T || specialDefinition == SpecialType.System_Collections_Generic_IReadOnlyList_T || specialDefinition == SpecialType.System_Collections_Generic_IReadOnlyCollection_T) { var sourceElement = ((NamedTypeSymbol)source).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo).Type; var destinationElement = destinationArray.ElementType; if (HasIdentityConversionInternal(sourceElement, destinationElement)) { return true; } if (HasImplicitReferenceConversion(sourceElement, destinationElement, ref useSiteInfo)) { return true; } if (HasExplicitReferenceConversion(sourceElement, destinationElement, ref useSiteInfo)) { return true; } } } return false; } private bool HasUnboxingConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (destination.IsPointerOrFunctionPointer()) { return false; } // Ref-like types cannot be boxed or unboxed if (destination.IsRestrictedType()) { return false; } // SPEC: An unboxing conversion permits a reference type to be explicitly converted to a value-type. // SPEC: An unboxing conversion exists from the types object and System.ValueType to any non-nullable-value-type, var specialTypeSource = source.SpecialType; if (specialTypeSource == SpecialType.System_Object || specialTypeSource == SpecialType.System_ValueType) { if (destination.IsValueType && !destination.IsNullableType()) { return true; } } // SPEC: and from any interface-type to any non-nullable-value-type that implements the interface-type. if (source.IsInterfaceType() && destination.IsValueType && !destination.IsNullableType() && HasBoxingConversion(destination, source, ref useSiteInfo)) { return true; } // SPEC: Furthermore type System.Enum can be unboxed to any enum-type. if (source.SpecialType == SpecialType.System_Enum && destination.IsEnumType()) { return true; } // SPEC: An unboxing conversion exists from a reference type to a nullable-type if an unboxing // SPEC: conversion exists from the reference type to the underlying non-nullable-value-type // SPEC: of the nullable-type. if (source.IsReferenceType && destination.IsNullableType() && HasUnboxingConversion(source, destination.GetNullableUnderlyingType(), ref useSiteInfo)) { return true; } // SPEC: UNDONE A value type S has an unboxing conversion from an interface type I if it has an unboxing // SPEC: UNDONE conversion from an interface type I0 and I0 has an identity conversion to I. // SPEC: UNDONE A value type S has an unboxing conversion from an interface type I if it has an unboxing conversion // SPEC: UNDONE from an interface or delegate type I0 and either I0 is variance-convertible to I or I is variance-convertible to I0. if (HasUnboxingTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } return false; } private static bool HasPointerToPointerConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); return source.IsPointerOrFunctionPointer() && destination.IsPointerOrFunctionPointer(); } private static bool HasPointerToIntegerConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!source.IsPointerOrFunctionPointer()) { return false; } // SPEC OMISSION: // // The spec should state that any pointer type is convertible to // sbyte, byte, ... etc, or any corresponding nullable type. return IsIntegerTypeSupportingPointerConversions(destination.StrippedType()); } private static bool HasIntegerToPointerConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!destination.IsPointerOrFunctionPointer()) { return false; } // Note that void* is convertible to int?, but int? is not convertible to void*. return IsIntegerTypeSupportingPointerConversions(source); } private static bool IsIntegerTypeSupportingPointerConversions(TypeSymbol type) { switch (type.SpecialType) { case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: return true; case SpecialType.System_IntPtr: case SpecialType.System_UIntPtr: return type.IsNativeIntegerType; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal abstract partial class ConversionsBase { private const int MaximumRecursionDepth = 50; protected readonly AssemblySymbol corLibrary; protected readonly int currentRecursionDepth; internal readonly bool IncludeNullability; /// <summary> /// An optional clone of this instance with distinct IncludeNullability. /// Used to avoid unnecessary allocations when calling WithNullability() repeatedly. /// </summary> private ConversionsBase _lazyOtherNullability; protected ConversionsBase(AssemblySymbol corLibrary, int currentRecursionDepth, bool includeNullability, ConversionsBase otherNullabilityOpt) { Debug.Assert((object)corLibrary != null); Debug.Assert(otherNullabilityOpt == null || includeNullability != otherNullabilityOpt.IncludeNullability); Debug.Assert(otherNullabilityOpt == null || currentRecursionDepth == otherNullabilityOpt.currentRecursionDepth); this.corLibrary = corLibrary; this.currentRecursionDepth = currentRecursionDepth; IncludeNullability = includeNullability; _lazyOtherNullability = otherNullabilityOpt; } /// <summary> /// Returns this instance if includeNullability is correct, and returns a /// cached clone of this instance with distinct IncludeNullability otherwise. /// </summary> internal ConversionsBase WithNullability(bool includeNullability) { if (IncludeNullability == includeNullability) { return this; } if (_lazyOtherNullability == null) { Interlocked.CompareExchange(ref _lazyOtherNullability, WithNullabilityCore(includeNullability), null); } Debug.Assert(_lazyOtherNullability.IncludeNullability == includeNullability); Debug.Assert(_lazyOtherNullability._lazyOtherNullability == this); return _lazyOtherNullability; } protected abstract ConversionsBase WithNullabilityCore(bool includeNullability); public abstract Conversion GetMethodGroupDelegateConversion(BoundMethodGroup source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); public abstract Conversion GetMethodGroupFunctionPointerConversion(BoundMethodGroup source, FunctionPointerTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); public abstract Conversion GetStackAllocConversion(BoundStackAllocArrayCreation sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); protected abstract ConversionsBase CreateInstance(int currentRecursionDepth); protected abstract Conversion GetInterpolatedStringConversion(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); internal AssemblySymbol CorLibrary { get { return corLibrary; } } /// <summary> /// Determines if the source expression is convertible to the destination type via /// any built-in or user-defined implicit conversion. /// </summary> public Conversion ClassifyImplicitConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null); Debug.Assert((object)destination != null); var sourceType = sourceExpression.Type; //PERF: identity conversion is by far the most common implicit conversion, check for that first if ((object)sourceType != null && HasIdentityConversionInternal(sourceType, destination)) { return Conversion.Identity; } Conversion conversion = ClassifyImplicitBuiltInConversionFromExpression(sourceExpression, sourceType, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } if ((object)sourceType != null) { // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(sourceType, destination); if (fastConversion.Exists) { if (fastConversion.IsImplicit) { return fastConversion; } } else { conversion = ClassifyImplicitBuiltInConversionSlow(sourceType, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } } } conversion = GetImplicitUserDefinedConversion(sourceExpression, sourceType, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } // The switch expression conversion is "lowest priority", so that if there is a conversion from the expression's // type it will be preferred over the switch expression conversion. Technically, we would want the language // specification to say that the switch expression conversion only "exists" if there is no implicit conversion // from the type, and we accomplish that by making it lowest priority. The same is true for the conditional // expression conversion. conversion = GetSwitchExpressionConversion(sourceExpression, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } return GetConditionalExpressionConversion(sourceExpression, destination, ref useSiteInfo); } /// <summary> /// Determines if the source type is convertible to the destination type via /// any built-in or user-defined implicit conversion. /// </summary> public Conversion ClassifyImplicitConversionFromType(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); //PERF: identity conversions are very common, check for that first. if (HasIdentityConversionInternal(source, destination)) { return Conversion.Identity; } // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion.IsImplicit ? fastConversion : Conversion.NoConversion; } else { Conversion conversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } } return GetImplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); } /// <summary> /// Determines if the source expression of given type is convertible to the destination type via /// any built-in or user-defined conversion. /// /// This helper is used in rare cases involving synthesized expressions where we know the type of an expression, but do not have the actual expression. /// The reason for this helper (as opposed to ClassifyConversionFromType) is that conversions from expressions could be different /// from conversions from type. For example expressions of dynamic type are implicitly convertable to any type, while dynamic type itself is not. /// </summary> public Conversion ClassifyConversionFromExpressionType(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // since we are converting from expression, we may have implicit dynamic conversion if (HasImplicitDynamicConversionFromExpression(source, destination)) { return Conversion.ImplicitDynamic; } return ClassifyConversionFromType(source, destination, ref useSiteInfo); } private static bool TryGetVoidConversion(TypeSymbol source, TypeSymbol destination, out Conversion conversion) { var sourceIsVoid = source?.SpecialType == SpecialType.System_Void; var destIsVoid = destination.SpecialType == SpecialType.System_Void; // 'void' is not supposed to be able to convert to or from anything, but in practice, // a lot of code depends on checking whether an expression of type 'void' is convertible to 'void'. // (e.g. for an expression lambda which returns void). // Therefore we allow an identity conversion between 'void' and 'void'. if (sourceIsVoid && destIsVoid) { conversion = Conversion.Identity; return true; } // If exactly one of source or destination is of type 'void' then no conversion may exist. if (sourceIsVoid || destIsVoid) { conversion = Conversion.NoConversion; return true; } conversion = default; return false; } /// <summary> /// Determines if the source expression is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source expression to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the implicit conversion or explicit depending on "forCast" /// </remarks> public Conversion ClassifyConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast = false) { Debug.Assert(sourceExpression != null); Debug.Assert((object)destination != null); if (TryGetVoidConversion(sourceExpression.Type, destination, out var conversion)) { return conversion; } if (forCast) { return ClassifyConversionFromExpressionForCast(sourceExpression, destination, ref useSiteInfo); } var result = ClassifyImplicitConversionFromExpression(sourceExpression, destination, ref useSiteInfo); if (result.Exists) { return result; } return ClassifyExplicitOnlyConversionFromExpression(sourceExpression, destination, ref useSiteInfo, forCast: false); } /// <summary> /// Determines if the source type is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source type to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the implicit conversion or explicit depending on "forCast" /// </remarks> public Conversion ClassifyConversionFromType(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast = false) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (TryGetVoidConversion(source, destination, out var voidConversion)) { return voidConversion; } if (forCast) { return ClassifyConversionFromTypeForCast(source, destination, ref useSiteInfo); } // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion; } else { Conversion conversion1 = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (conversion1.Exists) { return conversion1; } } Conversion conversion = GetImplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } conversion = ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteInfo, forCast: false); if (conversion.Exists) { return conversion; } return GetExplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); } /// <summary> /// Determines if the source expression is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source expression to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the built-in conversion. /// /// An implicit conversion exists from an expression of a dynamic type to any type. /// An explicit conversion exists from a dynamic type to any type. /// When casting we prefer the explicit conversion. /// </remarks> private Conversion ClassifyConversionFromExpressionForCast(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert((object)destination != null); Conversion implicitConversion = ClassifyImplicitConversionFromExpression(source, destination, ref useSiteInfo); if (implicitConversion.Exists && !ExplicitConversionMayDifferFromImplicit(implicitConversion)) { return implicitConversion; } Conversion explicitConversion = ClassifyExplicitOnlyConversionFromExpression(source, destination, ref useSiteInfo, forCast: true); if (explicitConversion.Exists) { return explicitConversion; } // It is possible for a user-defined conversion to be unambiguous when considered as // an implicit conversion and ambiguous when considered as an explicit conversion. // The native compiler does not check to see if a cast could be successfully bound as // an unambiguous user-defined implicit conversion; it goes right to the ambiguous // user-defined explicit conversion and produces an error. This means that in // C# 5 it is possible to have: // // Y y = new Y(); // Z z1 = y; // // succeed but // // Z z2 = (Z)y; // // fail. // // However, there is another interesting wrinkle. It is possible for both // an implicit user-defined conversion and an explicit user-defined conversion // to exist and be unambiguous. For example, if there is an implicit conversion // double-->C and an explicit conversion from int-->C, and the user casts a short // to C, then both the implicit and explicit conversions are applicable and // unambiguous. The native compiler in this case prefers the explicit conversion, // and for backwards compatibility, we match it. return implicitConversion; } /// <summary> /// Determines if the source type is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source type to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the built-in conversion. /// </remarks> private Conversion ClassifyConversionFromTypeForCast(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion; } Conversion implicitBuiltInConversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (implicitBuiltInConversion.Exists && !ExplicitConversionMayDifferFromImplicit(implicitBuiltInConversion)) { return implicitBuiltInConversion; } Conversion explicitBuiltInConversion = ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteInfo, forCast: true); if (explicitBuiltInConversion.Exists) { return explicitBuiltInConversion; } if (implicitBuiltInConversion.Exists) { return implicitBuiltInConversion; } // It is possible for a user-defined conversion to be unambiguous when considered as // an implicit conversion and ambiguous when considered as an explicit conversion. // The native compiler does not check to see if a cast could be successfully bound as // an unambiguous user-defined implicit conversion; it goes right to the ambiguous // user-defined explicit conversion and produces an error. This means that in // C# 5 it is possible to have: // // Y y = new Y(); // Z z1 = y; // // succeed but // // Z z2 = (Z)y; // // fail. var conversion = GetExplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } return GetImplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); } /// <summary> /// Attempt a quick classification of builtin conversions. As result of "no conversion" /// means that there is no built-in conversion, though there still may be a user-defined /// conversion if compiling against a custom mscorlib. /// </summary> public static Conversion FastClassifyConversion(TypeSymbol source, TypeSymbol target) { ConversionKind convKind = ConversionEasyOut.ClassifyConversion(source, target); if (convKind != ConversionKind.ImplicitNullable && convKind != ConversionKind.ExplicitNullable) { return Conversion.GetTrivialConversion(convKind); } return Conversion.MakeNullableConversion(convKind, FastClassifyConversion(source.StrippedType(), target.StrippedType())); } public Conversion ClassifyBuiltInConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion; } else { Conversion conversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } } return ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteInfo, forCast: false); } /// <summary> /// Determines if the source type is convertible to the destination type via /// any standard implicit or standard explicit conversion. /// </summary> /// <remarks> /// Not all built-in explicit conversions are standard explicit conversions. /// </remarks> public Conversion ClassifyStandardConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert((object)destination != null); // Note that the definition of explicit standard conversion does not include all explicit // reference conversions! There is a standard implicit reference conversion from // Action<Object> to Action<Exception>, thanks to contravariance. There is a standard // implicit reference conversion from Action<Object> to Action<String> for the same reason. // Therefore there is an explicit reference conversion from Action<Exception> to // Action<String>; a given Action<Exception> might be an Action<Object>, and hence // convertible to Action<String>. However, this is not a *standard* explicit conversion. The // standard explicit conversions are all the standard implicit conversions and their // opposites. Therefore Action<Object>-->Action<String> and Action<String>-->Action<Object> // are both standard conversions. But Action<String>-->Action<Exception> is not a standard // explicit conversion because neither it nor its opposite is a standard implicit // conversion. // // Similarly, there is no standard explicit conversion from double to decimal, because // there is no standard implicit conversion between the two types. // SPEC: The standard explicit conversions are all standard implicit conversions plus // SPEC: the subset of the explicit conversions for which an opposite standard implicit // SPEC: conversion exists. In other words, if a standard implicit conversion exists from // SPEC: a type A to a type B, then a standard explicit conversion exists from type A to // SPEC: type B and from type B to type A. Conversion conversion = ClassifyStandardImplicitConversion(sourceExpression, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } if ((object)source != null) { return DeriveStandardExplicitFromOppositeStandardImplicitConversion(source, destination, ref useSiteInfo); } return Conversion.NoConversion; } private Conversion ClassifyStandardImplicitConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert(sourceExpression == null || (object)sourceExpression.Type == (object)source); Debug.Assert((object)destination != null); // SPEC: The following implicit conversions are classified as standard implicit conversions: // SPEC: Identity conversions // SPEC: Implicit numeric conversions // SPEC: Implicit nullable conversions // SPEC: Implicit reference conversions // SPEC: Boxing conversions // SPEC: Implicit constant expression conversions // SPEC: Implicit conversions involving type parameters // // and in unsafe code: // // SPEC: From any pointer type to void* // // SPEC ERROR: // The specification does not say to take into account the conversion from // the *expression*, only its *type*. But the expression may not have a type // (because it is null, a method group, or a lambda), or the expression might // be convertible to the destination type via a constant numeric conversion. // For example, the native compiler allows "C c = 1;" to work if C is a class which // has an implicit conversion from byte to C, despite the fact that there is // obviously no standard implicit conversion from *int* to *byte*. // Similarly, if a struct S has an implicit conversion from string to S, then // "S s = null;" should be allowed. // // We extend the definition of standard implicit conversions to include // all of the implicit conversions that are allowed based on an expression, // with the exception of the switch expression conversion. Conversion conversion = ClassifyImplicitBuiltInConversionFromExpression(sourceExpression, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } if ((object)source != null) { return ClassifyStandardImplicitConversion(source, destination, ref useSiteInfo); } return Conversion.NoConversion; } private Conversion ClassifyStandardImplicitConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return Conversion.Identity; } if (HasImplicitNumericConversion(source, destination)) { return Conversion.ImplicitNumeric; } var nullableConversion = ClassifyImplicitNullableConversion(source, destination, ref useSiteInfo); if (nullableConversion.Exists) { return nullableConversion; } if (HasImplicitReferenceConversion(source, destination, ref useSiteInfo)) { return Conversion.ImplicitReference; } if (HasBoxingConversion(source, destination, ref useSiteInfo)) { return Conversion.Boxing; } if (HasImplicitPointerToVoidConversion(source, destination)) { return Conversion.PointerToVoid; } if (HasImplicitPointerConversion(source, destination, ref useSiteInfo)) { return Conversion.ImplicitPointer; } var tupleConversion = ClassifyImplicitTupleConversion(source, destination, ref useSiteInfo); if (tupleConversion.Exists) { return tupleConversion; } return Conversion.NoConversion; } private Conversion ClassifyImplicitBuiltInConversionSlow(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsVoidType() || destination.IsVoidType()) { return Conversion.NoConversion; } Conversion conversion = ClassifyStandardImplicitConversion(source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } return Conversion.NoConversion; } private Conversion GetImplicitUserDefinedConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var conversionResult = AnalyzeImplicitUserDefinedConversions(sourceExpression, source, destination, ref useSiteInfo); return new Conversion(conversionResult, isImplicit: true); } private Conversion ClassifyExplicitBuiltInOnlyConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsVoidType() || destination.IsVoidType()) { return Conversion.NoConversion; } // The call to HasExplicitNumericConversion isn't necessary, because it is always tested // already by the "FastConversion" code. Debug.Assert(!HasExplicitNumericConversion(source, destination)); //if (HasExplicitNumericConversion(source, specialTypeSource, destination, specialTypeDest)) //{ // return Conversion.ExplicitNumeric; //} if (HasSpecialIntPtrConversion(source, destination)) { return Conversion.IntPtr; } if (HasExplicitEnumerationConversion(source, destination)) { return Conversion.ExplicitEnumeration; } var nullableConversion = ClassifyExplicitNullableConversion(source, destination, ref useSiteInfo, forCast); if (nullableConversion.Exists) { return nullableConversion; } if (HasExplicitReferenceConversion(source, destination, ref useSiteInfo)) { return (source.Kind == SymbolKind.DynamicType) ? Conversion.ExplicitDynamic : Conversion.ExplicitReference; } if (HasUnboxingConversion(source, destination, ref useSiteInfo)) { return Conversion.Unboxing; } var tupleConversion = ClassifyExplicitTupleConversion(source, destination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return tupleConversion; } if (HasPointerToPointerConversion(source, destination)) { return Conversion.PointerToPointer; } if (HasPointerToIntegerConversion(source, destination)) { return Conversion.PointerToInteger; } if (HasIntegerToPointerConversion(source, destination)) { return Conversion.IntegerToPointer; } if (HasExplicitDynamicConversion(source, destination)) { return Conversion.ExplicitDynamic; } return Conversion.NoConversion; } private Conversion GetExplicitUserDefinedConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { UserDefinedConversionResult conversionResult = AnalyzeExplicitUserDefinedConversions(sourceExpression, source, destination, ref useSiteInfo); return new Conversion(conversionResult, isImplicit: false); } private Conversion DeriveStandardExplicitFromOppositeStandardImplicitConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var oppositeConversion = ClassifyStandardImplicitConversion(destination, source, ref useSiteInfo); Conversion impliedExplicitConversion; switch (oppositeConversion.Kind) { case ConversionKind.Identity: impliedExplicitConversion = Conversion.Identity; break; case ConversionKind.ImplicitNumeric: impliedExplicitConversion = Conversion.ExplicitNumeric; break; case ConversionKind.ImplicitReference: impliedExplicitConversion = Conversion.ExplicitReference; break; case ConversionKind.Boxing: impliedExplicitConversion = Conversion.Unboxing; break; case ConversionKind.NoConversion: impliedExplicitConversion = Conversion.NoConversion; break; case ConversionKind.ImplicitPointerToVoid: impliedExplicitConversion = Conversion.PointerToPointer; break; case ConversionKind.ImplicitTuple: // only implicit tuple conversions are standard conversions, // having implicit conversion in the other direction does not help here. impliedExplicitConversion = Conversion.NoConversion; break; case ConversionKind.ImplicitNullable: var strippedSource = source.StrippedType(); var strippedDestination = destination.StrippedType(); var underlyingConversion = DeriveStandardExplicitFromOppositeStandardImplicitConversion(strippedSource, strippedDestination, ref useSiteInfo); // the opposite underlying conversion may not exist // for example if underlying conversion is implicit tuple impliedExplicitConversion = underlyingConversion.Exists ? Conversion.MakeNullableConversion(ConversionKind.ExplicitNullable, underlyingConversion) : Conversion.NoConversion; break; default: throw ExceptionUtilities.UnexpectedValue(oppositeConversion.Kind); } return impliedExplicitConversion; } /// <summary> /// IsBaseInterface returns true if baseType is on the base interface list of derivedType or /// any base class of derivedType. It may be on the base interface list either directly or /// indirectly. /// * baseType must be an interface. /// * type parameters do not have base interfaces. (They have an "effective interface list".) /// * an interface is not a base of itself. /// * this does not check for variance conversions; if a type inherits from /// IEnumerable&lt;string> then IEnumerable&lt;object> is not a base interface. /// </summary> public bool IsBaseInterface(TypeSymbol baseType, TypeSymbol derivedType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)baseType != null); Debug.Assert((object)derivedType != null); if (!baseType.IsInterfaceType()) { return false; } var d = derivedType as NamedTypeSymbol; if ((object)d == null) { return false; } foreach (var iface in d.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(iface, baseType)) { return true; } } return false; } // IsBaseClass returns true if and only if baseType is a base class of derivedType, period. // // * interfaces do not have base classes. (Structs, enums and classes other than object do.) // * a class is not a base class of itself // * type parameters do not have base classes. (They have "effective base classes".) // * all base classes must be classes // * dynamics are removed; if we have class D : B<dynamic> then B<object> is a // base class of D. However, dynamic is never a base class of anything. public bool IsBaseClass(TypeSymbol derivedType, TypeSymbol baseType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)derivedType != null); Debug.Assert((object)baseType != null); // A base class has got to be a class. The derived type might be a struct, enum, or delegate. if (!baseType.IsClassType()) { return false; } for (TypeSymbol b = derivedType.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); (object)b != null; b = b.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(b, baseType)) { return true; } } return false; } /// <summary> /// returns true when implicit conversion is not necessarily the same as explicit conversion /// </summary> private static bool ExplicitConversionMayDifferFromImplicit(Conversion implicitConversion) { switch (implicitConversion.Kind) { case ConversionKind.ImplicitUserDefined: case ConversionKind.ImplicitDynamic: case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitTupleLiteral: case ConversionKind.ImplicitNullable: case ConversionKind.ConditionalExpression: return true; default: return false; } } private Conversion ClassifyImplicitBuiltInConversionFromExpression(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert(sourceExpression == null || (object)sourceExpression.Type == (object)source); Debug.Assert((object)destination != null); if (HasImplicitDynamicConversionFromExpression(source, destination)) { return Conversion.ImplicitDynamic; } // The following conversions only exist for certain form of expressions, // if we have no expression none if them is applicable. if (sourceExpression == null) { return Conversion.NoConversion; } if (HasImplicitEnumerationConversion(sourceExpression, destination)) { return Conversion.ImplicitEnumeration; } var constantConversion = ClassifyImplicitConstantExpressionConversion(sourceExpression, destination); if (constantConversion.Exists) { return constantConversion; } switch (sourceExpression.Kind) { case BoundKind.Literal: var nullLiteralConversion = ClassifyNullLiteralConversion(sourceExpression, destination); if (nullLiteralConversion.Exists) { return nullLiteralConversion; } break; case BoundKind.DefaultLiteral: return Conversion.DefaultLiteral; case BoundKind.ExpressionWithNullability: { var innerExpression = ((BoundExpressionWithNullability)sourceExpression).Expression; var innerConversion = ClassifyImplicitBuiltInConversionFromExpression(innerExpression, innerExpression.Type, destination, ref useSiteInfo); if (innerConversion.Exists) { return innerConversion; } break; } case BoundKind.TupleLiteral: var tupleConversion = ClassifyImplicitTupleLiteralConversion((BoundTupleLiteral)sourceExpression, destination, ref useSiteInfo); if (tupleConversion.Exists) { return tupleConversion; } break; case BoundKind.UnboundLambda: if (HasAnonymousFunctionConversion(sourceExpression, destination)) { return Conversion.AnonymousFunction; } break; case BoundKind.MethodGroup: Conversion methodGroupConversion = GetMethodGroupDelegateConversion((BoundMethodGroup)sourceExpression, destination, ref useSiteInfo); if (methodGroupConversion.Exists) { return methodGroupConversion; } break; case BoundKind.UnconvertedInterpolatedString: case BoundKind.BinaryOperator when ((BoundBinaryOperator)sourceExpression).IsUnconvertedInterpolatedStringAddition: Conversion interpolatedStringConversion = GetInterpolatedStringConversion(sourceExpression, destination, ref useSiteInfo); if (interpolatedStringConversion.Exists) { return interpolatedStringConversion; } break; case BoundKind.StackAllocArrayCreation: var stackAllocConversion = GetStackAllocConversion((BoundStackAllocArrayCreation)sourceExpression, destination, ref useSiteInfo); if (stackAllocConversion.Exists) { return stackAllocConversion; } break; case BoundKind.UnconvertedAddressOfOperator when destination is FunctionPointerTypeSymbol funcPtrType: var addressOfConversion = GetMethodGroupFunctionPointerConversion(((BoundUnconvertedAddressOfOperator)sourceExpression).Operand, funcPtrType, ref useSiteInfo); if (addressOfConversion.Exists) { return addressOfConversion; } break; case BoundKind.ThrowExpression: return Conversion.ImplicitThrow; case BoundKind.UnconvertedObjectCreationExpression: return Conversion.ObjectCreation; } return Conversion.NoConversion; } private Conversion GetSwitchExpressionConversion(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (source) { case BoundConvertedSwitchExpression _: // It has already been subjected to a switch expression conversion. return Conversion.NoConversion; case BoundUnconvertedSwitchExpression switchExpression: var innerConversions = ArrayBuilder<Conversion>.GetInstance(switchExpression.SwitchArms.Length); foreach (var arm in switchExpression.SwitchArms) { var nestedConversion = this.ClassifyImplicitConversionFromExpression(arm.Value, destination, ref useSiteInfo); if (!nestedConversion.Exists) { innerConversions.Free(); return Conversion.NoConversion; } innerConversions.Add(nestedConversion); } return Conversion.MakeSwitchExpression(innerConversions.ToImmutableAndFree()); default: return Conversion.NoConversion; } } private Conversion GetConditionalExpressionConversion(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!(source is BoundUnconvertedConditionalOperator conditionalOperator)) return Conversion.NoConversion; var trueConversion = this.ClassifyImplicitConversionFromExpression(conditionalOperator.Consequence, destination, ref useSiteInfo); if (!trueConversion.Exists) return Conversion.NoConversion; var falseConversion = this.ClassifyImplicitConversionFromExpression(conditionalOperator.Alternative, destination, ref useSiteInfo); if (!falseConversion.Exists) return Conversion.NoConversion; return Conversion.MakeConditionalExpression(ImmutableArray.Create(trueConversion, falseConversion)); } private static Conversion ClassifyNullLiteralConversion(BoundExpression source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!source.IsLiteralNull()) { return Conversion.NoConversion; } // SPEC: An implicit conversion exists from the null literal to any nullable type. if (destination.IsNullableType()) { // The spec defines a "null literal conversion" specifically as a conversion from // null to nullable type. return Conversion.NullLiteral; } // SPEC: An implicit conversion exists from the null literal to any reference type. // SPEC: An implicit conversion exists from the null literal to type parameter T, // SPEC: provided T is known to be a reference type. [...] The conversion [is] classified // SPEC: as implicit reference conversion. if (destination.IsReferenceType) { return Conversion.ImplicitReference; } // SPEC: The set of implicit conversions is extended to include... // SPEC: ... from the null literal to any pointer type. if (destination.IsPointerOrFunctionPointer()) { return Conversion.NullToPointer; } return Conversion.NoConversion; } private static Conversion ClassifyImplicitConstantExpressionConversion(BoundExpression source, TypeSymbol destination) { if (HasImplicitConstantExpressionConversion(source, destination)) { return Conversion.ImplicitConstant; } // strip nullable from the destination // // the following should work and it is an ImplicitNullable conversion // int? x = 1; if (destination.Kind == SymbolKind.NamedType) { var nt = (NamedTypeSymbol)destination; if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T && HasImplicitConstantExpressionConversion(source, nt.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type)) { return new Conversion(ConversionKind.ImplicitNullable, Conversion.ImplicitConstantUnderlying); } } return Conversion.NoConversion; } private Conversion ClassifyImplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var tupleConversion = GetImplicitTupleLiteralConversion(source, destination, ref useSiteInfo); if (tupleConversion.Exists) { return tupleConversion; } // strip nullable from the destination // // the following should work and it is an ImplicitNullable conversion // (int, double)? x = (1,2); if (destination.Kind == SymbolKind.NamedType) { var nt = (NamedTypeSymbol)destination; if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T) { var underlyingTupleConversion = GetImplicitTupleLiteralConversion(source, nt.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type, ref useSiteInfo); if (underlyingTupleConversion.Exists) { return new Conversion(ConversionKind.ImplicitNullable, ImmutableArray.Create(underlyingTupleConversion)); } } } return Conversion.NoConversion; } private Conversion ClassifyExplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { var tupleConversion = GetExplicitTupleLiteralConversion(source, destination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return tupleConversion; } // strip nullable from the destination // // the following should work and it is an ExplicitNullable conversion // var x = ((byte, string)?)(1,null); if (destination.Kind == SymbolKind.NamedType) { var nt = (NamedTypeSymbol)destination; if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T) { var underlyingTupleConversion = GetExplicitTupleLiteralConversion(source, nt.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type, ref useSiteInfo, forCast); if (underlyingTupleConversion.Exists) { return new Conversion(ConversionKind.ExplicitNullable, ImmutableArray.Create(underlyingTupleConversion)); } } } return Conversion.NoConversion; } internal static bool HasImplicitConstantExpressionConversion(BoundExpression source, TypeSymbol destination) { var constantValue = source.ConstantValue; if (constantValue == null || (object)source.Type == null) { return false; } // An implicit constant expression conversion permits the following conversions: // A constant-expression of type int can be converted to type sbyte, byte, short, // ushort, uint, or ulong, provided the value of the constant-expression is within the // range of the destination type. var specialSource = source.Type.GetSpecialTypeSafe(); if (specialSource == SpecialType.System_Int32) { //if the constant value could not be computed, be generous and assume the conversion will work int value = constantValue.IsBad ? 0 : constantValue.Int32Value; switch (destination.GetSpecialTypeSafe()) { case SpecialType.System_Byte: return byte.MinValue <= value && value <= byte.MaxValue; case SpecialType.System_SByte: return sbyte.MinValue <= value && value <= sbyte.MaxValue; case SpecialType.System_Int16: return short.MinValue <= value && value <= short.MaxValue; case SpecialType.System_IntPtr when destination.IsNativeIntegerType: return true; case SpecialType.System_UInt32: case SpecialType.System_UIntPtr when destination.IsNativeIntegerType: return uint.MinValue <= value; case SpecialType.System_UInt64: return (int)ulong.MinValue <= value; case SpecialType.System_UInt16: return ushort.MinValue <= value && value <= ushort.MaxValue; default: return false; } } else if (specialSource == SpecialType.System_Int64 && destination.GetSpecialTypeSafe() == SpecialType.System_UInt64 && (constantValue.IsBad || 0 <= constantValue.Int64Value)) { // A constant-expression of type long can be converted to type ulong, provided the // value of the constant-expression is not negative. return true; } return false; } private Conversion ClassifyExplicitOnlyConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { Debug.Assert(sourceExpression != null); Debug.Assert((object)destination != null); var sourceType = sourceExpression.Type; // NB: need to check for explicit tuple literal conversion before checking for explicit conversion from type // The same literal may have both explicit tuple conversion and explicit tuple literal conversion to the target type. // They are, however, observably different conversions via the order of argument evaluations and element-wise conversions if (sourceExpression.Kind == BoundKind.TupleLiteral) { Conversion tupleConversion = ClassifyExplicitTupleLiteralConversion((BoundTupleLiteral)sourceExpression, destination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return tupleConversion; } } if ((object)sourceType != null) { // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(sourceType, destination); if (fastConversion.Exists) { return fastConversion; } else { var conversion = ClassifyExplicitBuiltInOnlyConversion(sourceType, destination, ref useSiteInfo, forCast); if (conversion.Exists) { return conversion; } } } return GetExplicitUserDefinedConversion(sourceExpression, sourceType, destination, ref useSiteInfo); } #nullable enable private static bool HasImplicitEnumerationConversion(BoundExpression source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: An implicit enumeration conversion permits the decimal-integer-literal 0 to be converted to any enum-type // SPEC: and to any nullable-type whose underlying type is an enum-type. // // For historical reasons we actually allow a conversion from any *numeric constant // zero* to be converted to any enum type, not just the literal integer zero. bool validType = destination.IsEnumType() || destination.IsNullableType() && destination.GetNullableUnderlyingType().IsEnumType(); if (!validType) { return false; } var sourceConstantValue = source.ConstantValue; return sourceConstantValue != null && source.Type is object && IsNumericType(source.Type) && IsConstantNumericZero(sourceConstantValue); } private static LambdaConversionResult IsAnonymousFunctionCompatibleWithDelegate(UnboundLambda anonymousFunction, TypeSymbol type, bool isTargetExpressionTree) { Debug.Assert((object)anonymousFunction != null); Debug.Assert((object)type != null); // SPEC: An anonymous-method-expression or lambda-expression is classified as an anonymous function. // SPEC: The expression does not have a type but can be implicitly converted to a compatible delegate // SPEC: type or expression tree type. Specifically, a delegate type D is compatible with an // SPEC: anonymous function F provided: var delegateType = (NamedTypeSymbol)type; var invokeMethod = delegateType.DelegateInvokeMethod; if ((object)invokeMethod == null || invokeMethod.HasUseSiteError) { return LambdaConversionResult.BadTargetType; } if (anonymousFunction.HasExplicitReturnType(out var refKind, out var returnType)) { if (invokeMethod.RefKind != refKind || !invokeMethod.ReturnType.Equals(returnType.Type, TypeCompareKind.AllIgnoreOptions)) { return LambdaConversionResult.MismatchedReturnType; } } var delegateParameters = invokeMethod.Parameters; // SPEC: If F contains an anonymous-function-signature, then D and F have the same number of parameters. // SPEC: If F does not contain an anonymous-function-signature, then D may have zero or more parameters // SPEC: of any type, as long as no parameter of D has the out parameter modifier. if (anonymousFunction.HasSignature) { if (anonymousFunction.ParameterCount != invokeMethod.ParameterCount) { return LambdaConversionResult.BadParameterCount; } // SPEC: If F has an explicitly typed parameter list, each parameter in D has the same type // SPEC: and modifiers as the corresponding parameter in F. // SPEC: If F has an implicitly typed parameter list, D has no ref or out parameters. if (anonymousFunction.HasExplicitlyTypedParameterList) { for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].RefKind != anonymousFunction.RefKind(p) || !delegateParameters[p].Type.Equals(anonymousFunction.ParameterType(p), TypeCompareKind.AllIgnoreOptions)) { return LambdaConversionResult.MismatchedParameterType; } } } else { for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].RefKind != RefKind.None) { return LambdaConversionResult.RefInImplicitlyTypedLambda; } } // In C# it is not possible to make a delegate type // such that one of its parameter types is a static type. But static types are // in metadata just sealed abstract types; there is nothing stopping someone in // another language from creating a delegate with a static type for a parameter, // though the only argument you could pass for that parameter is null. // // In the native compiler we forbid conversion of an anonymous function that has // an implicitly-typed parameter list to a delegate type that has a static type // for a formal parameter type. However, we do *not* forbid it for an explicitly- // typed lambda (because we already require that the explicitly typed parameter not // be static) and we do not forbid it for an anonymous method with the entire // parameter list missing (because the body cannot possibly have a parameter that // is of static type, even though this means that we will be generating a hidden // method with a parameter of static type.) // // We also allow more exotic situations to work in the native compiler. For example, // though it is not possible to convert x=>{} to Action<GC>, it is possible to convert // it to Action<List<GC>> should there be a language that allows you to construct // a variable of that type. // // We might consider beefing up this rule to disallow a conversion of *any* anonymous // function to *any* delegate that has a static type *anywhere* in the parameter list. for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].TypeWithAnnotations.IsStatic) { return LambdaConversionResult.StaticTypeInImplicitlyTypedLambda; } } } } else { for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].RefKind == RefKind.Out) { return LambdaConversionResult.MissingSignatureWithOutParameter; } } } // Ensure the body can be converted to that delegate type var bound = anonymousFunction.Bind(delegateType, isTargetExpressionTree); if (ErrorFacts.PreventsSuccessfulDelegateConversion(bound.Diagnostics.Diagnostics)) { return LambdaConversionResult.BindingFailed; } return LambdaConversionResult.Success; } private static LambdaConversionResult IsAnonymousFunctionCompatibleWithExpressionTree(UnboundLambda anonymousFunction, NamedTypeSymbol type) { Debug.Assert((object)anonymousFunction != null); Debug.Assert((object)type != null); Debug.Assert(type.IsGenericOrNonGenericExpressionType(out _)); // SPEC OMISSION: // // The C# 3 spec said that anonymous methods and statement lambdas are *convertible* to expression tree // types if the anonymous method/statement lambda is convertible to its delegate type; however, actually // *using* such a conversion is an error. However, that is not what we implemented. In C# 3 we implemented // that an anonymous method is *not convertible* to an expression tree type, period. (Statement lambdas // used the rule described in the spec.) // // This appears to be a spec omission; the intention is to make old-style anonymous methods not // convertible to expression trees. var delegateType = type.Arity == 0 ? null : type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type; if (delegateType is { } && !delegateType.IsDelegateType()) { return LambdaConversionResult.ExpressionTreeMustHaveDelegateTypeArgument; } if (anonymousFunction.Syntax.Kind() == SyntaxKind.AnonymousMethodExpression) { return LambdaConversionResult.ExpressionTreeFromAnonymousMethod; } if (delegateType is null) { Debug.Assert(IsFeatureInferredDelegateTypeEnabled(anonymousFunction)); return GetInferredDelegateTypeResult(anonymousFunction); } return IsAnonymousFunctionCompatibleWithDelegate(anonymousFunction, delegateType, isTargetExpressionTree: true); } public static LambdaConversionResult IsAnonymousFunctionCompatibleWithType(UnboundLambda anonymousFunction, TypeSymbol type) { Debug.Assert((object)anonymousFunction != null); Debug.Assert((object)type != null); if (type.SpecialType == SpecialType.System_Delegate) { if (IsFeatureInferredDelegateTypeEnabled(anonymousFunction)) { return GetInferredDelegateTypeResult(anonymousFunction); } } else if (type.IsDelegateType()) { return IsAnonymousFunctionCompatibleWithDelegate(anonymousFunction, type, isTargetExpressionTree: false); } else if (type.IsGenericOrNonGenericExpressionType(out bool isGenericType)) { if (isGenericType || IsFeatureInferredDelegateTypeEnabled(anonymousFunction)) { return IsAnonymousFunctionCompatibleWithExpressionTree(anonymousFunction, (NamedTypeSymbol)type); } } return LambdaConversionResult.BadTargetType; } internal static bool IsFeatureInferredDelegateTypeEnabled(BoundExpression expr) { return expr.Syntax.IsFeatureEnabled(MessageID.IDS_FeatureInferredDelegateType); } private static LambdaConversionResult GetInferredDelegateTypeResult(UnboundLambda anonymousFunction) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return anonymousFunction.InferDelegateType(ref discardedUseSiteInfo) is null ? LambdaConversionResult.CannotInferDelegateType : LambdaConversionResult.Success; } private static bool HasAnonymousFunctionConversion(BoundExpression source, TypeSymbol destination) { Debug.Assert(source != null); Debug.Assert((object)destination != null); if (source.Kind != BoundKind.UnboundLambda) { return false; } return IsAnonymousFunctionCompatibleWithType((UnboundLambda)source, destination) == LambdaConversionResult.Success; } #nullable disable internal Conversion ClassifyImplicitUserDefinedConversionForV6SwitchGoverningType(TypeSymbol sourceType, out TypeSymbol switchGoverningType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The governing type of a switch statement is established by the switch expression. // SPEC: 1) If the type of the switch expression is sbyte, byte, short, ushort, int, uint, // SPEC: long, ulong, bool, char, string, or an enum-type, or if it is the nullable type // SPEC: corresponding to one of these types, then that is the governing type of the switch statement. // SPEC: 2) Otherwise, exactly one user-defined implicit conversion (§6.4) must exist from the // SPEC: type of the switch expression to one of the following possible governing types: // SPEC: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type // SPEC: corresponding to one of those types // NOTE: We should be called only if (1) is false for source type. Debug.Assert((object)sourceType != null); Debug.Assert(!sourceType.IsValidV6SwitchGoverningType()); UserDefinedConversionResult result = AnalyzeImplicitUserDefinedConversionForV6SwitchGoverningType(sourceType, ref useSiteInfo); if (result.Kind == UserDefinedConversionResultKind.Valid) { UserDefinedConversionAnalysis analysis = result.Results[result.Best]; switchGoverningType = analysis.ToType; Debug.Assert(switchGoverningType.IsValidV6SwitchGoverningType(isTargetTypeOfUserDefinedOp: true)); } else { switchGoverningType = null; } return new Conversion(result, isImplicit: true); } internal Conversion GetCallerLineNumberConversion(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var greenNode = new Syntax.InternalSyntax.LiteralExpressionSyntax(SyntaxKind.NumericLiteralExpression, new Syntax.InternalSyntax.SyntaxToken(SyntaxKind.NumericLiteralToken)); var syntaxNode = new LiteralExpressionSyntax(greenNode, null, 0); TypeSymbol expectedAttributeType = corLibrary.GetSpecialType(SpecialType.System_Int32); BoundLiteral intMaxValueLiteral = new BoundLiteral(syntaxNode, ConstantValue.Create(int.MaxValue), expectedAttributeType); return ClassifyStandardImplicitConversion(intMaxValueLiteral, expectedAttributeType, destination, ref useSiteInfo); } internal bool HasCallerLineNumberConversion(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return GetCallerLineNumberConversion(destination, ref useSiteInfo).Exists; } internal bool HasCallerInfoStringConversion(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { TypeSymbol expectedAttributeType = corLibrary.GetSpecialType(SpecialType.System_String); Conversion conversion = ClassifyStandardImplicitConversion(expectedAttributeType, destination, ref useSiteInfo); return conversion.Exists; } public static bool HasIdentityConversion(TypeSymbol type1, TypeSymbol type2) { return HasIdentityConversionInternal(type1, type2, includeNullability: false); } private static bool HasIdentityConversionInternal(TypeSymbol type1, TypeSymbol type2, bool includeNullability) { // Spec (6.1.1): // An identity conversion converts from any type to the same type. This conversion exists // such that an entity that already has a required type can be said to be convertible to // that type. // // Because object and dynamic are considered equivalent there is an identity conversion // between object and dynamic, and between constructed types that are the same when replacing // all occurrences of dynamic with object. Debug.Assert((object)type1 != null); Debug.Assert((object)type2 != null); // Note, when we are paying attention to nullability, we ignore oblivious mismatch. // See TypeCompareKind.ObliviousNullableModifierMatchesAny var compareKind = includeNullability ? TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes : TypeCompareKind.AllIgnoreOptions; return type1.Equals(type2, compareKind); } private bool HasIdentityConversionInternal(TypeSymbol type1, TypeSymbol type2) { return HasIdentityConversionInternal(type1, type2, IncludeNullability); } /// <summary> /// Returns true if: /// - Either type has no nullability information (oblivious). /// - Both types cannot have different nullability at the same time, /// including the case of type parameters that by themselves can represent nullable and not nullable reference types. /// </summary> internal bool HasTopLevelNullabilityIdentityConversion(TypeWithAnnotations source, TypeWithAnnotations destination) { if (!IncludeNullability) { return true; } if (source.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsOblivious()) { return true; } var sourceIsPossiblyNullableTypeParameter = IsPossiblyNullableTypeTypeParameter(source); var destinationIsPossiblyNullableTypeParameter = IsPossiblyNullableTypeTypeParameter(destination); if (sourceIsPossiblyNullableTypeParameter && !destinationIsPossiblyNullableTypeParameter) { return destination.NullableAnnotation.IsAnnotated(); } if (destinationIsPossiblyNullableTypeParameter && !sourceIsPossiblyNullableTypeParameter) { return source.NullableAnnotation.IsAnnotated(); } return source.NullableAnnotation.IsAnnotated() == destination.NullableAnnotation.IsAnnotated(); } /// <summary> /// Returns false if source type can be nullable at the same time when destination type can be not nullable, /// including the case of type parameters that by themselves can represent nullable and not nullable reference types. /// When either type has no nullability information (oblivious), this method returns true. /// </summary> internal bool HasTopLevelNullabilityImplicitConversion(TypeWithAnnotations source, TypeWithAnnotations destination) { if (!IncludeNullability) { return true; } if (source.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsAnnotated()) { return true; } if (IsPossiblyNullableTypeTypeParameter(source) && !IsPossiblyNullableTypeTypeParameter(destination)) { return false; } return !source.NullableAnnotation.IsAnnotated(); } private static bool IsPossiblyNullableTypeTypeParameter(in TypeWithAnnotations typeWithAnnotations) { var type = typeWithAnnotations.Type; return type is object && (type.IsPossiblyNullableReferenceTypeTypeParameter() || type.IsNullableTypeOrTypeParameter()); } /// <summary> /// Returns false if the source does not have an implicit conversion to the destination /// because of either incompatible top level or nested nullability. /// </summary> public bool HasAnyNullabilityImplicitConversion(TypeWithAnnotations source, TypeWithAnnotations destination) { Debug.Assert(IncludeNullability); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return HasTopLevelNullabilityImplicitConversion(source, destination) && ClassifyImplicitConversionFromType(source.Type, destination.Type, ref discardedUseSiteInfo).Kind != ConversionKind.NoConversion; } public static bool HasIdentityConversionToAny<T>(T type, ArrayBuilder<T> targetTypes) where T : TypeSymbol { foreach (var targetType in targetTypes) { if (HasIdentityConversionInternal(type, targetType, includeNullability: false)) { return true; } } return false; } public Conversion ConvertExtensionMethodThisArg(TypeSymbol parameterType, TypeSymbol thisType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)thisType != null); var conversion = this.ClassifyImplicitExtensionMethodThisArgConversion(null, thisType, parameterType, ref useSiteInfo); return IsValidExtensionMethodThisArgConversion(conversion) ? conversion : Conversion.NoConversion; } // Spec 7.6.5.2: "An extension method ... is eligible if ... [an] implicit identity, reference, // or boxing conversion exists from expr to the type of the first parameter" public Conversion ClassifyImplicitExtensionMethodThisArgConversion(BoundExpression sourceExpressionOpt, TypeSymbol sourceType, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpressionOpt == null || (object)sourceExpressionOpt.Type == sourceType); Debug.Assert((object)destination != null); if ((object)sourceType != null) { if (HasIdentityConversionInternal(sourceType, destination)) { return Conversion.Identity; } if (HasBoxingConversion(sourceType, destination, ref useSiteInfo)) { return Conversion.Boxing; } if (HasImplicitReferenceConversion(sourceType, destination, ref useSiteInfo)) { return Conversion.ImplicitReference; } } if (sourceExpressionOpt?.Kind == BoundKind.TupleLiteral) { // GetTupleLiteralConversion is not used with IncludeNullability currently. // If that changes, the delegate below will need to consider top-level nullability. Debug.Assert(!IncludeNullability); var tupleConversion = GetTupleLiteralConversion( (BoundTupleLiteral)sourceExpressionOpt, destination, ref useSiteInfo, ConversionKind.ImplicitTupleLiteral, (ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => conversions.ClassifyImplicitExtensionMethodThisArgConversion(s, s.Type, d.Type, ref u), arg: false); if (tupleConversion.Exists) { return tupleConversion; } } if ((object)sourceType != null) { var tupleConversion = ClassifyTupleConversion( sourceType, destination, ref useSiteInfo, ConversionKind.ImplicitTuple, (ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => { if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) { return Conversion.NoConversion; } return conversions.ClassifyImplicitExtensionMethodThisArgConversion(null, s.Type, d.Type, ref u); }, arg: false); if (tupleConversion.Exists) { return tupleConversion; } } return Conversion.NoConversion; } // It should be possible to remove IsValidExtensionMethodThisArgConversion // since ClassifyImplicitExtensionMethodThisArgConversion should only // return valid conversions. https://github.com/dotnet/roslyn/issues/19622 // Spec 7.6.5.2: "An extension method ... is eligible if ... [an] implicit identity, reference, // or boxing conversion exists from expr to the type of the first parameter" public static bool IsValidExtensionMethodThisArgConversion(Conversion conversion) { switch (conversion.Kind) { case ConversionKind.Identity: case ConversionKind.Boxing: case ConversionKind.ImplicitReference: return true; case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitTupleLiteral: // check if all element conversions satisfy the requirement foreach (var elementConversion in conversion.UnderlyingConversions) { if (!IsValidExtensionMethodThisArgConversion(elementConversion)) { return false; } } return true; default: // Caller should have not have calculated another conversion. Debug.Assert(conversion.Kind == ConversionKind.NoConversion); return false; } } private const bool F = false; private const bool T = true; // Notice that there is no implicit numeric conversion from a type to itself. That's an // identity conversion. private static readonly bool[,] s_implicitNumericConversions = { // to sb b s us i ui l ul c f d m // from /* sb */ { F, F, T, F, T, F, T, F, F, T, T, T }, /* b */ { F, F, T, T, T, T, T, T, F, T, T, T }, /* s */ { F, F, F, F, T, F, T, F, F, T, T, T }, /* us */ { F, F, F, F, T, T, T, T, F, T, T, T }, /* i */ { F, F, F, F, F, F, T, F, F, T, T, T }, /* ui */ { F, F, F, F, F, F, T, T, F, T, T, T }, /* l */ { F, F, F, F, F, F, F, F, F, T, T, T }, /* ul */ { F, F, F, F, F, F, F, F, F, T, T, T }, /* c */ { F, F, F, T, T, T, T, T, F, T, T, T }, /* f */ { F, F, F, F, F, F, F, F, F, F, T, F }, /* d */ { F, F, F, F, F, F, F, F, F, F, F, F }, /* m */ { F, F, F, F, F, F, F, F, F, F, F, F } }; private static readonly bool[,] s_explicitNumericConversions = { // to sb b s us i ui l ul c f d m // from /* sb */ { F, T, F, T, F, T, F, T, T, F, F, F }, /* b */ { T, F, F, F, F, F, F, F, T, F, F, F }, /* s */ { T, T, F, T, F, T, F, T, T, F, F, F }, /* us */ { T, T, T, F, F, F, F, F, T, F, F, F }, /* i */ { T, T, T, T, F, T, F, T, T, F, F, F }, /* ui */ { T, T, T, T, T, F, F, F, T, F, F, F }, /* l */ { T, T, T, T, T, T, F, T, T, F, F, F }, /* ul */ { T, T, T, T, T, T, T, F, T, F, F, F }, /* c */ { T, T, T, F, F, F, F, F, F, F, F, F }, /* f */ { T, T, T, T, T, T, T, T, T, F, F, T }, /* d */ { T, T, T, T, T, T, T, T, T, T, F, T }, /* m */ { T, T, T, T, T, T, T, T, T, T, T, F } }; private static int GetNumericTypeIndex(SpecialType specialType) { switch (specialType) { case SpecialType.System_SByte: return 0; case SpecialType.System_Byte: return 1; case SpecialType.System_Int16: return 2; case SpecialType.System_UInt16: return 3; case SpecialType.System_Int32: return 4; case SpecialType.System_UInt32: return 5; case SpecialType.System_Int64: return 6; case SpecialType.System_UInt64: return 7; case SpecialType.System_Char: return 8; case SpecialType.System_Single: return 9; case SpecialType.System_Double: return 10; case SpecialType.System_Decimal: return 11; default: return -1; } } #nullable enable private static bool HasImplicitNumericConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); int sourceIndex = GetNumericTypeIndex(source.SpecialType); if (sourceIndex < 0) { return false; } int destinationIndex = GetNumericTypeIndex(destination.SpecialType); if (destinationIndex < 0) { return false; } return s_implicitNumericConversions[sourceIndex, destinationIndex]; } private static bool HasExplicitNumericConversion(TypeSymbol source, TypeSymbol destination) { // SPEC: The explicit numeric conversions are the conversions from a numeric-type to another // SPEC: numeric-type for which an implicit numeric conversion does not already exist. Debug.Assert((object)source != null); Debug.Assert((object)destination != null); int sourceIndex = GetNumericTypeIndex(source.SpecialType); if (sourceIndex < 0) { return false; } int destinationIndex = GetNumericTypeIndex(destination.SpecialType); if (destinationIndex < 0) { return false; } return s_explicitNumericConversions[sourceIndex, destinationIndex]; } private static bool IsConstantNumericZero(ConstantValue value) { switch (value.Discriminator) { case ConstantValueTypeDiscriminator.SByte: return value.SByteValue == 0; case ConstantValueTypeDiscriminator.Byte: return value.ByteValue == 0; case ConstantValueTypeDiscriminator.Int16: return value.Int16Value == 0; case ConstantValueTypeDiscriminator.Int32: case ConstantValueTypeDiscriminator.NInt: return value.Int32Value == 0; case ConstantValueTypeDiscriminator.Int64: return value.Int64Value == 0; case ConstantValueTypeDiscriminator.UInt16: return value.UInt16Value == 0; case ConstantValueTypeDiscriminator.UInt32: case ConstantValueTypeDiscriminator.NUInt: return value.UInt32Value == 0; case ConstantValueTypeDiscriminator.UInt64: return value.UInt64Value == 0; case ConstantValueTypeDiscriminator.Single: case ConstantValueTypeDiscriminator.Double: return value.DoubleValue == 0; case ConstantValueTypeDiscriminator.Decimal: return value.DecimalValue == 0; } return false; } private static bool IsNumericType(TypeSymbol type) { switch (type.SpecialType) { case SpecialType.System_Char: case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: case SpecialType.System_IntPtr when type.IsNativeIntegerType: case SpecialType.System_UIntPtr when type.IsNativeIntegerType: return true; default: return false; } } private static bool HasSpecialIntPtrConversion(TypeSymbol source, TypeSymbol target) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); // There are only a total of twelve user-defined explicit conversions on IntPtr and UIntPtr: // // IntPtr <---> int // IntPtr <---> long // IntPtr <---> void* // UIntPtr <---> uint // UIntPtr <---> ulong // UIntPtr <---> void* // // The specification says that you can put any *standard* implicit or explicit conversion // on "either side" of a user-defined explicit conversion, so the specification allows, say, // UIntPtr --> byte because the conversion UIntPtr --> uint is user-defined and the // conversion uint --> byte is "standard". It is "standard" because the conversion // byte --> uint is an implicit numeric conversion. // This means that certain conversions should be illegal. For example, IntPtr --> ulong // should be illegal because none of int --> ulong, long --> ulong and void* --> ulong // are "standard" conversions. // Similarly, some conversions involving IntPtr should be illegal because they are // ambiguous. byte --> IntPtr?, for example, is ambiguous. (There are four possible // UD operators: int --> IntPtr and long --> IntPtr, and their lifted versions. The // best possible source type is int, the best possible target type is IntPtr?, and // there is an ambiguity between the unlifted int --> IntPtr, and the lifted // int? --> IntPtr? conversions.) // In practice, the native compiler, and hence, the Roslyn compiler, allows all // these conversions. Any conversion from a numeric type to IntPtr, or from an IntPtr // to a numeric type, is allowed. Also, any conversion from a pointer type to IntPtr // or vice versa is allowed. var s0 = source.StrippedType(); var t0 = target.StrippedType(); TypeSymbol otherType; if (isIntPtrOrUIntPtr(s0)) { otherType = t0; } else if (isIntPtrOrUIntPtr(t0)) { otherType = s0; } else { return false; } if (otherType.IsPointerOrFunctionPointer()) { return true; } if (otherType.TypeKind == TypeKind.Enum) { return true; } switch (otherType.SpecialType) { case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Char: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Double: case SpecialType.System_Single: case SpecialType.System_Decimal: return true; } return false; static bool isIntPtrOrUIntPtr(TypeSymbol type) => (type.SpecialType == SpecialType.System_IntPtr || type.SpecialType == SpecialType.System_UIntPtr) && !type.IsNativeIntegerType; } private static bool HasExplicitEnumerationConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: The explicit enumeration conversions are: // SPEC: From sbyte, byte, short, ushort, int, uint, long, ulong, nint, nuint, char, float, double, or decimal to any enum-type. // SPEC: From any enum-type to sbyte, byte, short, ushort, int, uint, long, ulong, nint, nuint, char, float, double, or decimal. // SPEC: From any enum-type to any other enum-type. if (IsNumericType(source) && destination.IsEnumType()) { return true; } if (IsNumericType(destination) && source.IsEnumType()) { return true; } if (source.IsEnumType() && destination.IsEnumType()) { return true; } return false; } #nullable disable private Conversion ClassifyImplicitNullableConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: Predefined implicit conversions that operate on non-nullable value types can also be used with // SPEC: nullable forms of those types. For each of the predefined implicit identity, numeric and tuple conversions // SPEC: that convert from a non-nullable value type S to a non-nullable value type T, the following implicit // SPEC: nullable conversions exist: // SPEC: * An implicit conversion from S? to T?. // SPEC: * An implicit conversion from S to T?. if (!destination.IsNullableType()) { return Conversion.NoConversion; } TypeSymbol unwrappedDestination = destination.GetNullableUnderlyingType(); TypeSymbol unwrappedSource = source.StrippedType(); if (!unwrappedSource.IsValueType) { return Conversion.NoConversion; } if (HasIdentityConversionInternal(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ImplicitNullable, Conversion.IdentityUnderlying); } if (HasImplicitNumericConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ImplicitNullable, Conversion.ImplicitNumericUnderlying); } var tupleConversion = ClassifyImplicitTupleConversion(unwrappedSource, unwrappedDestination, ref useSiteInfo); if (tupleConversion.Exists) { return new Conversion(ConversionKind.ImplicitNullable, ImmutableArray.Create(tupleConversion)); } return Conversion.NoConversion; } private delegate Conversion ClassifyConversionFromExpressionDelegate(ConversionsBase conversions, BoundExpression sourceExpression, TypeWithAnnotations destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool arg); private delegate Conversion ClassifyConversionFromTypeDelegate(ConversionsBase conversions, TypeWithAnnotations source, TypeWithAnnotations destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool arg); private Conversion GetImplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // GetTupleLiteralConversion is not used with IncludeNullability currently. // If that changes, the delegate below will need to consider top-level nullability. Debug.Assert(!IncludeNullability); return GetTupleLiteralConversion( source, destination, ref useSiteInfo, ConversionKind.ImplicitTupleLiteral, (ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => conversions.ClassifyImplicitConversionFromExpression(s, d.Type, ref u), arg: false); } private Conversion GetExplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { // GetTupleLiteralConversion is not used with IncludeNullability currently. // If that changes, the delegate below will need to consider top-level nullability. Debug.Assert(!IncludeNullability); return GetTupleLiteralConversion( source, destination, ref useSiteInfo, ConversionKind.ExplicitTupleLiteral, (ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => conversions.ClassifyConversionFromExpression(s, d.Type, ref u, a), forCast); } private Conversion GetTupleLiteralConversion( BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConversionKind kind, ClassifyConversionFromExpressionDelegate classifyConversion, bool arg) { var arguments = source.Arguments; // check if the type is actually compatible type for a tuple of given cardinality if (!destination.IsTupleTypeOfCardinality(arguments.Length)) { return Conversion.NoConversion; } var targetElementTypes = destination.TupleElementTypesWithAnnotations; Debug.Assert(arguments.Length == targetElementTypes.Length); // check arguments against flattened list of target element types var argumentConversions = ArrayBuilder<Conversion>.GetInstance(arguments.Length); for (int i = 0; i < arguments.Length; i++) { var argument = arguments[i]; var result = classifyConversion(this, argument, targetElementTypes[i], ref useSiteInfo, arg); if (!result.Exists) { argumentConversions.Free(); return Conversion.NoConversion; } argumentConversions.Add(result); } return new Conversion(kind, argumentConversions.ToImmutableAndFree()); } private Conversion ClassifyImplicitTupleConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ClassifyTupleConversion( source, destination, ref useSiteInfo, ConversionKind.ImplicitTuple, (ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => { if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) { return Conversion.NoConversion; } return conversions.ClassifyImplicitConversionFromType(s.Type, d.Type, ref u); }, arg: false); } private Conversion ClassifyExplicitTupleConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { return ClassifyTupleConversion( source, destination, ref useSiteInfo, ConversionKind.ExplicitTuple, (ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => { if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) { return Conversion.NoConversion; } return conversions.ClassifyConversionFromType(s.Type, d.Type, ref u, a); }, forCast); } private Conversion ClassifyTupleConversion( TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConversionKind kind, ClassifyConversionFromTypeDelegate classifyConversion, bool arg) { ImmutableArray<TypeWithAnnotations> sourceTypes; ImmutableArray<TypeWithAnnotations> destTypes; if (!source.TryGetElementTypesWithAnnotationsIfTupleType(out sourceTypes) || !destination.TryGetElementTypesWithAnnotationsIfTupleType(out destTypes) || sourceTypes.Length != destTypes.Length) { return Conversion.NoConversion; } var nestedConversions = ArrayBuilder<Conversion>.GetInstance(sourceTypes.Length); for (int i = 0; i < sourceTypes.Length; i++) { var conversion = classifyConversion(this, sourceTypes[i], destTypes[i], ref useSiteInfo, arg); if (!conversion.Exists) { nestedConversions.Free(); return Conversion.NoConversion; } nestedConversions.Add(conversion); } return new Conversion(kind, nestedConversions.ToImmutableAndFree()); } private Conversion ClassifyExplicitNullableConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: Explicit nullable conversions permit predefined explicit conversions that operate on // SPEC: non-nullable value types to also be used with nullable forms of those types. For // SPEC: each of the predefined explicit conversions that convert from a non-nullable value type // SPEC: S to a non-nullable value type T, the following nullable conversions exist: // SPEC: An explicit conversion from S? to T?. // SPEC: An explicit conversion from S to T?. // SPEC: An explicit conversion from S? to T. if (!source.IsNullableType() && !destination.IsNullableType()) { return Conversion.NoConversion; } TypeSymbol unwrappedSource = source.StrippedType(); TypeSymbol unwrappedDestination = destination.StrippedType(); if (HasIdentityConversionInternal(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.IdentityUnderlying); } if (HasImplicitNumericConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.ImplicitNumericUnderlying); } if (HasExplicitNumericConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.ExplicitNumericUnderlying); } var tupleConversion = ClassifyExplicitTupleConversion(unwrappedSource, unwrappedDestination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return new Conversion(ConversionKind.ExplicitNullable, ImmutableArray.Create(tupleConversion)); } if (HasExplicitEnumerationConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.ExplicitEnumerationUnderlying); } if (HasPointerToIntegerConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.PointerToIntegerUnderlying); } return Conversion.NoConversion; } private bool HasCovariantArrayConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); var s = source as ArrayTypeSymbol; var d = destination as ArrayTypeSymbol; if ((object)s == null || (object)d == null) { return false; } // * S and T differ only in element type. In other words, S and T have the same number of dimensions. if (!s.HasSameShapeAs(d)) { return false; } // * Both SE and TE are reference types. // * An implicit reference conversion exists from SE to TE. return HasImplicitReferenceConversion(s.ElementTypeWithAnnotations, d.ElementTypeWithAnnotations, ref useSiteInfo); } public bool HasIdentityOrImplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return true; } return HasImplicitReferenceConversion(source, destination, ref useSiteInfo); } private static bool HasImplicitDynamicConversionFromExpression(TypeSymbol expressionType, TypeSymbol destination) { // Spec (§6.1.8) // An implicit dynamic conversion exists from an expression of type dynamic to any type T. Debug.Assert((object)destination != null); return expressionType?.Kind == SymbolKind.DynamicType && !destination.IsPointerOrFunctionPointer(); } private static bool HasExplicitDynamicConversion(TypeSymbol source, TypeSymbol destination) { // SPEC: An explicit dynamic conversion exists from an expression of [sic] type dynamic to any type T. // ISSUE: The "an expression of" part of the spec is probably an error; see https://github.com/dotnet/csharplang/issues/132 Debug.Assert((object)source != null); Debug.Assert((object)destination != null); return source.Kind == SymbolKind.DynamicType && !destination.IsPointerOrFunctionPointer(); } private bool HasArrayConversionToInterface(ArrayTypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!source.IsSZArray) { return false; } if (!destination.IsInterfaceType()) { return false; } // The specification says that there is a conversion: // * From a single-dimensional array type S[] to IList<T> and its base // interfaces, provided that there is an implicit identity or reference // conversion from S to T. // // Newer versions of the framework also have arrays be convertible to // IReadOnlyList<T> and IReadOnlyCollection<T>; we honor that as well. // // Therefore we must check for: // // IList<T> // ICollection<T> // IEnumerable<T> // IEnumerable // IReadOnlyList<T> // IReadOnlyCollection<T> if (destination.SpecialType == SpecialType.System_Collections_IEnumerable) { return true; } NamedTypeSymbol destinationAgg = (NamedTypeSymbol)destination; if (destinationAgg.AllTypeArgumentCount() != 1) { return false; } if (!destinationAgg.IsPossibleArrayGenericInterface()) { return false; } TypeWithAnnotations elementType = source.ElementTypeWithAnnotations; TypeWithAnnotations argument0 = destinationAgg.TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo); if (IncludeNullability && !HasTopLevelNullabilityImplicitConversion(elementType, argument0)) { return false; } return HasIdentityOrImplicitReferenceConversion(elementType.Type, argument0.Type, ref useSiteInfo); } private bool HasImplicitReferenceConversion(TypeWithAnnotations source, TypeWithAnnotations destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (IncludeNullability) { if (!HasTopLevelNullabilityImplicitConversion(source, destination)) { return false; } // Check for identity conversion of underlying types if the top-level nullability is distinct. // (An identity conversion where nullability matches is not considered an implicit reference conversion.) if (source.NullableAnnotation != destination.NullableAnnotation && HasIdentityConversionInternal(source.Type, destination.Type, includeNullability: true)) { return true; } } return HasImplicitReferenceConversion(source.Type, destination.Type, ref useSiteInfo); } internal bool HasImplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsErrorType()) { return false; } if (!source.IsReferenceType) { return false; } // SPEC: The implicit reference conversions are: // SPEC: UNDONE: From any reference-type to a reference-type T if it has an implicit identity // SPEC: UNDONE: or reference conversion to a reference-type T0 and T0 has an identity conversion to T. // UNDONE: Is the right thing to do here to strip dynamic off and check for convertibility? // SPEC: From any reference type to object and dynamic. if (destination.SpecialType == SpecialType.System_Object || destination.Kind == SymbolKind.DynamicType) { return true; } switch (source.TypeKind) { case TypeKind.Class: // SPEC: From any class type S to any class type T provided S is derived from T. if (destination.IsClassType() && IsBaseClass(source, destination, ref useSiteInfo)) { return true; } return HasImplicitConversionToInterface(source, destination, ref useSiteInfo); case TypeKind.Interface: // SPEC: From any interface-type S to any interface-type T, provided S is derived from T. // NOTE: This handles variance conversions return HasImplicitConversionToInterface(source, destination, ref useSiteInfo); case TypeKind.Delegate: // SPEC: From any delegate-type to System.Delegate and the interfaces it implements. // NOTE: This handles variance conversions. return HasImplicitConversionFromDelegate(source, destination, ref useSiteInfo); case TypeKind.TypeParameter: return HasImplicitReferenceTypeParameterConversion((TypeParameterSymbol)source, destination, ref useSiteInfo); case TypeKind.Array: // SPEC: From an array-type S ... to an array-type T, provided ... // SPEC: From any array-type to System.Array and the interfaces it implements. // SPEC: From a single-dimensional array type S[] to IList<T>, provided ... return HasImplicitConversionFromArray(source, destination, ref useSiteInfo); } // UNDONE: Implicit conversions involving type parameters that are known to be reference types. return false; } private bool HasImplicitConversionToInterface(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!destination.IsInterfaceType()) { return false; } // * From any class type S to any interface type T provided S implements an interface // convertible to T. if (source.IsClassType()) { return HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo); } // * From any interface type S to any interface type T provided S implements an interface // convertible to T. // * From any interface type S to any interface type T provided S is not T and S is // an interface convertible to T. if (source.IsInterfaceType()) { if (HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) { return true; } if (!HasIdentityConversionInternal(source, destination) && HasInterfaceVarianceConversion(source, destination, ref useSiteInfo)) { return true; } } return false; } private bool HasImplicitConversionFromArray(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { ArrayTypeSymbol s = source as ArrayTypeSymbol; if ((object)s == null) { return false; } // * From an array type S with an element type SE to an array type T with element type TE // provided that all of the following are true: // * S and T differ only in element type. In other words, S and T have the same number of dimensions. // * Both SE and TE are reference types. // * An implicit reference conversion exists from SE to TE. if (HasCovariantArrayConversion(source, destination, ref useSiteInfo)) { return true; } // * From any array type to System.Array or any interface implemented by System.Array. if (destination.GetSpecialTypeSafe() == SpecialType.System_Array) { return true; } if (IsBaseInterface(destination, this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Array), ref useSiteInfo)) { return true; } // * From a single-dimensional array type S[] to IList<T> and its base // interfaces, provided that there is an implicit identity or reference // conversion from S to T. if (HasArrayConversionToInterface(s, destination, ref useSiteInfo)) { return true; } return false; } private bool HasImplicitConversionFromDelegate(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!source.IsDelegateType()) { return false; } // * From any delegate type to System.Delegate // // SPEC OMISSION: // // The spec should actually say // // * From any delegate type to System.Delegate // * From any delegate type to System.MulticastDelegate // * From any delegate type to any interface implemented by System.MulticastDelegate var specialDestination = destination.GetSpecialTypeSafe(); if (specialDestination == SpecialType.System_MulticastDelegate || specialDestination == SpecialType.System_Delegate || IsBaseInterface(destination, this.corLibrary.GetDeclaredSpecialType(SpecialType.System_MulticastDelegate), ref useSiteInfo)) { return true; } // * From any delegate type S to a delegate type T provided S is not T and // S is a delegate convertible to T if (HasDelegateVarianceConversion(source, destination, ref useSiteInfo)) { return true; } return false; } public bool HasImplicitTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (HasImplicitReferenceTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } if (HasImplicitBoxingTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } if ((destination.TypeKind == TypeKind.TypeParameter) && source.DependsOn((TypeParameterSymbol)destination)) { return true; } return false; } private bool HasImplicitReferenceTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsValueType) { return false; // Not a reference conversion. } // The following implicit conversions exist for a given type parameter T: // // * From T to its effective base class C. // * From T to any base class of C. // * From T to any interface implemented by C (or any interface variance-compatible with such) if (HasImplicitEffectiveBaseConversion(source, destination, ref useSiteInfo)) { return true; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I (or any interface variance-compatible with such) if (HasImplicitEffectiveInterfaceSetConversion(source, destination, ref useSiteInfo)) { return true; } // * From T to a type parameter U, provided T depends on U. if ((destination.TypeKind == TypeKind.TypeParameter) && source.DependsOn((TypeParameterSymbol)destination)) { return true; } return false; } // Spec 6.1.10: Implicit conversions involving type parameters private bool HasImplicitEffectiveBaseConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // * From T to its effective base class C. var effectiveBaseClass = source.EffectiveBaseClass(ref useSiteInfo); if (HasIdentityConversionInternal(effectiveBaseClass, destination)) { return true; } // * From T to any base class of C. if (IsBaseClass(effectiveBaseClass, destination, ref useSiteInfo)) { return true; } // * From T to any interface implemented by C (or any interface variance-compatible with such) if (HasAnyBaseInterfaceConversion(effectiveBaseClass, destination, ref useSiteInfo)) { return true; } return false; } private bool HasImplicitEffectiveInterfaceSetConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!destination.IsInterfaceType()) { return false; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I (or any interface variance-compatible with such) foreach (var i in source.AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasInterfaceVarianceConversion(i, destination, ref useSiteInfo)) { return true; } } return false; } private bool HasAnyBaseInterfaceConversion(TypeSymbol derivedType, TypeSymbol baseType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)derivedType != null); Debug.Assert((object)baseType != null); if (!baseType.IsInterfaceType()) { return false; } var d = derivedType as NamedTypeSymbol; if ((object)d == null) { return false; } foreach (var i in d.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasInterfaceVarianceConversion(i, baseType, ref useSiteInfo)) { return true; } } return false; } //////////////////////////////////////////////////////////////////////////////// // The rules for variant interface and delegate conversions are the same: // // An interface/delegate type S is convertible to an interface/delegate type T // if and only if T is U<S1, ... Sn> and T is U<T1, ... Tn> such that for all // parameters of U: // // * if the ith parameter of U is invariant then Si is exactly equal to Ti. // * if the ith parameter of U is covariant then either Si is exactly equal // to Ti, or there is an implicit reference conversion from Si to Ti. // * if the ith parameter of U is contravariant then either Si is exactly // equal to Ti, or there is an implicit reference conversion from Ti to Si. private bool HasInterfaceVarianceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); NamedTypeSymbol s = source as NamedTypeSymbol; NamedTypeSymbol d = destination as NamedTypeSymbol; if ((object)s == null || (object)d == null) { return false; } if (!s.IsInterfaceType() || !d.IsInterfaceType()) { return false; } return HasVariantConversion(s, d, ref useSiteInfo); } private bool HasDelegateVarianceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); NamedTypeSymbol s = source as NamedTypeSymbol; NamedTypeSymbol d = destination as NamedTypeSymbol; if ((object)s == null || (object)d == null) { return false; } if (!s.IsDelegateType() || !d.IsDelegateType()) { return false; } return HasVariantConversion(s, d, ref useSiteInfo); } private bool HasVariantConversion(NamedTypeSymbol source, NamedTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // We check for overflows in HasVariantConversion, because they are only an issue // in the presence of contravariant type parameters, which are not involved in // most conversions. // See VarianceTests for examples (e.g. TestVarianceConversionCycle, // TestVarianceConversionInfiniteExpansion). // // CONSIDER: A more rigorous solution would mimic the CLI approach, which uses // a combination of requiring finite instantiation closures (see section 9.2 of // the CLI spec) and records previous conversion steps to check for cycles. if (currentRecursionDepth >= MaximumRecursionDepth) { // NOTE: The spec doesn't really address what happens if there's an overflow // in our conversion check. It's sort of implied that the conversion "proof" // should be finite, so we'll just say that no conversion is possible. return false; } // Do a quick check up front to avoid instantiating a new Conversions object, // if possible. var quickResult = HasVariantConversionQuick(source, destination); if (quickResult.HasValue()) { return quickResult.Value(); } return this.CreateInstance(currentRecursionDepth + 1). HasVariantConversionNoCycleCheck(source, destination, ref useSiteInfo); } private ThreeState HasVariantConversionQuick(NamedTypeSymbol source, NamedTypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return ThreeState.True; } NamedTypeSymbol typeSymbol = source.OriginalDefinition; if (!TypeSymbol.Equals(typeSymbol, destination.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { return ThreeState.False; } return ThreeState.Unknown; } private bool HasVariantConversionNoCycleCheck(NamedTypeSymbol source, NamedTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); var typeParameters = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var destinationTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); try { source.OriginalDefinition.GetAllTypeArguments(typeParameters, ref useSiteInfo); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); destination.GetAllTypeArguments(destinationTypeArguments, ref useSiteInfo); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, destination.OriginalDefinition, TypeCompareKind.AllIgnoreOptions)); Debug.Assert(typeParameters.Count == sourceTypeArguments.Count); Debug.Assert(typeParameters.Count == destinationTypeArguments.Count); for (int paramIndex = 0; paramIndex < typeParameters.Count; ++paramIndex) { var sourceTypeArgument = sourceTypeArguments[paramIndex]; var destinationTypeArgument = destinationTypeArguments[paramIndex]; // If they're identical then this one is automatically good, so skip it. if (HasIdentityConversionInternal(sourceTypeArgument.Type, destinationTypeArgument.Type) && HasTopLevelNullabilityIdentityConversion(sourceTypeArgument, destinationTypeArgument)) { continue; } TypeParameterSymbol typeParameterSymbol = (TypeParameterSymbol)typeParameters[paramIndex].Type; switch (typeParameterSymbol.Variance) { case VarianceKind.None: // System.IEquatable<T> is invariant for back compat reasons (dynamic type checks could start // to succeed where they previously failed, creating different runtime behavior), but the uses // require treatment specifically of nullability as contravariant, so we special case the // behavior here. Normally we use GetWellKnownType for these kinds of checks, but in this // case we don't want just the canonical IEquatable to be special-cased, we want all definitions // to be treated as contravariant, in case there are other definitions in metadata that were // compiled with that expectation. if (isTypeIEquatable(destination.OriginalDefinition) && TypeSymbol.Equals(destinationTypeArgument.Type, sourceTypeArgument.Type, TypeCompareKind.AllNullableIgnoreOptions) && HasAnyNullabilityImplicitConversion(destinationTypeArgument, sourceTypeArgument)) { return true; } return false; case VarianceKind.Out: if (!HasImplicitReferenceConversion(sourceTypeArgument, destinationTypeArgument, ref useSiteInfo)) { return false; } break; case VarianceKind.In: if (!HasImplicitReferenceConversion(destinationTypeArgument, sourceTypeArgument, ref useSiteInfo)) { return false; } break; default: throw ExceptionUtilities.UnexpectedValue(typeParameterSymbol.Variance); } } } finally { typeParameters.Free(); sourceTypeArguments.Free(); destinationTypeArguments.Free(); } return true; static bool isTypeIEquatable(NamedTypeSymbol type) { return type is { IsInterface: true, Name: "IEquatable", ContainingNamespace: { Name: "System", ContainingNamespace: { IsGlobalNamespace: true } }, ContainingSymbol: { Kind: SymbolKind.Namespace }, TypeParameters: { Length: 1 } }; } } // Spec 6.1.10 private bool HasImplicitBoxingTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsReferenceType) { return false; // Not a boxing conversion; both source and destination are references. } // The following implicit conversions exist for a given type parameter T: // // * From T to its effective base class C. // * From T to any base class of C. // * From T to any interface implemented by C (or any interface variance-compatible with such) if (HasImplicitEffectiveBaseConversion(source, destination, ref useSiteInfo)) { return true; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I (or any interface variance-compatible with such) if (HasImplicitEffectiveInterfaceSetConversion(source, destination, ref useSiteInfo)) { return true; } // SPEC: From T to a type parameter U, provided T depends on U if ((destination.TypeKind == TypeKind.TypeParameter) && source.DependsOn((TypeParameterSymbol)destination)) { return true; } // SPEC: From T to a reference type I if it has an implicit conversion to a reference // SPEC: type S0 and S0 has an identity conversion to S. At run-time the conversion // SPEC: is executed the same way as the conversion to S0. // REVIEW: If T is not known to be a reference type then the only way this clause can // REVIEW: come into effect is if the target type is dynamic. Is that correct? if (destination.Kind == SymbolKind.DynamicType) { return true; } return false; } public bool HasBoxingConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // Certain type parameter conversions are classified as boxing conversions. if ((source.TypeKind == TypeKind.TypeParameter) && HasImplicitBoxingTypeParameterConversion((TypeParameterSymbol)source, destination, ref useSiteInfo)) { return true; } // The rest of the boxing conversions only operate when going from a value type to a // reference type. if (!source.IsValueType || !destination.IsReferenceType) { return false; } // A boxing conversion exists from a nullable type to a reference type if and only if a // boxing conversion exists from the underlying type. if (source.IsNullableType()) { return HasBoxingConversion(source.GetNullableUnderlyingType(), destination, ref useSiteInfo); } // A boxing conversion exists from any non-nullable value type to object and dynamic, to // System.ValueType, and to any interface type variance-compatible with one implemented // by the non-nullable value type. // Furthermore, an enum type can be converted to the type System.Enum. // We set the base class of the structs to System.ValueType, System.Enum, etc, so we can // just check here. // There are a couple of exceptions. The very special types ArgIterator, ArgumentHandle and // TypedReference are not boxable: if (source.IsRestrictedType()) { return false; } if (destination.Kind == SymbolKind.DynamicType) { return !source.IsPointerOrFunctionPointer(); } if (IsBaseClass(source, destination, ref useSiteInfo)) { return true; } if (HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) { return true; } return false; } internal static bool HasImplicitPointerToVoidConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: The set of implicit conversions is extended to include... // SPEC: ... from any pointer type to the type void*. return source.IsPointerOrFunctionPointer() && destination is PointerTypeSymbol { PointedAtType: { SpecialType: SpecialType.System_Void } }; } #nullable enable internal bool HasImplicitPointerConversion(TypeSymbol? source, TypeSymbol? destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!(source is FunctionPointerTypeSymbol { Signature: { } sourceSig }) || !(destination is FunctionPointerTypeSymbol { Signature: { } destinationSig })) { return false; } if (sourceSig.ParameterCount != destinationSig.ParameterCount || sourceSig.CallingConvention != destinationSig.CallingConvention) { return false; } if (sourceSig.CallingConvention == Cci.CallingConvention.Unmanaged && !sourceSig.GetCallingConventionModifiers().SetEquals(destinationSig.GetCallingConventionModifiers())) { return false; } for (int i = 0; i < sourceSig.ParameterCount; i++) { var sourceParam = sourceSig.Parameters[i]; var destinationParam = destinationSig.Parameters[i]; if (sourceParam.RefKind != destinationParam.RefKind) { return false; } if (!hasConversion(sourceParam.RefKind, destinationSig.Parameters[i].TypeWithAnnotations, sourceSig.Parameters[i].TypeWithAnnotations, ref useSiteInfo)) { return false; } } return sourceSig.RefKind == destinationSig.RefKind && hasConversion(sourceSig.RefKind, sourceSig.ReturnTypeWithAnnotations, destinationSig.ReturnTypeWithAnnotations, ref useSiteInfo); bool hasConversion(RefKind refKind, TypeWithAnnotations sourceType, TypeWithAnnotations destinationType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (refKind) { case RefKind.None: return (!IncludeNullability || HasTopLevelNullabilityImplicitConversion(sourceType, destinationType)) && (HasIdentityOrImplicitReferenceConversion(sourceType.Type, destinationType.Type, ref useSiteInfo) || HasImplicitPointerToVoidConversion(sourceType.Type, destinationType.Type) || HasImplicitPointerConversion(sourceType.Type, destinationType.Type, ref useSiteInfo)); default: return (!IncludeNullability || HasTopLevelNullabilityIdentityConversion(sourceType, destinationType)) && HasIdentityConversion(sourceType.Type, destinationType.Type); } } } #nullable disable private bool HasIdentityOrReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return true; } if (HasImplicitReferenceConversion(source, destination, ref useSiteInfo)) { return true; } if (HasExplicitReferenceConversion(source, destination, ref useSiteInfo)) { return true; } return false; } private bool HasExplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: The explicit reference conversions are: // SPEC: From object and dynamic to any other reference type. if (source.SpecialType == SpecialType.System_Object) { if (destination.IsReferenceType) { return true; } } else if (source.Kind == SymbolKind.DynamicType && destination.IsReferenceType) { return true; } // SPEC: From any class-type S to any class-type T, provided S is a base class of T. if (destination.IsClassType() && IsBaseClass(destination, source, ref useSiteInfo)) { return true; } // SPEC: From any class-type S to any interface-type T, provided S is not sealed and provided S does not implement T. // ISSUE: class C : IEnumerable<Mammal> { } converting this to IEnumerable<Animal> is not an explicit conversion, // ISSUE: it is an implicit conversion. if (source.IsClassType() && destination.IsInterfaceType() && !source.IsSealed && !HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) { return true; } // SPEC: From any interface-type S to any class-type T, provided T is not sealed or provided T implements S. // ISSUE: What if T is sealed and implements an interface variance-convertible to S? // ISSUE: eg, sealed class C : IEnum<Mammal> { ... } you should be able to cast an IEnum<Animal> to C. if (source.IsInterfaceType() && destination.IsClassType() && (!destination.IsSealed || HasAnyBaseInterfaceConversion(destination, source, ref useSiteInfo))) { return true; } // SPEC: From any interface-type S to any interface-type T, provided S is not derived from T. // ISSUE: This does not rule out identity conversions, which ought not to be classified as // ISSUE: explicit reference conversions. // ISSUE: IEnumerable<Mammal> and IEnumerable<Animal> do not derive from each other but this is // ISSUE: not an explicit reference conversion, this is an implicit reference conversion. if (source.IsInterfaceType() && destination.IsInterfaceType() && !HasImplicitConversionToInterface(source, destination, ref useSiteInfo)) { return true; } // SPEC: UNDONE: From a reference type to a reference type T if it has an explicit reference conversion to a reference type T0 and T0 has an identity conversion T. // SPEC: UNDONE: From a reference type to an interface or delegate type T if it has an explicit reference conversion to an interface or delegate type T0 and either T0 is variance-convertible to T or T is variance-convertible to T0 (§13.1.3.2). if (HasExplicitArrayConversion(source, destination, ref useSiteInfo)) { return true; } if (HasExplicitDelegateConversion(source, destination, ref useSiteInfo)) { return true; } if (HasExplicitReferenceTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } return false; } // Spec 6.2.7 Explicit conversions involving type parameters private bool HasExplicitReferenceTypeParameterConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); TypeParameterSymbol s = source as TypeParameterSymbol; TypeParameterSymbol t = destination as TypeParameterSymbol; // SPEC: The following explicit conversions exist for a given type parameter T: // SPEC: If T is known to be a reference type, the conversions are all classified as explicit reference conversions. // SPEC: If T is not known to be a reference type, the conversions are classified as unboxing conversions. // SPEC: From the effective base class C of T to T and from any base class of C to T. if ((object)t != null && t.IsReferenceType) { for (var type = t.EffectiveBaseClass(ref useSiteInfo); (object)type != null; type = type.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(type, source)) { return true; } } } // SPEC: From any interface type to T. if ((object)t != null && source.IsInterfaceType() && t.IsReferenceType) { return true; } // SPEC: From T to any interface-type I provided there is not already an implicit conversion from T to I. if ((object)s != null && s.IsReferenceType && destination.IsInterfaceType() && !HasImplicitReferenceTypeParameterConversion(s, destination, ref useSiteInfo)) { return true; } // SPEC: From a type parameter U to T, provided T depends on U (§10.1.5) if ((object)s != null && (object)t != null && t.IsReferenceType && t.DependsOn(s)) { return true; } return false; } // Spec 6.2.7 Explicit conversions involving type parameters private bool HasUnboxingTypeParameterConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); TypeParameterSymbol s = source as TypeParameterSymbol; TypeParameterSymbol t = destination as TypeParameterSymbol; // SPEC: The following explicit conversions exist for a given type parameter T: // SPEC: If T is known to be a reference type, the conversions are all classified as explicit reference conversions. // SPEC: If T is not known to be a reference type, the conversions are classified as unboxing conversions. // SPEC: From the effective base class C of T to T and from any base class of C to T. if ((object)t != null && !t.IsReferenceType) { for (var type = t.EffectiveBaseClass(ref useSiteInfo); (object)type != null; type = type.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (TypeSymbol.Equals(type, source, TypeCompareKind.ConsiderEverything2)) { return true; } } } // SPEC: From any interface type to T. if (source.IsInterfaceType() && (object)t != null && !t.IsReferenceType) { return true; } // SPEC: From T to any interface-type I provided there is not already an implicit conversion from T to I. if ((object)s != null && !s.IsReferenceType && destination.IsInterfaceType() && !HasImplicitReferenceTypeParameterConversion(s, destination, ref useSiteInfo)) { return true; } // SPEC: From a type parameter U to T, provided T depends on U (§10.1.5) if ((object)s != null && (object)t != null && !t.IsReferenceType && t.DependsOn(s)) { return true; } return false; } private bool HasExplicitDelegateConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: From System.Delegate and the interfaces it implements to any delegate-type. // We also support System.MulticastDelegate in the implementation, in spite of it not being mentioned in the spec. if (destination.IsDelegateType()) { if (source.SpecialType == SpecialType.System_Delegate || source.SpecialType == SpecialType.System_MulticastDelegate) { return true; } if (HasImplicitConversionToInterface(this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Delegate), source, ref useSiteInfo)) { return true; } } // SPEC: From D<S1...Sn> to a D<T1...Tn> where D<X1...Xn> is a generic delegate type, D<S1...Sn> is not compatible with or identical to D<T1...Tn>, // SPEC: and for each type parameter Xi of D the following holds: // SPEC: If Xi is invariant, then Si is identical to Ti. // SPEC: If Xi is covariant, then there is an implicit or explicit identity or reference conversion from Si to Ti. // SPECL If Xi is contravariant, then Si and Ti are either identical or both reference types. if (!source.IsDelegateType() || !destination.IsDelegateType()) { return false; } if (!TypeSymbol.Equals(source.OriginalDefinition, destination.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { return false; } var sourceType = (NamedTypeSymbol)source; var destinationType = (NamedTypeSymbol)destination; var original = sourceType.OriginalDefinition; if (HasIdentityConversionInternal(source, destination)) { return false; } if (HasDelegateVarianceConversion(source, destination, ref useSiteInfo)) { return false; } var sourceTypeArguments = sourceType.TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo); var destinationTypeArguments = destinationType.TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo); for (int i = 0; i < sourceTypeArguments.Length; ++i) { var sourceArg = sourceTypeArguments[i].Type; var destinationArg = destinationTypeArguments[i].Type; switch (original.TypeParameters[i].Variance) { case VarianceKind.None: if (!HasIdentityConversionInternal(sourceArg, destinationArg)) { return false; } break; case VarianceKind.Out: if (!HasIdentityOrReferenceConversion(sourceArg, destinationArg, ref useSiteInfo)) { return false; } break; case VarianceKind.In: bool hasIdentityConversion = HasIdentityConversionInternal(sourceArg, destinationArg); bool bothAreReferenceTypes = sourceArg.IsReferenceType && destinationArg.IsReferenceType; if (!(hasIdentityConversion || bothAreReferenceTypes)) { return false; } break; } } return true; } private bool HasExplicitArrayConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); var sourceArray = source as ArrayTypeSymbol; var destinationArray = destination as ArrayTypeSymbol; // SPEC: From an array-type S with an element type SE to an array-type T with an element type TE, provided all of the following are true: // SPEC: S and T differ only in element type. (In other words, S and T have the same number of dimensions.) // SPEC: Both SE and TE are reference-types. // SPEC: An explicit reference conversion exists from SE to TE. if ((object)sourceArray != null && (object)destinationArray != null) { // HasExplicitReferenceConversion checks that SE and TE are reference types so // there's no need for that check here. Moreover, it's not as simple as checking // IsReferenceType, at least not in the case of type parameters, since SE will be // considered a reference type implicitly in the case of "where TE : class, SE" even // though SE.IsReferenceType may be false. Again, HasExplicitReferenceConversion // already handles these cases. return sourceArray.HasSameShapeAs(destinationArray) && HasExplicitReferenceConversion(sourceArray.ElementType, destinationArray.ElementType, ref useSiteInfo); } // SPEC: From System.Array and the interfaces it implements to any array-type. if ((object)destinationArray != null) { if (source.SpecialType == SpecialType.System_Array) { return true; } foreach (var iface in this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Array).AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(iface, source)) { return true; } } } // SPEC: From a single-dimensional array type S[] to System.Collections.Generic.IList<T> and its base interfaces // SPEC: provided that there is an explicit reference conversion from S to T. // The framework now also allows arrays to be converted to IReadOnlyList<T> and IReadOnlyCollection<T>; we // honor that as well. if ((object)sourceArray != null && sourceArray.IsSZArray && destination.IsPossibleArrayGenericInterface()) { if (HasExplicitReferenceConversion(sourceArray.ElementType, ((NamedTypeSymbol)destination).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo).Type, ref useSiteInfo)) { return true; } } // SPEC: From System.Collections.Generic.IList<S> and its base interfaces to a single-dimensional array type T[], // provided that there is an explicit identity or reference conversion from S to T. // Similarly, we honor IReadOnlyList<S> and IReadOnlyCollection<S> in the same way. if ((object)destinationArray != null && destinationArray.IsSZArray) { var specialDefinition = ((TypeSymbol)source.OriginalDefinition).SpecialType; if (specialDefinition == SpecialType.System_Collections_Generic_IList_T || specialDefinition == SpecialType.System_Collections_Generic_ICollection_T || specialDefinition == SpecialType.System_Collections_Generic_IEnumerable_T || specialDefinition == SpecialType.System_Collections_Generic_IReadOnlyList_T || specialDefinition == SpecialType.System_Collections_Generic_IReadOnlyCollection_T) { var sourceElement = ((NamedTypeSymbol)source).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo).Type; var destinationElement = destinationArray.ElementType; if (HasIdentityConversionInternal(sourceElement, destinationElement)) { return true; } if (HasImplicitReferenceConversion(sourceElement, destinationElement, ref useSiteInfo)) { return true; } if (HasExplicitReferenceConversion(sourceElement, destinationElement, ref useSiteInfo)) { return true; } } } return false; } private bool HasUnboxingConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (destination.IsPointerOrFunctionPointer()) { return false; } // Ref-like types cannot be boxed or unboxed if (destination.IsRestrictedType()) { return false; } // SPEC: An unboxing conversion permits a reference type to be explicitly converted to a value-type. // SPEC: An unboxing conversion exists from the types object and System.ValueType to any non-nullable-value-type, var specialTypeSource = source.SpecialType; if (specialTypeSource == SpecialType.System_Object || specialTypeSource == SpecialType.System_ValueType) { if (destination.IsValueType && !destination.IsNullableType()) { return true; } } // SPEC: and from any interface-type to any non-nullable-value-type that implements the interface-type. if (source.IsInterfaceType() && destination.IsValueType && !destination.IsNullableType() && HasBoxingConversion(destination, source, ref useSiteInfo)) { return true; } // SPEC: Furthermore type System.Enum can be unboxed to any enum-type. if (source.SpecialType == SpecialType.System_Enum && destination.IsEnumType()) { return true; } // SPEC: An unboxing conversion exists from a reference type to a nullable-type if an unboxing // SPEC: conversion exists from the reference type to the underlying non-nullable-value-type // SPEC: of the nullable-type. if (source.IsReferenceType && destination.IsNullableType() && HasUnboxingConversion(source, destination.GetNullableUnderlyingType(), ref useSiteInfo)) { return true; } // SPEC: UNDONE A value type S has an unboxing conversion from an interface type I if it has an unboxing // SPEC: UNDONE conversion from an interface type I0 and I0 has an identity conversion to I. // SPEC: UNDONE A value type S has an unboxing conversion from an interface type I if it has an unboxing conversion // SPEC: UNDONE from an interface or delegate type I0 and either I0 is variance-convertible to I or I is variance-convertible to I0. if (HasUnboxingTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } return false; } private static bool HasPointerToPointerConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); return source.IsPointerOrFunctionPointer() && destination.IsPointerOrFunctionPointer(); } private static bool HasPointerToIntegerConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!source.IsPointerOrFunctionPointer()) { return false; } // SPEC OMISSION: // // The spec should state that any pointer type is convertible to // sbyte, byte, ... etc, or any corresponding nullable type. return IsIntegerTypeSupportingPointerConversions(destination.StrippedType()); } private static bool HasIntegerToPointerConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!destination.IsPointerOrFunctionPointer()) { return false; } // Note that void* is convertible to int?, but int? is not convertible to void*. return IsIntegerTypeSupportingPointerConversions(source); } private static bool IsIntegerTypeSupportingPointerConversions(TypeSymbol type) { switch (type.SpecialType) { case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: return true; case SpecialType.System_IntPtr: case SpecialType.System_UIntPtr: return type.IsNativeIntegerType; } return false; } } }
1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Portable/Binder/Semantics/Conversions/LambdaConversionResult.cs
// Licensed to the .NET Foundation under one or more 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 { internal enum LambdaConversionResult { Success, BadTargetType, BadParameterCount, MissingSignatureWithOutParameter, MismatchedReturnType, MismatchedParameterType, RefInImplicitlyTypedLambda, StaticTypeInImplicitlyTypedLambda, ExpressionTreeMustHaveDelegateTypeArgument, ExpressionTreeFromAnonymousMethod, BindingFailed } }
// Licensed to the .NET Foundation under one or more 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 { internal enum LambdaConversionResult { Success, BadTargetType, BadParameterCount, MissingSignatureWithOutParameter, MismatchedReturnType, MismatchedParameterType, RefInImplicitlyTypedLambda, StaticTypeInImplicitlyTypedLambda, ExpressionTreeMustHaveDelegateTypeArgument, ExpressionTreeFromAnonymousMethod, CannotInferDelegateType, BindingFailed } }
1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenTupleEqualityTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { [CompilerTrait(CompilerFeature.TupleEquality)] public class CodeGenTupleEqualityTests : CSharpTestBase { [Fact] public void TestCSharp7_2() { var source = @" class C { static void Main() { var t = (1, 2); System.Console.Write(t == (1, 2)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_2); comp.VerifyDiagnostics( // (7,30): error CS8320: Feature 'tuple equality' is not available in C# 7.2. Please use language version 7.3 or greater. // System.Console.Write(t == (1, 2)); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "t == (1, 2)").WithArguments("tuple equality", "7.3").WithLocation(7, 30) ); } [Theory] [InlineData("(1, 2)", "(1L, 2L)", true)] [InlineData("(1, 2)", "(1, 0)", false)] [InlineData("(1, 2)", "(0, 2)", false)] [InlineData("(1, 2)", "((long, long))(1, 2)", true)] [InlineData("((1, 2L), (3, 4))", "((1L, 2), (3L, 4))", true)] [InlineData("((1, 2L), (3, 4))", "((0L, 2), (3L, 4))", false)] [InlineData("((1, 2L), (3, 4))", "((1L, 0), (3L, 4))", false)] [InlineData("((1, 2L), (3, 4))", "((1L, 0), (0L, 4))", false)] [InlineData("((1, 2L), (3, 4))", "((1L, 0), (3L, 0))", false)] void TestSimple(string change1, string change2, bool expectedMatch) { var sourceTemplate = @" class C { static void Main() { var t1 = CHANGE1; var t2 = CHANGE2; System.Console.Write($""{(t1 == t2) == EXPECTED} {(t1 != t2) != EXPECTED}""); } }"; string source = sourceTemplate .Replace("CHANGE1", change1) .Replace("CHANGE2", change2) .Replace("EXPECTED", expectedMatch ? "true" : "false"); string name = GetUniqueName(); var comp = CreateCompilation(source, options: TestOptions.DebugExe, assemblyName: name); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True True"); } [Fact] public void TestTupleLiteralsWithDifferentCardinalities() { var source = @" class C { static bool M() { return (1, 1) == (2, 2, 2); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,16): error CS8373: Tuple types used as operands of an == or != operator must have matching cardinalities. But this operator has tuple types of cardinality 2 on the left and 3 on the right. // return (1, 1) == (2, 2, 2); Diagnostic(ErrorCode.ERR_TupleSizesMismatchForBinOps, "(1, 1) == (2, 2, 2)").WithArguments("2", "3").WithLocation(6, 16) ); } [Fact] public void TestTuplesWithDifferentCardinalities() { var source = @" class C { static bool M() { var t1 = (1, 1); var t2 = (2, 2, 2); return t1 == t2; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,16): error CS8355: Tuple types used as operands of a binary operator must have matching cardinalities. But this operator has tuple types of cardinality 2 on the left and 3 on the right. // return t1 == t2; Diagnostic(ErrorCode.ERR_TupleSizesMismatchForBinOps, "t1 == t2").WithArguments("2", "3").WithLocation(8, 16) ); } [Fact] public void TestNestedTuplesWithDifferentCardinalities() { var source = @" class C { static bool M() { var t1 = (1, (1, 1)); var t2 = (2, (2, 2, 2)); return t1 == t2; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,16): error CS8355: Tuple types used as operands of a binary operator must have matching cardinalities. But this operator has tuple types of cardinality 2 on the left and 3 on the right. // return t1 == t2; Diagnostic(ErrorCode.ERR_TupleSizesMismatchForBinOps, "t1 == t2").WithArguments("2", "3").WithLocation(8, 16) ); } [Fact, WorkItem(25295, "https://github.com/dotnet/roslyn/issues/25295")] public void TestWithoutValueTuple() { var source = @" class C { static bool M() { return (1, 2) == (3, 4); } }"; var comp = CreateCompilationWithMscorlib40(source); // https://github.com/dotnet/roslyn/issues/25295 // Can we relax the requirement on ValueTuple types being found? comp.VerifyDiagnostics( // (6,16): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // return (1, 2) == (3, 4); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(1, 2)").WithArguments("System.ValueTuple`2").WithLocation(6, 16), // (6,26): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // return (1, 2) == (3, 4); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(3, 4)").WithArguments("System.ValueTuple`2").WithLocation(6, 26) ); } [Fact] public void TestNestedNullableTuplesWithDifferentCardinalities() { var source = @" class C { static bool M() { (int, int)? nt = (1, 1); var t1 = (1, nt); var t2 = (2, (2, 2, 2)); return t1 == t2; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,16): error CS8373: Tuple types used as operands of a binary operator must have matching cardinalities. But this operator has tuple types of cardinality 2 on the left and 3 on the right. // return t1 == t2; Diagnostic(ErrorCode.ERR_TupleSizesMismatchForBinOps, "t1 == t2").WithArguments("2", "3").WithLocation(9, 16) ); } [Fact] public void TestILForSimpleEqual() { var source = @" class C { static bool M() { var t1 = (1, 1); var t2 = (2, 2); return t1 == t2; } }"; var comp = CompileAndVerify(source); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @"{ // Code size 50 (0x32) .maxstack 3 .locals init (System.ValueTuple<int, int> V_0, //t1 System.ValueTuple<int, int> V_1, System.ValueTuple<int, int> V_2) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldc.i4.1 IL_0004: call ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0009: ldc.i4.2 IL_000a: ldc.i4.2 IL_000b: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0010: ldloc.0 IL_0011: stloc.1 IL_0012: stloc.2 IL_0013: ldloc.1 IL_0014: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0019: ldloc.2 IL_001a: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_001f: bne.un.s IL_0030 IL_0021: ldloc.1 IL_0022: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0027: ldloc.2 IL_0028: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_002d: ceq IL_002f: ret IL_0030: ldc.i4.0 IL_0031: ret }"); } [Fact] public void TestILForSimpleNotEqual() { var source = @" class C { static bool M((int, int) t1, (int, int) t2) { return t1 != t2; } }"; var comp = CompileAndVerify(source); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @"{ // Code size 38 (0x26) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0, System.ValueTuple<int, int> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.1 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0010: bne.un.s IL_0024 IL_0012: ldloc.0 IL_0013: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_001e: ceq IL_0020: ldc.i4.0 IL_0021: ceq IL_0023: ret IL_0024: ldc.i4.1 IL_0025: ret }"); } [Fact] public void TestILForSimpleEqualOnInTuple() { var source = @" class C { static bool M(in (int, int) t1, in (int, int) t2) { return t1 == t2; } }"; var comp = CompileAndVerify(source); comp.VerifyDiagnostics(); // note: the logic to save variables and side-effects results in copying the inputs comp.VerifyIL("C.M", @"{ // Code size 45 (0x2d) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0, System.ValueTuple<int, int> V_1) IL_0000: ldarg.0 IL_0001: ldobj ""System.ValueTuple<int, int>"" IL_0006: stloc.0 IL_0007: ldarg.1 IL_0008: ldobj ""System.ValueTuple<int, int>"" IL_000d: stloc.1 IL_000e: ldloc.0 IL_000f: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0014: ldloc.1 IL_0015: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_001a: bne.un.s IL_002b IL_001c: ldloc.0 IL_001d: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0022: ldloc.1 IL_0023: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0028: ceq IL_002a: ret IL_002b: ldc.i4.0 IL_002c: ret }"); } [Fact] public void TestILForSimpleEqualOnTupleLiterals() { var source = @" class C { static void Main() { M(1, 1); M(1, 2); M(2, 1); } static void M(int x, byte y) { System.Console.Write($""{(x, x) == (y, y)} ""); } }"; var comp = CompileAndVerify(source, expectedOutput: "True False False"); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @"{ // Code size 38 (0x26) .maxstack 3 .locals init (int V_0, byte V_1, byte V_2) IL_0000: ldstr ""{0} "" IL_0005: ldarg.0 IL_0006: ldarg.0 IL_0007: stloc.0 IL_0008: ldarg.1 IL_0009: stloc.1 IL_000a: ldarg.1 IL_000b: stloc.2 IL_000c: ldloc.1 IL_000d: bne.un.s IL_0015 IL_000f: ldloc.0 IL_0010: ldloc.2 IL_0011: ceq IL_0013: br.s IL_0016 IL_0015: ldc.i4.0 IL_0016: box ""bool"" IL_001b: call ""string string.Format(string, object)"" IL_0020: call ""void System.Console.Write(string)"" IL_0025: ret }"); var tree = comp.Compilation.SyntaxTrees.First(); var model = comp.Compilation.GetSemanticModel(tree); // check x var tupleX = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal("(x, x)", tupleX.ToString()); Assert.Equal(Conversion.Identity, model.GetConversion(tupleX)); Assert.Null(model.GetSymbolInfo(tupleX).Symbol); var lastX = tupleX.Arguments[1].Expression; Assert.Equal("x", lastX.ToString()); Assert.Equal(Conversion.Identity, model.GetConversion(lastX)); Assert.Equal("System.Int32 x", model.GetSymbolInfo(lastX).Symbol.ToTestDisplayString()); var xSymbol = model.GetTypeInfo(lastX); Assert.Equal("System.Int32", xSymbol.Type.ToTestDisplayString()); Assert.Equal("System.Int32", xSymbol.ConvertedType.ToTestDisplayString()); var tupleXSymbol = model.GetTypeInfo(tupleX); Assert.Equal("(System.Int32, System.Int32)", tupleXSymbol.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)", tupleXSymbol.ConvertedType.ToTestDisplayString()); // check y var tupleY = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().Last(); Assert.Equal("(y, y)", tupleY.ToString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(tupleY).Kind); var lastY = tupleY.Arguments[1].Expression; Assert.Equal("y", lastY.ToString()); Assert.Equal(Conversion.ImplicitNumeric, model.GetConversion(lastY)); var ySymbol = model.GetTypeInfo(lastY); Assert.Equal("System.Byte", ySymbol.Type.ToTestDisplayString()); Assert.Equal("System.Int32", ySymbol.ConvertedType.ToTestDisplayString()); var tupleYSymbol = model.GetTypeInfo(tupleY); Assert.Equal("(System.Byte, System.Byte)", tupleYSymbol.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)", tupleYSymbol.ConvertedType.ToTestDisplayString()); } [Fact] public void TestILForAlwaysValuedNullable() { var source = @" class C { static void Main() { System.Console.Write($""{(new int?(Identity(42)), (int?)2) == (new int?(42), new int?(2))} ""); } static int Identity(int x) => x; }"; var comp = CompileAndVerify(source, expectedOutput: "True"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 39 (0x27) .maxstack 3 IL_0000: ldstr ""{0} "" IL_0005: ldc.i4.s 42 IL_0007: call ""int C.Identity(int)"" IL_000c: ldc.i4.s 42 IL_000e: bne.un.s IL_0016 IL_0010: ldc.i4.2 IL_0011: ldc.i4.2 IL_0012: ceq IL_0014: br.s IL_0017 IL_0016: ldc.i4.0 IL_0017: box ""bool"" IL_001c: call ""string string.Format(string, object)"" IL_0021: call ""void System.Console.Write(string)"" IL_0026: ret }"); } [Fact] public void TestILForNullableElementsEqualsToNull() { var source = @" class C { static void Main() { System.Console.Write(M(null, null)); System.Console.Write(M(1, true)); } static bool M(int? i1, bool? b1) { var t1 = (i1, b1); return t1 == (null, null); } }"; var comp = CompileAndVerify(source, expectedOutput: "TrueFalse"); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @"{ // Code size 40 (0x28) .maxstack 2 .locals init (System.ValueTuple<int?, bool?> V_0) IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: newobj ""System.ValueTuple<int?, bool?>..ctor(int?, bool?)"" IL_0007: stloc.0 IL_0008: ldloca.s V_0 IL_000a: ldflda ""int? System.ValueTuple<int?, bool?>.Item1"" IL_000f: call ""bool int?.HasValue.get"" IL_0014: brtrue.s IL_0026 IL_0016: ldloca.s V_0 IL_0018: ldflda ""bool? System.ValueTuple<int?, bool?>.Item2"" IL_001d: call ""bool bool?.HasValue.get"" IL_0022: ldc.i4.0 IL_0023: ceq IL_0025: ret IL_0026: ldc.i4.0 IL_0027: ret }"); } [Fact] public void TestILForNullableElementsNotEqualsToNull() { var source = @" class C { static void Main() { System.Console.Write(M(null, null)); System.Console.Write(M(1, true)); } static bool M(int? i1, bool? b1) { var t1 = (i1, b1); return t1 != (null, null); } }"; var comp = CompileAndVerify(source, expectedOutput: "FalseTrue"); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @"{ // Code size 37 (0x25) .maxstack 2 .locals init (System.ValueTuple<int?, bool?> V_0) IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: newobj ""System.ValueTuple<int?, bool?>..ctor(int?, bool?)"" IL_0007: stloc.0 IL_0008: ldloca.s V_0 IL_000a: ldflda ""int? System.ValueTuple<int?, bool?>.Item1"" IL_000f: call ""bool int?.HasValue.get"" IL_0014: brtrue.s IL_0023 IL_0016: ldloca.s V_0 IL_0018: ldflda ""bool? System.ValueTuple<int?, bool?>.Item2"" IL_001d: call ""bool bool?.HasValue.get"" IL_0022: ret IL_0023: ldc.i4.1 IL_0024: ret }"); } [Fact] public void TestILForNullableElementsComparedToNonNullValues() { var source = @" class C { static void Main() { System.Console.Write(M((null, null))); System.Console.Write(M((2, true))); } static bool M((int?, bool?) t1) { return t1 == (2, true); } }"; var comp = CompileAndVerify(source, expectedOutput: "FalseTrue"); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @"{ // Code size 63 (0x3f) .maxstack 2 .locals init (System.ValueTuple<int?, bool?> V_0, int? V_1, int V_2, bool? V_3, bool V_4) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldfld ""int? System.ValueTuple<int?, bool?>.Item1"" IL_0008: stloc.1 IL_0009: ldc.i4.2 IL_000a: stloc.2 IL_000b: ldloca.s V_1 IL_000d: call ""int int?.GetValueOrDefault()"" IL_0012: ldloc.2 IL_0013: ceq IL_0015: ldloca.s V_1 IL_0017: call ""bool int?.HasValue.get"" IL_001c: and IL_001d: brfalse.s IL_003d IL_001f: ldloc.0 IL_0020: ldfld ""bool? System.ValueTuple<int?, bool?>.Item2"" IL_0025: stloc.3 IL_0026: ldc.i4.1 IL_0027: stloc.s V_4 IL_0029: ldloca.s V_3 IL_002b: call ""bool bool?.GetValueOrDefault()"" IL_0030: ldloc.s V_4 IL_0032: ceq IL_0034: ldloca.s V_3 IL_0036: call ""bool bool?.HasValue.get"" IL_003b: and IL_003c: ret IL_003d: ldc.i4.0 IL_003e: ret }"); } [Fact] public void TestILForNullableStructEqualsToNull() { var source = @" struct S { static void Main() { S? s = null; _ = s == null; System.Console.Write((s, null) == (null, s)); } }"; var comp = CompileAndVerify(source, expectedOutput: "True"); comp.VerifyDiagnostics(); comp.VerifyIL("S.Main", @"{ // Code size 48 (0x30) .maxstack 2 .locals init (S? V_0, //s S? V_1, S? V_2) IL_0000: ldloca.s V_0 IL_0002: initobj ""S?"" IL_0008: ldloca.s V_0 IL_000a: call ""bool S?.HasValue.get"" IL_000f: pop IL_0010: ldloc.0 IL_0011: stloc.1 IL_0012: ldloc.0 IL_0013: stloc.2 IL_0014: ldloca.s V_1 IL_0016: call ""bool S?.HasValue.get"" IL_001b: brtrue.s IL_0029 IL_001d: ldloca.s V_2 IL_001f: call ""bool S?.HasValue.get"" IL_0024: ldc.i4.0 IL_0025: ceq IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: call ""void System.Console.Write(bool)"" IL_002f: ret }"); } [Fact, WorkItem(25488, "https://github.com/dotnet/roslyn/issues/25488")] public void TestThisStruct() { var source = @" public struct S { public int I; public static void Main() { S s = new S() { I = 1 }; s.M(); } void M() { System.Console.Write((this, 2) == (1, this.Mutate())); } S Mutate() { I++; return this; } public static implicit operator S(int value) { return new S() { I = value }; } public static bool operator==(S s1, S s2) { System.Console.Write($""{s1.I} == {s2.I}, ""); return s1.I == s2.I; } public static bool operator!=(S s1, S s2) { throw null; } public override bool Equals(object o) { throw null; } public override int GetHashCode() { throw null; } }"; var comp = CompileAndVerify(source, expectedOutput: "1 == 1, 2 == 2, True"); comp.VerifyDiagnostics(); } [Fact] public void TestThisClass() { var source = @" public class C { public int I; public static void Main() { C c = new C() { I = 1 }; c.M(); } void M() { System.Console.Write((this, 2) == (2, this.Mutate())); } C Mutate() { I++; return this; } public static implicit operator C(int value) { return new C() { I = value }; } public static bool operator==(C c1, C c2) { System.Console.Write($""{c1.I} == {c2.I}, ""); return c1.I == c2.I; } public static bool operator!=(C c1, C c2) { throw null; } public override bool Equals(object o) { throw null; } public override int GetHashCode() { throw null; } }"; var comp = CompileAndVerify(source, expectedOutput: "2 == 2, 2 == 2, True"); comp.VerifyDiagnostics(); } [Fact] public void TestSimpleEqualOnTypelessTupleLiteral() { var source = @" class C { static bool M((string, long) t) { return t == (null, 1) && t == (""hello"", 1); } }"; var comp = CompileAndVerify(source); comp.VerifyDiagnostics(); var tree = comp.Compilation.SyntaxTrees.First(); var model = comp.Compilation.GetSemanticModel(tree); var tuple1 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(0); var symbol1 = model.GetTypeInfo(tuple1); Assert.Null(symbol1.Type); Assert.Equal("(System.String, System.Int64)", symbol1.ConvertedType.ToTestDisplayString()); Assert.Equal("(System.String, System.Int64)", model.GetDeclaredSymbol(tuple1).ToTestDisplayString()); var tuple2 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); var symbol2 = model.GetTypeInfo(tuple2); Assert.Equal("(System.String, System.Int32)", symbol2.Type.ToTestDisplayString()); Assert.Equal("(System.String, System.Int64)", symbol2.ConvertedType.ToTestDisplayString()); Assert.False(model.GetConstantValue(tuple2).HasValue); Assert.Equal(1, model.GetConstantValue(tuple2.Arguments[1].Expression).Value); } [Fact] public void TestConversionOnTupleExpression() { var source = @" class C { static bool M((int, byte) t) { return t == (1L, 2); } }"; var comp = CompileAndVerify(source); comp.VerifyDiagnostics(); var tree = comp.Compilation.SyntaxTrees.First(); var model = comp.Compilation.GetSemanticModel(tree); var equals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); // check t var t = equals.Left; Assert.Equal("t", t.ToString()); Assert.Equal("(System.Int32, System.Byte) t", model.GetSymbolInfo(t).Symbol.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTuple, model.GetConversion(t).Kind); var tTypeInfo = model.GetTypeInfo(t); Assert.Equal("(System.Int32, System.Byte)", tTypeInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, System.Int32)", tTypeInfo.ConvertedType.ToTestDisplayString()); // check tuple var tuple = equals.Right; Assert.Equal("(1L, 2)", tuple.ToString()); Assert.Null(model.GetSymbolInfo(tuple).Symbol); Assert.Equal(Conversion.Identity, model.GetConversion(tuple)); var tupleTypeInfo = model.GetTypeInfo(tuple); Assert.Equal("(System.Int64, System.Int32)", tupleTypeInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, System.Int32)", tupleTypeInfo.ConvertedType.ToTestDisplayString()); } [Fact] public void TestOtherOperatorsOnTuples() { var source = @" class C { void M() { var t1 = (1, 2); _ = t1 + t1; // error 1 _ = t1 > t1; // error 2 _ = t1 >= t1; // error 3 _ = !t1; // error 4 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,13): error CS0019: Operator '+' cannot be applied to operands of type '(int, int)' and '(int, int)' // _ = t1 + t1; // error 1 Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 + t1").WithArguments("+", "(int, int)", "(int, int)").WithLocation(7, 13), // (8,13): error CS0019: Operator '>' cannot be applied to operands of type '(int, int)' and '(int, int)' // _ = t1 > t1; // error 2 Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 > t1").WithArguments(">", "(int, int)", "(int, int)").WithLocation(8, 13), // (9,13): error CS0019: Operator '>=' cannot be applied to operands of type '(int, int)' and '(int, int)' // _ = t1 >= t1; // error 3 Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 >= t1").WithArguments(">=", "(int, int)", "(int, int)").WithLocation(9, 13), // (10,13): error CS0023: Operator '!' cannot be applied to operand of type '(int, int)' // _ = !t1; // error 4 Diagnostic(ErrorCode.ERR_BadUnaryOp, "!t1").WithArguments("!", "(int, int)").WithLocation(10, 13) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var tuple = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().Single(); Assert.Equal("(System.Int32, System.Int32)", model.GetDeclaredSymbol(tuple).ToTestDisplayString()); } [Fact] public void TestTypelessTuples() { var source = @" class C { static void Main() { string s = null; System.Console.Write((s, null) == (null, s)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); // check first tuple and its null var tuple1 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal("(s, null)", tuple1.ToString()); var tupleType1 = model.GetTypeInfo(tuple1); Assert.Null(tupleType1.Type); Assert.Equal("(System.String s, System.String)", tupleType1.ConvertedType.ToTestDisplayString()); var tuple1Null = tuple1.Arguments[1].Expression; var tuple1NullTypeInfo = model.GetTypeInfo(tuple1Null); Assert.Null(tuple1NullTypeInfo.Type); Assert.Equal("System.String", tuple1NullTypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitReference, model.GetConversion(tuple1Null).Kind); // check second tuple and its null var tuple2 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal("(null, s)", tuple2.ToString()); var tupleType2 = model.GetTypeInfo(tuple2); Assert.Null(tupleType2.Type); Assert.Equal("(System.String, System.String s)", tupleType2.ConvertedType.ToTestDisplayString()); var tuple2Null = tuple2.Arguments[0].Expression; var tuple2NullTypeInfo = model.GetTypeInfo(tuple2Null); Assert.Null(tuple2NullTypeInfo.Type); Assert.Equal("System.String", tuple2NullTypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitReference, model.GetConversion(tuple2Null).Kind); } [Fact] public void TestWithNoSideEffectsOrTemps() { var source = @" class C { static void Main() { System.Console.Write((1, 2) == (1, 3)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "False"); } [Fact] public void TestSimpleTupleAndTupleType_01() { var source = @" class C { static void Main() { var t1 = (1, 2L); System.Console.Write(t1 == (1L, 2)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var equals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); // check t1 var t1 = equals.Left; Assert.Equal("t1", t1.ToString()); var t1TypeInfo = model.GetTypeInfo(t1); Assert.Equal("(System.Int32, System.Int64)", t1TypeInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, System.Int64)", t1TypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTuple, model.GetConversion(t1).Kind); // check tuple and its literal 2 var tuple = (TupleExpressionSyntax)equals.Right; Assert.Equal("(1L, 2)", tuple.ToString()); var tupleType = model.GetTypeInfo(tuple); Assert.Equal("(System.Int64, System.Int32)", tupleType.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, System.Int64)", tupleType.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(tuple).Kind); var two = tuple.Arguments[1].Expression; Assert.Equal("2", two.ToString()); var twoType = model.GetTypeInfo(two); Assert.Equal("System.Int32", twoType.Type.ToTestDisplayString()); Assert.Equal("System.Int64", twoType.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitNumeric, model.GetConversion(two).Kind); } [Fact] public void TestSimpleTupleAndTupleType_02() { var source = @" class C { static void Main() { var t1 = (1, 2UL); System.Console.Write(t1 == (1L, 2)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var equals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); // check t1 var t1 = equals.Left; Assert.Equal("t1", t1.ToString()); var t1TypeInfo = model.GetTypeInfo(t1); Assert.Equal("(System.Int32, System.UInt64)", t1TypeInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, System.UInt64)", t1TypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTuple, model.GetConversion(t1).Kind); // check tuple and its literal 2 var tuple = (TupleExpressionSyntax)equals.Right; Assert.Equal("(1L, 2)", tuple.ToString()); var tupleType = model.GetTypeInfo(tuple); Assert.Equal("(System.Int64, System.Int32)", tupleType.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, System.UInt64)", tupleType.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(tuple).Kind); var two = tuple.Arguments[1].Expression; Assert.Equal("2", two.ToString()); var twoType = model.GetTypeInfo(two); Assert.Equal("System.Int32", twoType.Type.ToTestDisplayString()); Assert.Equal("System.UInt64", twoType.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitConstant, model.GetConversion(two).Kind); } [Fact] public void TestNestedTupleAndTupleType() { var source = @" class C { static void Main() { var t1 = (1, (2L, ""hello"")); var t2 = (2, ""hello""); System.Console.Write(t1 == (1L, t2)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var equals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); // check t1 var t1 = equals.Left; Assert.Equal("t1", t1.ToString()); var t1TypeInfo = model.GetTypeInfo(t1); Assert.Equal("(System.Int32, (System.Int64, System.String))", t1TypeInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, (System.Int64, System.String))", t1TypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTuple, model.GetConversion(t1).Kind); Assert.Equal("(System.Int32, (System.Int64, System.String)) t1", model.GetSymbolInfo(t1).Symbol.ToTestDisplayString()); // check tuple and its t2 var tuple = (TupleExpressionSyntax)equals.Right; Assert.Equal("(1L, t2)", tuple.ToString()); var tupleType = model.GetTypeInfo(tuple); Assert.Equal("(System.Int64, (System.Int32, System.String) t2)", tupleType.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, (System.Int64, System.String) t2)", tupleType.ConvertedType.ToTestDisplayString()); var t2 = tuple.Arguments[1].Expression; Assert.Equal("t2", t2.ToString()); var t2TypeInfo = model.GetTypeInfo(t2); Assert.Equal("(System.Int32, System.String)", t2TypeInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, System.String)", t2TypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTuple, model.GetConversion(t2).Kind); Assert.Equal("(System.Int32, System.String) t2", model.GetSymbolInfo(t2).Symbol.ToTestDisplayString()); } [Fact] public void TestTypelessTupleAndTupleType() { var source = @" class C { static void Main() { (string, string) t = (null, null); System.Console.Write(t == (null, null)); System.Console.Write(t != (null, null)); System.Console.Write((1, t) == (1, (null, null))); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueFalseTrue"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var tuple = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal("(null, null)", tuple.ToString()); var tupleType = model.GetTypeInfo(tuple); Assert.Null(tupleType.Type); Assert.Equal("(System.String, System.String)", tupleType.ConvertedType.ToTestDisplayString()); // check last tuple ... var lastEquals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Last(); var lastTuple = (TupleExpressionSyntax)lastEquals.Right; Assert.Equal("(1, (null, null))", lastTuple.ToString()); TypeInfo lastTupleTypeInfo = model.GetTypeInfo(lastTuple); Assert.Null(lastTupleTypeInfo.Type); Assert.Equal("(System.Int32, (System.String, System.String))", lastTupleTypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(lastTuple).Kind); // ... and its nested (null, null) tuple ... var nullNull = (TupleExpressionSyntax)lastTuple.Arguments[1].Expression; TypeInfo nullNullTypeInfo = model.GetTypeInfo(nullNull); Assert.Null(nullNullTypeInfo.Type); Assert.Equal("(System.String, System.String)", nullNullTypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(nullNull).Kind); // ... and its last null. var lastNull = nullNull.Arguments[1].Expression; TypeInfo lastNullTypeInfo = model.GetTypeInfo(lastNull); Assert.Null(lastNullTypeInfo.Type); Assert.Equal("System.String", lastNullTypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitReference, model.GetConversion(lastNull).Kind); } [Fact] public void TestTypedTupleAndDefault() { var source = @" class C { static void Main() { (string, string) t = (null, null); System.Console.Write(t == default); System.Console.Write(t != default); (string, string) t2 = (null, ""hello""); System.Console.Write(t2 == default); System.Console.Write(t2 != default); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueFalseFalseTrue"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var defaultLiterals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>() .Where(e => e.Kind() == SyntaxKind.DefaultLiteralExpression); foreach (var literal in defaultLiterals) { Assert.Equal("default", literal.ToString()); var info = model.GetTypeInfo(literal); Assert.Equal("(System.String, System.String)", info.Type.ToTestDisplayString()); Assert.Equal("(System.String, System.String)", info.ConvertedType.ToTestDisplayString()); } } [Fact] public void TestNullableTupleAndDefault() { var source = @" class C { static void Main() { (string, string)? t = (null, null); System.Console.Write(t == default); System.Console.Write(t != default); System.Console.Write(default == t); System.Console.Write(default != t); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "FalseTrueFalseTrue"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var defaultLiterals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>() .Where(e => e.Kind() == SyntaxKind.DefaultLiteralExpression); foreach (var literal in defaultLiterals) { Assert.Equal("default", literal.ToString()); var info = model.GetTypeInfo(literal); Assert.Equal("(System.String, System.String)?", info.Type.ToTestDisplayString()); Assert.Equal("(System.String, System.String)?", info.ConvertedType.ToTestDisplayString()); } } [Fact] public void TestNullableTupleAndDefault_Nested() { var source = @" class C { static void Main() { (string, string)? t = (null, null); System.Console.Write((null, t) == (null, default)); System.Console.Write((t, null) != (default, null)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "FalseTrue"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var defaultLiterals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>() .Where(e => e.Kind() == SyntaxKind.DefaultLiteralExpression); foreach (var literal in defaultLiterals) { Assert.Equal("default", literal.ToString()); var info = model.GetTypeInfo(literal); Assert.Equal("(System.String, System.String)?", info.Type.ToTestDisplayString()); Assert.Equal("(System.String, System.String)?", info.ConvertedType.ToTestDisplayString()); } } [Fact] public void TestNestedDefaultWithNonTupleType() { var source = @" class C { static void Main() { System.Console.Write((null, 1) == (null, default)); System.Console.Write((0, null) != (default, null)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "FalseFalse"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var defaultLiterals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>() .Where(e => e.Kind() == SyntaxKind.DefaultLiteralExpression); foreach (var literal in defaultLiterals) { Assert.Equal("default", literal.ToString()); var info = model.GetTypeInfo(literal); Assert.Equal("System.Int32", info.Type.ToTestDisplayString()); Assert.Equal("System.Int32", info.ConvertedType.ToTestDisplayString()); } } [Fact] public void TestNestedDefaultWithNullableNonTupleType() { var source = @" struct S { static void Main() { S? ns = null; _ = (null, ns) == (null, default); _ = (ns, null) != (default, null); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'default' // _ = (null, ns) == (null, default); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(null, ns) == (null, default)").WithArguments("==", "S?", "default").WithLocation(7, 13), // (8,13): error CS0019: Operator '!=' cannot be applied to operands of type 'S?' and 'default' // _ = (ns, null) != (default, null); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, null) != (default, null)").WithArguments("!=", "S?", "default").WithLocation(8, 13) ); } [Fact] public void TestNestedDefaultWithNullableNonTupleType_WithComparisonOperator() { var source = @" public struct S { public static void Main() { S? ns = new S(); System.Console.Write((null, ns) == (null, default)); System.Console.Write((ns, null) != (default, null)); } public static bool operator==(S s1, S s2) => throw null; public static bool operator!=(S s1, S s2) => throw null; public override int GetHashCode() => throw null; public override bool Equals(object o) => throw null; }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "FalseTrue"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var defaults = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>() .Where(e => e.Kind() == SyntaxKind.DefaultLiteralExpression); foreach (var literal in defaults) { var type = model.GetTypeInfo(literal); Assert.Equal("S?", type.Type.ToTestDisplayString()); Assert.Equal("S?", type.ConvertedType.ToTestDisplayString()); } } [Fact] public void TestAllDefaults() { var source = @" class C { static void Main() { System.Console.Write((default, default) == (default, default)); System.Console.Write(default == (default, default)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,30): error CS8315: Operator '==' is ambiguous on operands 'default' and 'default' // System.Console.Write((default, default) == (default, default)); Diagnostic(ErrorCode.ERR_AmbigBinaryOpsOnDefault, "(default, default) == (default, default)").WithArguments("==", "default", "default").WithLocation(6, 30), // (6,30): error CS8315: Operator '==' is ambiguous on operands 'default' and 'default' // System.Console.Write((default, default) == (default, default)); Diagnostic(ErrorCode.ERR_AmbigBinaryOpsOnDefault, "(default, default) == (default, default)").WithArguments("==", "default", "default").WithLocation(6, 30), // (7,30): error CS0034: Operator '==' is ambiguous on operands of type 'default' and '(default, default)' // System.Console.Write(default == (default, default)); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "default == (default, default)").WithArguments("==", "default", "(default, default)").WithLocation(7, 30) ); } [Fact] public void TestNullsAndDefaults() { var source = @" class C { static void Main() { _ = (null, default) != (default, null); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,13): error CS0034: Operator '!=' is ambiguous on operands of type '<null>' and 'default' // _ = (null, default) != (default, null); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "(null, default) != (default, null)").WithArguments("!=", "<null>", "default").WithLocation(6, 13), // (6,13): error CS0034: Operator '!=' is ambiguous on operands of type 'default' and '<null>' // _ = (null, default) != (default, null); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "(null, default) != (default, null)").WithArguments("!=", "default", "<null>").WithLocation(6, 13) ); } [Fact] public void TestAllDefaults_Nested() { var source = @" class C { static void Main() { System.Console.Write((null, (default, default)) == (null, (default, default))); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,30): error CS8315: Operator '==' is ambiguous on operands 'default' and 'default' // System.Console.Write((null, (default, default)) == (null, (default, default))); Diagnostic(ErrorCode.ERR_AmbigBinaryOpsOnDefault, "(null, (default, default)) == (null, (default, default))").WithArguments("==", "default", "default").WithLocation(6, 30), // (6,30): error CS8315: Operator '==' is ambiguous on operands 'default' and 'default' // System.Console.Write((null, (default, default)) == (null, (default, default))); Diagnostic(ErrorCode.ERR_AmbigBinaryOpsOnDefault, "(null, (default, default)) == (null, (default, default))").WithArguments("==", "default", "default").WithLocation(6, 30) ); } [Fact] public void TestTypedTupleAndTupleOfDefaults() { var source = @" class C { static void Main() { (string, string)? t = (null, null); System.Console.Write(t == (default, default)); System.Console.Write(t != (default, default)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueFalse"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var lastTuple = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().Last(); Assert.Equal("(default, default)", lastTuple.ToString()); Assert.Null(model.GetTypeInfo(lastTuple).Type); Assert.Equal("(System.String, System.String)?", model.GetTypeInfo(lastTuple).ConvertedType.ToTestDisplayString()); var lastDefault = lastTuple.Arguments[1].Expression; Assert.Equal("default", lastDefault.ToString()); Assert.Equal("System.String", model.GetTypeInfo(lastDefault).Type.ToTestDisplayString()); Assert.Equal("System.String", model.GetTypeInfo(lastDefault).ConvertedType.ToTestDisplayString()); } [Fact] public void TestTypelessTupleAndTupleOfDefaults() { var source = @" class C { static void Main() { System.Console.Write((null, () => 1) == (default, default)); System.Console.Write((null, () => 2) == default); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,30): error CS0034: Operator '==' is ambiguous on operands of type '<null>' and 'default' // System.Console.Write((null, () => 1) == (default, default)); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "(null, () => 1) == (default, default)").WithArguments("==", "<null>", "default").WithLocation(6, 30), // (6,30): error CS0019: Operator '==' cannot be applied to operands of type 'lambda expression' and 'default' // System.Console.Write((null, () => 1) == (default, default)); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(null, () => 1) == (default, default)").WithArguments("==", "lambda expression", "default").WithLocation(6, 30), // (7,30): error CS0034: Operator '==' is ambiguous on operands of type '(<null>, lambda expression)' and 'default' // System.Console.Write((null, () => 2) == default); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "(null, () => 2) == default").WithArguments("==", "(<null>, lambda expression)", "default").WithLocation(7, 30) ); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,30): error CS0034: Operator '==' is ambiguous on operands of type '<null>' and 'default' // System.Console.Write((null, () => 1) == (default, default)); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "(null, () => 1) == (default, default)").WithArguments("==", "<null>", "default").WithLocation(6, 30), // (7,30): error CS0034: Operator '==' is ambiguous on operands of type '(<null>, lambda expression)' and 'default' // System.Console.Write((null, () => 2) == default); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "(null, () => 2) == default").WithArguments("==", "(<null>, lambda expression)", "default").WithLocation(7, 30) ); } [Fact] public void TestNullableStructAndDefault() { var source = @" struct S { static void M(string s) { S? ns = new S(); _ = ns == null; _ = s == null; _ = ns == default; // error 1 _ = (ns, ns) == (null, null); _ = (ns, ns) == (default, default); // errors 2 and 3 _ = (ns, ns) == default; // error 4 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'default' // _ = ns == default; // error 1 Diagnostic(ErrorCode.ERR_BadBinaryOps, "ns == default").WithArguments("==", "S?", "default").WithLocation(9, 13), // (11,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'default' // _ = (ns, ns) == (default, default); // errors 2 and 3 Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, ns) == (default, default)").WithArguments("==", "S?", "default").WithLocation(11, 13), // (11,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'default' // _ = (ns, ns) == (default, default); // errors 2 and 3 Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, ns) == (default, default)").WithArguments("==", "S?", "default").WithLocation(11, 13), // (12,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'S?' // _ = (ns, ns) == default; // error 4 Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, ns) == default").WithArguments("==", "S?", "S?").WithLocation(12, 13), // (12,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'S?' // _ = (ns, ns) == default; // error 4 Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, ns) == default").WithArguments("==", "S?", "S?").WithLocation(12, 13) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var literals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>(); var nullLiteral = literals.ElementAt(0); Assert.Equal("null", nullLiteral.ToString()); Assert.Null(model.GetTypeInfo(nullLiteral).ConvertedType); var nullLiteral2 = literals.ElementAt(1); Assert.Equal("null", nullLiteral2.ToString()); Assert.Null(model.GetTypeInfo(nullLiteral2).Type); Assert.Equal("System.String", model.GetTypeInfo(nullLiteral2).ConvertedType.ToTestDisplayString()); var defaultLiterals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>() .Where(e => e.Kind() == SyntaxKind.DelegateDeclaration); foreach (var defaultLiteral in defaultLiterals) { Assert.Equal("default", defaultLiteral.ToString()); Assert.Null(model.GetTypeInfo(defaultLiteral).Type); Assert.Null(model.GetTypeInfo(defaultLiteral).ConvertedType); } } [Fact, WorkItem(25318, "https://github.com/dotnet/roslyn/issues/25318")] public void TestNullableStructAndDefault_WithComparisonOperator() { var source = @" public struct S { static void M(string s) { S? ns = new S(); _ = ns == 1; _ = (ns, ns) == (default, default); _ = (ns, ns) == default; } public static bool operator==(S s, byte b) => throw null; public static bool operator!=(S s, byte b) => throw null; public override bool Equals(object other) => throw null; public override int GetHashCode() => throw null; }"; var comp = CreateCompilation(source); // https://github.com/dotnet/roslyn/issues/25318 // This should be allowed comp.VerifyDiagnostics( // (7,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'int' // _ = ns == 1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "ns == 1").WithArguments("==", "S?", "int").WithLocation(7, 13), // (8,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'default' // _ = (ns, ns) == (default, default); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, ns) == (default, default)").WithArguments("==", "S?", "default").WithLocation(8, 13), // (8,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'default' // _ = (ns, ns) == (default, default); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, ns) == (default, default)").WithArguments("==", "S?", "default").WithLocation(8, 13), // (9,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'S?' // _ = (ns, ns) == default; Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, ns) == default").WithArguments("==", "S?", "S?").WithLocation(9, 13), // (9,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'S?' // _ = (ns, ns) == default; Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, ns) == default").WithArguments("==", "S?", "S?").WithLocation(9, 13) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var defaultLiterals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>() .Where(e => e.Kind() == SyntaxKind.DelegateDeclaration); // Should have types foreach (var defaultLiteral in defaultLiterals) { Assert.Equal("default", defaultLiteral.ToString()); Assert.Null(model.GetTypeInfo(defaultLiteral).Type); Assert.Null(model.GetTypeInfo(defaultLiteral).ConvertedType); // https://github.com/dotnet/roslyn/issues/25318 // default should become int } } [Fact] public void TestMixedTupleLiteralsAndTypes() { var source = @" class C { static void Main() { (string, string) t = (null, null); System.Console.Write((t, (null, null)) == ((null, null), t)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); // check last tuple ... var tuple = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(3); Assert.Equal("((null, null), t)", tuple.ToString()); var tupleType = model.GetTypeInfo(tuple); Assert.Null(tupleType.Type); Assert.Equal("((System.String, System.String), (System.String, System.String) t)", tupleType.ConvertedType.ToTestDisplayString()); // ... its t ... var t = tuple.Arguments[1].Expression; Assert.Equal("t", t.ToString()); var tType = model.GetTypeInfo(t); Assert.Equal("(System.String, System.String)", tType.Type.ToTestDisplayString()); Assert.Equal("(System.String, System.String)", tType.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, model.GetConversion(t).Kind); Assert.Equal("(System.String, System.String) t", model.GetSymbolInfo(t).Symbol.ToTestDisplayString()); Assert.Null(model.GetDeclaredSymbol(t)); // ... its nested tuple ... var nestedTuple = (TupleExpressionSyntax)tuple.Arguments[0].Expression; Assert.Equal("(null, null)", nestedTuple.ToString()); var nestedTupleType = model.GetTypeInfo(nestedTuple); Assert.Null(nestedTupleType.Type); Assert.Equal("(System.String, System.String)", nestedTupleType.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(nestedTuple).Kind); Assert.Null(model.GetSymbolInfo(nestedTuple).Symbol); Assert.Equal("(System.String, System.String)", model.GetDeclaredSymbol(nestedTuple).ToTestDisplayString()); // ... a nested null. var nestedNull = nestedTuple.Arguments[0].Expression; Assert.Equal("null", nestedNull.ToString()); var nestedNullType = model.GetTypeInfo(nestedNull); Assert.Null(nestedNullType.Type); Assert.Equal("System.String", nestedNullType.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitReference, model.GetConversion(nestedNull).Kind); } [Fact] public void TestAllNulls() { var source = @" class C { static void Main() { System.Console.Write(null == null); System.Console.Write((null, null) == (null, null)); System.Console.Write((null, null) != (null, null)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueTrueFalse"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var nulls = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>(); foreach (var literal in nulls) { Assert.Equal("null", literal.ToString()); var symbol = model.GetTypeInfo(literal); Assert.Null(symbol.Type); Assert.Null(symbol.ConvertedType); } var tuples = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>(); foreach (var tuple in tuples) { Assert.Equal("(null, null)", tuple.ToString()); var symbol = model.GetTypeInfo(tuple); Assert.Null(symbol.Type); Assert.Null(symbol.ConvertedType); } } [Fact] public void TestConvertedElementInTypelessTuple() { var source = @" class C { static void Main() { System.Console.Write((null, 1L) == (null, 2)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "False"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var lastLiteral = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Last(); Assert.Equal("2", lastLiteral.ToString()); var literalInfo = model.GetTypeInfo(lastLiteral); Assert.Equal("System.Int32", literalInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int64", literalInfo.ConvertedType.ToTestDisplayString()); } [Fact] public void TestConvertedElementInTypelessTuple_Nested() { var source = @" class C { static void Main() { System.Console.Write(((null, 1L), null) == ((null, 2), null)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "False"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var rightTuple = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(2); Assert.Equal("((null, 2), null)", rightTuple.ToString()); var literalInfo = model.GetTypeInfo(rightTuple); Assert.Null(literalInfo.Type); Assert.Null(literalInfo.ConvertedType); var nestedTuple = (TupleExpressionSyntax)rightTuple.Arguments[0].Expression; Assert.Equal("(null, 2)", nestedTuple.ToString()); var nestedLiteralInfo = model.GetTypeInfo(rightTuple); Assert.Null(nestedLiteralInfo.Type); Assert.Null(nestedLiteralInfo.ConvertedType); var two = nestedTuple.Arguments[1].Expression; Assert.Equal("2", two.ToString()); var twoInfo = model.GetTypeInfo(two); Assert.Equal("System.Int32", twoInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int64", twoInfo.ConvertedType.ToTestDisplayString()); } [Fact] public void TestFailedInference() { var source = @" class C { static void Main() { System.Console.Write((null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,30): error CS0019: Operator '==' cannot be applied to operands of type '<null>' and 'lambda expression' // System.Console.Write((null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })").WithArguments("==", "<null>", "lambda expression").WithLocation(6, 30), // (6,30): error CS0019: Operator '==' cannot be applied to operands of type '<null>' and 'method group' // System.Console.Write((null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })").WithArguments("==", "<null>", "method group").WithLocation(6, 30), // (6,30): error CS0019: Operator '==' cannot be applied to operands of type '<null>' and 'lambda expression' // System.Console.Write((null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })").WithArguments("==", "<null>", "lambda expression").WithLocation(6, 30)); verify(comp, inferDelegate: false); comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,65): error CS8917: The delegate type could not be inferred. // System.Console.Write((null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(6, 65), // (6,65): error CS8917: The delegate type could not be inferred. // System.Console.Write((null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(6, 65)); verify(comp, inferDelegate: true); static void verify(CSharpCompilation comp, bool inferDelegate) { var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); // check tuple on the left var tuple1 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal("(null, null, null, null)", tuple1.ToString()); var tupleType1 = model.GetTypeInfo(tuple1); Assert.Null(tupleType1.Type); Assert.Null(tupleType1.ConvertedType); // check tuple on the right ... var tuple2 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal("(null, x => x, Main, (int i) => { int j = 0; return i + j; })", tuple2.ToString()); var tupleType2 = model.GetTypeInfo(tuple2); Assert.Null(tupleType2.Type); Assert.Null(tupleType2.ConvertedType); // ... its first lambda ... var firstLambda = tuple2.Arguments[1].Expression; Assert.Null(model.GetTypeInfo(firstLambda).Type); verifyType("System.Delegate", model.GetTypeInfo(firstLambda).ConvertedType, inferDelegate); // ... its method group ... var methodGroup = tuple2.Arguments[2].Expression; Assert.Null(model.GetTypeInfo(methodGroup).Type); verifyType("System.Delegate", model.GetTypeInfo(methodGroup).ConvertedType, inferDelegate); Assert.Null(model.GetSymbolInfo(methodGroup).Symbol); Assert.Equal(new[] { "void C.Main()" }, model.GetSymbolInfo(methodGroup).CandidateSymbols.Select(s => s.ToTestDisplayString())); // ... its second lambda and the symbols it uses var secondLambda = tuple2.Arguments[3].Expression; verifyType("System.Func<System.Int32, System.Int32>", model.GetTypeInfo(secondLambda).Type, inferDelegate); verifyType("System.Delegate", model.GetTypeInfo(secondLambda).ConvertedType, inferDelegate); var addition = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Last(); Assert.Equal("i + j", addition.ToString()); var i = addition.Left; Assert.Equal("System.Int32 i", model.GetSymbolInfo(i).Symbol.ToTestDisplayString()); var j = addition.Right; Assert.Equal("System.Int32 j", model.GetSymbolInfo(j).Symbol.ToTestDisplayString()); } static void verifyType(string expectedType, ITypeSymbol type, bool inferDelegate) { if (inferDelegate) { Assert.Equal(expectedType, type.ToTestDisplayString()); } else { Assert.Null(type); } } } [Fact] public void TestVoidTypeElement() { var source = @" class C { static void Main() { System.Console.Write((Main(), null) != (null, Main())); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,31): error CS8210: A tuple may not contain a value of type 'void'. // System.Console.Write((Main(), null) != (null, Main())); Diagnostic(ErrorCode.ERR_VoidInTuple, "Main()").WithLocation(6, 31), // (6,55): error CS8210: A tuple may not contain a value of type 'void'. // System.Console.Write((Main(), null) != (null, Main())); Diagnostic(ErrorCode.ERR_VoidInTuple, "Main()").WithLocation(6, 55) ); } [Fact] public void TestFailedConversion() { var source = @" class C { static void M(string s) { System.Console.Write((s, s) == (1, () => { })); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,30): error CS0019: Operator '==' cannot be applied to operands of type 'string' and 'int' // System.Console.Write((s, s) == (1, () => { })); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(s, s) == (1, () => { })").WithArguments("==", "string", "int").WithLocation(6, 30), // (6,30): error CS0019: Operator '==' cannot be applied to operands of type 'string' and 'lambda expression' // System.Console.Write((s, s) == (1, () => { })); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(s, s) == (1, () => { })").WithArguments("==", "string", "lambda expression").WithLocation(6, 30) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var tuple1 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal("(s, s)", tuple1.ToString()); var tupleType1 = model.GetTypeInfo(tuple1); Assert.Equal("(System.String, System.String)", tupleType1.Type.ToTestDisplayString()); Assert.Equal("(System.String, System.String)", tupleType1.ConvertedType.ToTestDisplayString()); var tuple2 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal("(1, () => { })", tuple2.ToString()); var tupleType2 = model.GetTypeInfo(tuple2); Assert.Null(tupleType2.Type); Assert.Null(tupleType2.ConvertedType); } [Fact] public void TestDynamic() { var source = @" public class C { public static void Main() { dynamic d1 = 1; dynamic d2 = 2; System.Console.Write($""{(d1, 2) == (1, d2)} ""); System.Console.Write($""{(d1, 2) != (1, d2)} ""); System.Console.Write($""{(d1, 20) == (10, d2)} ""); System.Console.Write($""{(d1, 20) != (10, d2)} ""); } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True False False True"); } [Fact] public void TestDynamicWithConstants() { var source = @" public class C { public static void Main() { System.Console.Write($""{((dynamic)true, (dynamic)false) == ((dynamic)true, (dynamic)false)} ""); } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); } [Fact] public void TestDynamic_WithTypelessExpression() { var source = @" public class C { public static void Main() { dynamic d1 = 1; dynamic d2 = 2; System.Console.Write((d1, 2) == (() => 1, d2)); } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (8,30): error CS0019: Operator '==' cannot be applied to operands of type 'dynamic' and 'lambda expression' // System.Console.Write((d1, 2) == (() => 1, d2)); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(d1, 2) == (() => 1, d2)").WithArguments("==", "dynamic", "lambda expression").WithLocation(8, 30) ); } [Fact] public void TestDynamic_WithBooleanConstants() { var source = @" public class C { public static void Main() { System.Console.Write(((dynamic)true, (dynamic)false) == (true, false)); System.Console.Write(((dynamic)true, (dynamic)false) != (true, false)); } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueFalse"); } [Fact] public void TestDynamic_WithBadType() { var source = @" public class C { public static void Main() { System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture; dynamic d1 = 1; dynamic d2 = 2; try { bool b = ((d1, 2) == (""hello"", d2)); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { System.Console.Write(e.Message); } finally { System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture; } } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Operator '==' cannot be applied to operands of type 'int' and 'string'"); } [Fact] public void TestDynamic_WithNull() { var source = @" public class C { public static void Main() { dynamic d1 = null; dynamic d2 = null; System.Console.Write((d1, null) == (null, d2)); } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var tuple1 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal("(d1, null)", tuple1.ToString()); var tupleType1 = model.GetTypeInfo(tuple1); Assert.Null(tupleType1.Type); Assert.Equal("(dynamic d1, dynamic)", tupleType1.ConvertedType.ToTestDisplayString()); var tuple2 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal("(null, d2)", tuple2.ToString()); var tupleType2 = model.GetTypeInfo(tuple2); Assert.Null(tupleType2.Type); Assert.Equal("(dynamic, dynamic d2)", tupleType2.ConvertedType.ToTestDisplayString()); } [Fact] public void TestBadConstraintOnTuple() { // https://github.com/dotnet/roslyn/issues/37121 : This test appears to produce a duplicate diagnostic at (6, 35) var source = @" ref struct S { void M(S s1, S s2) { System.Console.Write(("""", s1) == (null, s2)); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,35): error CS0306: The type 'S' may not be used as a type argument // System.Console.Write(("", s1) == (null, s2)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "s1").WithArguments("S").WithLocation(6, 35), // (6,30): error CS0019: Operator '==' cannot be applied to operands of type 'S' and 'S' // System.Console.Write(("", s1) == (null, s2)); Diagnostic(ErrorCode.ERR_BadBinaryOps, @"("""", s1) == (null, s2)").WithArguments("==", "S", "S").WithLocation(6, 30), // (6,35): error CS0306: The type 'S' may not be used as a type argument // System.Console.Write(("", s1) == (null, s2)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "s1").WithArguments("S").WithLocation(6, 35), // (6,49): error CS0306: The type 'S' may not be used as a type argument // System.Console.Write(("", s1) == (null, s2)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "s2").WithArguments("S").WithLocation(6, 49) ); } [Fact] public void TestErrorInTuple() { var source = @" public class C { public void M() { if (error1 == (error2, 3)) { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,13): error CS0103: The name 'error1' does not exist in the current context // if (error1 == (error2, 3)) { } Diagnostic(ErrorCode.ERR_NameNotInContext, "error1").WithArguments("error1").WithLocation(6, 13), // (6,24): error CS0103: The name 'error2' does not exist in the current context // if (error1 == (error2, 3)) { } Diagnostic(ErrorCode.ERR_NameNotInContext, "error2").WithArguments("error2").WithLocation(6, 24) ); } [Fact] public void TestWithTypelessTuple() { var source = @" public class C { public void M() { var t = (null, null); if (null == (() => {}) ) {} if ("""" == 1) {} } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,13): error CS0815: Cannot assign (<null>, <null>) to an implicitly-typed variable // var t = (null, null); Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "t = (null, null)").WithArguments("(<null>, <null>)").WithLocation(6, 13), // (7,13): error CS0019: Operator '==' cannot be applied to operands of type '<null>' and 'lambda expression' // if (null == (() => {}) ) {} Diagnostic(ErrorCode.ERR_BadBinaryOps, "null == (() => {})").WithArguments("==", "<null>", "lambda expression").WithLocation(7, 13), // (8,13): error CS0019: Operator '==' cannot be applied to operands of type 'string' and 'int' // if ("" == 1) {} Diagnostic(ErrorCode.ERR_BadBinaryOps, @""""" == 1").WithArguments("==", "string", "int").WithLocation(8, 13) ); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,13): error CS0815: Cannot assign (<null>, <null>) to an implicitly-typed variable // var t = (null, null); Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "t = (null, null)").WithArguments("(<null>, <null>)").WithLocation(6, 13), // (8,13): error CS0019: Operator '==' cannot be applied to operands of type 'string' and 'int' // if ("" == 1) {} Diagnostic(ErrorCode.ERR_BadBinaryOps, @""""" == 1").WithArguments("==", "string", "int").WithLocation(8, 13) ); } [Fact] public void TestTupleEqualityPreferredOverCustomOperator() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public static bool operator ==(ValueTuple<T1, T2> t1, ValueTuple<T1, T2> t2) => throw null; public static bool operator !=(ValueTuple<T1, T2> t1, ValueTuple<T1, T2> t2) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } } public class C { public static void Main() { var t1 = (1, 1); var t2 = (2, 2); System.Console.Write(t1 == t2); System.Console.Write(t1 != t2); } } "; var comp = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); // Note: tuple equality picked ahead of custom operator== (small compat break) CompileAndVerify(comp, expectedOutput: "FalseTrue"); } [Fact] public void TestCustomOperatorPlusAllowed() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public static ValueTuple<T1, T2> operator +(ValueTuple<T1, T2> t1, ValueTuple<T1, T2> t2) => (default(T1), default(T2)); public override string ToString() => $""({Item1}, {Item2})""; } } public class C { public static void Main() { var t1 = (0, 1); var t2 = (2, 3); System.Console.Write(t1 + t2); } } "; var comp = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "(0, 0)"); } [Fact] void TestTupleEqualityPreferredOverCustomOperator_Nested() { string source = @" public class C { public static void Main() { System.Console.Write( (1, 2, (3, 4)) == (1, 2, (3, 4)) ); } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public static bool operator ==(ValueTuple<T1, T2> t1, ValueTuple<T1, T2> t2) => throw null; public static bool operator !=(ValueTuple<T1, T2> t1, ValueTuple<T1, T2> t2) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public struct ValueTuple<T1, T2, T3> { public T1 Item1; public T2 Item2; public T3 Item3; public ValueTuple(T1 item1, T2 item2, T3 item3) { this.Item1 = item1; this.Item2 = item2; this.Item3 = item3; } } } "; var comp = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); // Note: tuple equality picked ahead of custom operator== CompileAndVerify(comp, expectedOutput: "True"); } [Fact] public void TestNaN() { var source = @" public class C { public static void Main() { var t1 = (System.Double.NaN, 1); var t2 = (System.Double.NaN, 1); System.Console.Write($""{t1 == t2} {t1.Equals(t2)} {t1 != t2} {t1 == (System.Double.NaN, 1)}""); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "False True True False"); } [Fact] public void TestTopLevelDynamic() { var source = @" public class C { public static void Main() { System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture; dynamic d1 = (1, 1); try { try { _ = d1 == (1, 1); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { System.Console.WriteLine(e.Message); } try { _ = d1 != (1, 2); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { System.Console.WriteLine(e.Message); } } finally { System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture; } } } "; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"Operator '==' cannot be applied to operands of type 'System.ValueTuple<int,int>' and 'System.ValueTuple<int,int>' Operator '!=' cannot be applied to operands of type 'System.ValueTuple<int,int>' and 'System.ValueTuple<int,int>'"); } [Fact] public void TestNestedDynamic() { var source = @" public class C { public static void Main() { System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture; dynamic d1 = (1, 1, 1); try { try { _ = (2, d1) == (2, (1, 1, 1)); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { System.Console.WriteLine(e.Message); } try { _ = (3, d1) != (3, (1, 2, 3)); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { System.Console.WriteLine(e.Message); } } finally { System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture; } } } "; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"Operator '==' cannot be applied to operands of type 'System.ValueTuple<int,int,int>' and 'System.ValueTuple<int,int,int>' Operator '!=' cannot be applied to operands of type 'System.ValueTuple<int,int,int>' and 'System.ValueTuple<int,int,int>'"); } [Fact] public void TestComparisonWithDeconstructionResult() { var source = @" public class C { public static void Main() { var b1 = (1, 2) == ((_, _) = new C()); var b2 = (1, 42) != ((_, _) = new C()); var b3 = (1, 42) == ((_, _) = new C()); // false var b4 = ((_, _) = new C()) == (1, 2); var b5 = ((_, _) = new C()) != (1, 42); var b6 = ((_, _) = new C()) == (1, 42); // false System.Console.Write($""{b1} {b2} {b3} {b4} {b5} {b6}""); } public void Deconstruct(out int x, out int y) { x = 1; y = 2; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"True True False True True False"); } [Fact] public void TestComparisonWithDeconstruction() { var source = @" public class C { public static void Main() { var b1 = (1, 2) == new C(); } public void Deconstruct(out int x, out int y) { x = 1; y = 2; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): error CS0019: Operator '==' cannot be applied to operands of type '(int, int)' and 'C' // var b1 = (1, 2) == new C(); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(1, 2) == new C()").WithArguments("==", "(int, int)", "C").WithLocation(6, 18) ); } [Fact] public void TestEvaluationOrderOnTupleLiteral() { var source = @" public class C { public static void Main() { System.Console.Write($""{EXPRESSION}""); } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; throw null; } } } public class Base { public int I; public Base(int i) { I = i; } } public class A : Base { public A(int i) : base(i) { System.Console.Write($""A:{i}, ""); } public static bool operator ==(A a, Y y) { System.Console.Write($""A({a.I}) == Y({y.I}), ""); return a.I == y.I; } public static bool operator !=(A a, Y y) { System.Console.Write($""A({a.I}) != Y({y.I}), ""); return a.I != y.I; } public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) { System.Console.Write($""X:{i}, ""); } } public class Y : Base { public Y(int i) : base(i) { System.Console.Write($""Y:{i}, ""); } public static implicit operator Y(X x) { System.Console.Write(""X -> ""); return new Y(x.I); } } "; validate("(new A(1), new A(2)) == (new X(1), new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A(1) == Y(1), A(2) == Y(2), True"); validate("(new A(1), new A(2)) == (new X(30), new Y(40))", "A:1, A:2, X:30, Y:40, X -> Y:30, A(1) == Y(30), False"); validate("(new A(1), new A(2)) == (new X(1), new Y(50))", "A:1, A:2, X:1, Y:50, X -> Y:1, A(1) == Y(1), A(2) == Y(50), False"); validate("(new A(1), new A(2)) != (new X(1), new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A(1) != Y(1), A(2) != Y(2), False"); validate("(new A(1), new A(2)) != (new Y(1), new X(2))", "A:1, A:2, Y:1, X:2, A(1) != Y(1), X -> Y:2, A(2) != Y(2), False"); validate("(new A(1), new A(2)) != (new X(30), new Y(40))", "A:1, A:2, X:30, Y:40, X -> Y:30, A(1) != Y(30), True"); validate("(new A(1), new A(2)) != (new X(50), new Y(2))", "A:1, A:2, X:50, Y:2, X -> Y:50, A(1) != Y(50), True"); validate("(new A(1), new A(2)) != (new X(1), new Y(60))", "A:1, A:2, X:1, Y:60, X -> Y:1, A(1) != Y(1), A(2) != Y(60), True"); void validate(string expression, string expected) { var comp = CreateCompilation(source.Replace("EXPRESSION", expression), options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: expected); } } [Fact] public void TestEvaluationOrderOnTupleType() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { System.Console.Write(""ValueTuple2, ""); this.Item1 = item1; this.Item2 = item2; } } public struct ValueTuple<T1, T2, T3> { public ValueTuple(T1 item1, T2 item2, T3 item3) { // ValueTuple'3 required (constructed in bound tree), but not emitted throw null; } } } public class Base { public int I; public Base(int i) { I = i; } } public class A : Base { public A(int i) : base(i) { System.Console.Write($""A:{i}, ""); } public static bool operator ==(A a, Y y) { System.Console.Write($""A({a.I}) == Y({y.I}), ""); return true; } public static bool operator !=(A a, Y y) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) { System.Console.Write($""X:{i}, ""); } } public class Y : Base { public Y(int i) : base(i) { System.Console.Write($""Y:{i}, ""); } public static implicit operator Y(X x) { System.Console.Write(""X -> ""); return new Y(x.I); } } public class C { public static void Main() { System.Console.Write($""{(new A(1), GetTuple(), new A(4)) == (new X(5), (new X(6), new Y(7)), new Y(8))}""); } public static (A, A) GetTuple() { System.Console.Write($""GetTuple, ""); return (new A(30), new A(40)); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "A:1, GetTuple, A:30, A:40, ValueTuple2, A:4, X:5, X:6, Y:7, Y:8, X -> Y:5, A(1) == Y(5), X -> Y:6, A(30) == Y(6), A(40) == Y(7), A(4) == Y(8), True"); } [Fact] public void TestConstrainedValueTuple() { var source = @" class C { void M() { _ = (this, this) == (0, 1); // constraint violated by tuple in source _ = (this, this) == (this, this); // constraint violated by converted tuple } public static bool operator ==(C c, int i) => throw null; public static bool operator !=(C c, int i) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; public static implicit operator int(C c) => throw null; } namespace System { public struct ValueTuple<T1, T2> where T1 : class where T2 : class { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; throw null; } } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,30): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T1' in the generic type or method '(T1, T2)' // _ = (this, this) == (0, 1); // constraint violated by tuple in source Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "0").WithArguments("(T1, T2)", "T1", "int").WithLocation(6, 30), // (6,30): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T1' in the generic type or method '(T1, T2)' // _ = (this, this) == (0, 1); // constraint violated by tuple in source Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "0").WithArguments("(T1, T2)", "T1", "int").WithLocation(6, 30), // (6,33): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T2' in the generic type or method '(T1, T2)' // _ = (this, this) == (0, 1); // constraint violated by tuple in source Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "1").WithArguments("(T1, T2)", "T2", "int").WithLocation(6, 33), // (6,33): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T2' in the generic type or method '(T1, T2)' // _ = (this, this) == (0, 1); // constraint violated by tuple in source Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "1").WithArguments("(T1, T2)", "T2", "int").WithLocation(6, 33), // (7,30): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T1' in the generic type or method '(T1, T2)' // _ = (this, this) == (this, this); // constraint violated by converted tuple Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "this").WithArguments("(T1, T2)", "T1", "int").WithLocation(7, 30), // (7,36): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T2' in the generic type or method '(T1, T2)' // _ = (this, this) == (this, this); // constraint violated by converted tuple Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "this").WithArguments("(T1, T2)", "T2", "int").WithLocation(7, 36) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); // check the int tuple var firstEquals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); var intTuple = firstEquals.Right; Assert.Equal("(0, 1)", intTuple.ToString()); var intTupleType = model.GetTypeInfo(intTuple); Assert.Equal("(System.Int32, System.Int32)", intTupleType.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)", intTupleType.ConvertedType.ToTestDisplayString()); // check the last tuple var secondEquals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Last(); var lastTuple = secondEquals.Right; Assert.Equal("(this, this)", lastTuple.ToString()); var lastTupleType = model.GetTypeInfo(lastTuple); Assert.Equal("(C, C)", lastTupleType.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)", lastTupleType.ConvertedType.ToTestDisplayString()); } [Fact] public void TestConstrainedNullable() { var source = @" class C { void M((int, int)? t1, (long, long)? t2) { _ = t1 == t2; } } public interface IInterface { } namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Int32 { } public struct Int64 { } public struct Nullable<T> where T : struct, IInterface { public T GetValueOrDefault() => default(T); } public class Exception { } public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; throw null; } } } "; var comp = CreateEmptyCompilation(source); comp.VerifyDiagnostics( // (4,24): error CS0315: The type '(int, int)' cannot be used as type parameter 'T' in the generic type or method 'Nullable<T>'. There is no boxing conversion from '(int, int)' to 'IInterface'. // void M((int, int)? t1, (long, long)? t2) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "t1").WithArguments("System.Nullable<T>", "IInterface", "T", "(int, int)").WithLocation(4, 24), // (4,42): error CS0315: The type '(long, long)' cannot be used as type parameter 'T' in the generic type or method 'Nullable<T>'. There is no boxing conversion from '(long, long)' to 'IInterface'. // void M((int, int)? t1, (long, long)? t2) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "t2").WithArguments("System.Nullable<T>", "IInterface", "T", "(long, long)").WithLocation(4, 42) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); // check t1 var equals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Last(); var t1 = equals.Left; Assert.Equal("t1", t1.ToString()); var t1Type = model.GetTypeInfo(t1); Assert.Equal("(System.Int32, System.Int32)?", t1Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, System.Int64)?", t1Type.ConvertedType.ToTestDisplayString()); } [Fact] public void TestEvaluationOrderOnTupleType2() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { System.Console.Write(""ValueTuple2, ""); this.Item1 = item1; this.Item2 = item2; } } public struct ValueTuple<T1, T2, T3> { public ValueTuple(T1 item1, T2 item2, T3 item3) { // ValueTuple'3 required (constructed in bound tree), but not emitted throw null; } } } public class Base { public int I; public Base(int i) { I = i; } } public class A : Base { public A(int i) : base(i) { System.Console.Write($""A:{i}, ""); } public static bool operator ==(A a, Y y) { System.Console.Write($""A({a.I}) == Y({y.I}), ""); return true; } public static bool operator !=(A a, Y y) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) { System.Console.Write($""X:{i}, ""); } } public class Y : Base { public Y(int i) : base(i) { System.Console.Write($""Y:{i}, ""); } public static implicit operator Y(X x) { System.Console.Write($""X:{x.I} -> ""); return new Y(x.I); } } public class C { public static void Main() { System.Console.Write($""{(new A(1), (new A(2), new A(3)), new A(4)) == (new X(5), GetTuple(), new Y(8))}""); } public static (X, Y) GetTuple() { System.Console.Write($""GetTuple, ""); return (new X(6), new Y(7)); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"A:1, A:2, A:3, A:4, X:5, GetTuple, X:6, Y:7, ValueTuple2, Y:8, X:5 -> Y:5, A(1) == Y(5), X:6 -> Y:6, A(2) == Y(6), A(3) == Y(7), A(4) == Y(8), True"); } [Fact] public void TestEvaluationOrderOnTupleType3() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { System.Console.Write(""ValueTuple2, ""); this.Item1 = item1; this.Item2 = item2; } } public struct ValueTuple<T1, T2, T3> { public ValueTuple(T1 item1, T2 item2, T3 item3) { // ValueTuple'3 required (constructed in bound tree), but not emitted throw null; } } } public class Base { public int I; public Base(int i) { I = i; } } public class A : Base { public A(int i) : base(i) { System.Console.Write($""A:{i}, ""); } public static bool operator ==(A a, Y y) { System.Console.Write($""A({a.I}) == Y({y.I}), ""); return true; } public static bool operator !=(A a, Y y) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) { System.Console.Write($""X:{i}, ""); } } public class Y : Base { public Y(int i) : base(i) { System.Console.Write($""Y:{i}, ""); } public static implicit operator Y(X x) { System.Console.Write(""X -> ""); return new Y(x.I); } } public class C { public static void Main() { System.Console.Write($""{GetTuple() == (new X(6), new Y(7))}""); } public static (A, A) GetTuple() { System.Console.Write($""GetTuple, ""); return (new A(30), new A(40)); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "GetTuple, A:30, A:40, ValueTuple2, X:6, Y:7, X -> Y:6, A(30) == Y(6), A(40) == Y(7), True"); } [Fact] public void TestObsoleteEqualityOperator() { var source = @" class C { void M() { System.Console.WriteLine($""{(new A(), new A()) == (new X(), new Y())}""); System.Console.WriteLine($""{(new A(), new A()) != (new X(), new Y())}""); } } public class A { [System.Obsolete(""obsolete"", true)] public static bool operator ==(A a, Y y) => throw null; [System.Obsolete(""obsolete too"", true)] public static bool operator !=(A a, Y y) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X { } public class Y { public static implicit operator Y(X x) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,37): error CS0619: 'A.operator ==(A, Y)' is obsolete: 'obsolete' // System.Console.WriteLine($"{(new A(), new A()) == (new X(), new Y())}"); Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "(new A(), new A()) == (new X(), new Y())").WithArguments("A.operator ==(A, Y)", "obsolete").WithLocation(6, 37), // (6,37): error CS0619: 'A.operator ==(A, Y)' is obsolete: 'obsolete' // System.Console.WriteLine($"{(new A(), new A()) == (new X(), new Y())}"); Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "(new A(), new A()) == (new X(), new Y())").WithArguments("A.operator ==(A, Y)", "obsolete").WithLocation(6, 37), // (7,37): error CS0619: 'A.operator !=(A, Y)' is obsolete: 'obsolete too' // System.Console.WriteLine($"{(new A(), new A()) != (new X(), new Y())}"); Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "(new A(), new A()) != (new X(), new Y())").WithArguments("A.operator !=(A, Y)", "obsolete too").WithLocation(7, 37), // (7,37): error CS0619: 'A.operator !=(A, Y)' is obsolete: 'obsolete too' // System.Console.WriteLine($"{(new A(), new A()) != (new X(), new Y())}"); Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "(new A(), new A()) != (new X(), new Y())").WithArguments("A.operator !=(A, Y)", "obsolete too").WithLocation(7, 37) ); } [Fact] public void TestDefiniteAssignment() { var source = @" class C { void M() { int error1; System.Console.Write((1, 2) == (error1, 2)); int error2; System.Console.Write((1, (error2, 3)) == (1, (2, 3))); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,41): error CS0165: Use of unassigned local variable 'error1' // System.Console.Write((1, 2) == (error1, 2)); Diagnostic(ErrorCode.ERR_UseDefViolation, "error1").WithArguments("error1").WithLocation(7, 41), // (10,35): error CS0165: Use of unassigned local variable 'error2' // System.Console.Write((1, (error2, 3)) == (1, (2, 3))); Diagnostic(ErrorCode.ERR_UseDefViolation, "error2").WithArguments("error2").WithLocation(10, 35) ); } [Fact] public void TestDefiniteAssignment2() { var source = @" class C { int M(out int x) { _ = (M(out int y), y) == (1, 2); // ok _ = (z, M(out int z)) == (1, 2); // error x = 1; return 2; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,14): error CS0841: Cannot use local variable 'z' before it is declared // _ = (z, M(out int z)) == (1, 2); // error Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "z").WithArguments("z").WithLocation(7, 14) ); } [Fact] public void TestEqualityOfTypeConvertingToTuple() { var source = @" class C { private int i; void M() { System.Console.Write(this == (1, 1)); System.Console.Write((1, 1) == this); } public static implicit operator (int, int)(C c) { return (c.i, c.i); } C(int i) { this.i = i; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,30): error CS0019: Operator '==' cannot be applied to operands of type 'C' and '(int, int)' // System.Console.Write(this == (1, 1)); Diagnostic(ErrorCode.ERR_BadBinaryOps, "this == (1, 1)").WithArguments("==", "C", "(int, int)").WithLocation(7, 30), // (8,30): error CS0019: Operator '==' cannot be applied to operands of type '(int, int)' and 'C' // System.Console.Write((1, 1) == this); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(1, 1) == this").WithArguments("==", "(int, int)", "C").WithLocation(8, 30) ); } [Fact] public void TestEqualityOfTypeConvertingFromTuple() { var source = @" class C { private int i; public static void Main() { var c = new C(2); System.Console.Write(c == (1, 1)); System.Console.Write((1, 1) == c); } public static implicit operator C((int, int) x) { return new C(x.Item1 + x.Item2); } public static bool operator ==(C c1, C c2) => c1.i == c2.i; public static bool operator !=(C c1, C c2) => throw null; public override int GetHashCode() => throw null; public override bool Equals(object other) => throw null; C(int i) { this.i = i; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueTrue"); } [Fact] public void TestEqualityOfTypeComparableWithTuple() { var source = @" class C { private static void Main() { System.Console.Write(new C() == (1, 1)); System.Console.Write(new C() != (1, 1)); } public static bool operator ==(C c, (int, int) t) { return t.Item1 + t.Item2 == 2; } public static bool operator !=(C c, (int, int) t) { return t.Item1 + t.Item2 != 2; } public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueFalse"); } [Fact] public void TestOfTwoUnrelatedTypes() { var source = @" class A { } class C { static void M() { System.Console.Write(new C() == new A()); System.Console.Write((1, new C()) == (1, new A())); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,30): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'A' // System.Console.Write(new C() == new A()); Diagnostic(ErrorCode.ERR_BadBinaryOps, "new C() == new A()").WithArguments("==", "C", "A").WithLocation(7, 30), // (8,30): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'A' // System.Console.Write((1, new C()) == (1, new A())); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(1, new C()) == (1, new A())").WithArguments("==", "C", "A").WithLocation(8, 30) ); } [Fact] public void TestOfTwoUnrelatedTypes2() { var source = @" class A { } class C { static void M(string s, System.Exception e) { System.Console.Write(s == 3); System.Console.Write((1, s) == (1, e)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,30): error CS0019: Operator '==' cannot be applied to operands of type 'string' and 'int' // System.Console.Write(s == 3); Diagnostic(ErrorCode.ERR_BadBinaryOps, "s == 3").WithArguments("==", "string", "int").WithLocation(7, 30), // (8,30): error CS0019: Operator '==' cannot be applied to operands of type 'string' and 'Exception' // System.Console.Write((1, s) == (1, e)); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(1, s) == (1, e)").WithArguments("==", "string", "System.Exception").WithLocation(8, 30) ); } [Fact] public void TestBadRefCompare() { var source = @" class C { static void M() { string s = ""11""; object o = s + s; (object, object) t = default; bool b = o == s; bool b2 = t == (s, s); // no warning } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,18): warning CS0252: Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string' // bool b = o == s; Diagnostic(ErrorCode.WRN_BadRefCompareLeft, "o == s").WithArguments("string").WithLocation(10, 18) ); } [Fact, WorkItem(27047, "https://github.com/dotnet/roslyn/issues/27047")] public void TestWithObsoleteImplicitConversion() { var source = @" class C { private static bool TupleEquals((C, int)? nt1, (int, C) nt2) => nt1 == nt2; // warn 1 and 2 private static bool TupleNotEquals((C, int)? nt1, (int, C) nt2) => nt1 != nt2; // warn 3 and 4 [System.Obsolete(""obsolete"", error: true)] public static implicit operator int(C c) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,12): error CS0619: 'C.implicit operator int(C)' is obsolete: 'obsolete' // => nt1 == nt2; // warn 1 and 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "nt1").WithArguments("C.implicit operator int(C)", "obsolete").WithLocation(5, 12), // (5,19): error CS0619: 'C.implicit operator int(C)' is obsolete: 'obsolete' // => nt1 == nt2; // warn 1 and 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "nt2").WithArguments("C.implicit operator int(C)", "obsolete").WithLocation(5, 19), // (8,12): error CS0619: 'C.implicit operator int(C)' is obsolete: 'obsolete' // => nt1 != nt2; // warn 3 and 4 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "nt1").WithArguments("C.implicit operator int(C)", "obsolete").WithLocation(8, 12), // (8,19): error CS0619: 'C.implicit operator int(C)' is obsolete: 'obsolete' // => nt1 != nt2; // warn 3 and 4 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "nt2").WithArguments("C.implicit operator int(C)", "obsolete").WithLocation(8, 19) ); } [Fact, WorkItem(27047, "https://github.com/dotnet/roslyn/issues/27047")] public void TestWithObsoleteBoolConversion() { var source = @" public class A { public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 public static NotBool operator ==(A a1, A a2) => throw null; public static NotBool operator !=(A a1, A a2) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class NotBool { [System.Obsolete(""obsolete"", error: true)] public static implicit operator bool(NotBool b) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,49): error CS0619: 'NotBool.implicit operator bool(NotBool)' is obsolete: 'obsolete' // public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t == t").WithArguments("NotBool.implicit operator bool(NotBool)", "obsolete").WithLocation(4, 49), // (4,49): error CS0619: 'NotBool.implicit operator bool(NotBool)' is obsolete: 'obsolete' // public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t == t").WithArguments("NotBool.implicit operator bool(NotBool)", "obsolete").WithLocation(4, 49), // (5,52): error CS0619: 'NotBool.implicit operator bool(NotBool)' is obsolete: 'obsolete' // public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t != t").WithArguments("NotBool.implicit operator bool(NotBool)", "obsolete").WithLocation(5, 52), // (5,52): error CS0619: 'NotBool.implicit operator bool(NotBool)' is obsolete: 'obsolete' // public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t != t").WithArguments("NotBool.implicit operator bool(NotBool)", "obsolete").WithLocation(5, 52) ); } [Fact, WorkItem(27047, "https://github.com/dotnet/roslyn/issues/27047")] public void TestWithObsoleteComparisonOperators() { var source = @" public class A { public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 [System.Obsolete("""", error: true)] public static bool operator ==(A a1, A a2) => throw null; [System.Obsolete("""", error: true)] public static bool operator !=(A a1, A a2) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,49): error CS0619: 'A.operator ==(A, A)' is obsolete: '' // public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t == t").WithArguments("A.operator ==(A, A)", "").WithLocation(4, 49), // (4,49): error CS0619: 'A.operator ==(A, A)' is obsolete: '' // public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t == t").WithArguments("A.operator ==(A, A)", "").WithLocation(4, 49), // (5,52): error CS0619: 'A.operator !=(A, A)' is obsolete: '' // public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t != t").WithArguments("A.operator !=(A, A)", "").WithLocation(5, 52), // (5,52): error CS0619: 'A.operator !=(A, A)' is obsolete: '' // public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t != t").WithArguments("A.operator !=(A, A)", "").WithLocation(5, 52) ); } [Fact, WorkItem(27047, "https://github.com/dotnet/roslyn/issues/27047")] public void TestWithObsoleteTruthOperators() { var source = @" public class A { public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 public static NotBool operator ==(A a1, A a2) => throw null; public static NotBool operator !=(A a1, A a2) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class NotBool { [System.Obsolete(""obsolete"", error: true)] public static bool operator true(NotBool b) => throw null; [System.Obsolete(""obsolete"", error: true)] public static bool operator false(NotBool b) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,49): error CS0619: 'NotBool.operator false(NotBool)' is obsolete: 'obsolete' // public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t == t").WithArguments("NotBool.operator false(NotBool)", "obsolete").WithLocation(4, 49), // (4,49): error CS0619: 'NotBool.operator false(NotBool)' is obsolete: 'obsolete' // public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t == t").WithArguments("NotBool.operator false(NotBool)", "obsolete").WithLocation(4, 49), // (5,52): error CS0619: 'NotBool.operator true(NotBool)' is obsolete: 'obsolete' // public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t != t").WithArguments("NotBool.operator true(NotBool)", "obsolete").WithLocation(5, 52), // (5,52): error CS0619: 'NotBool.operator true(NotBool)' is obsolete: 'obsolete' // public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t != t").WithArguments("NotBool.operator true(NotBool)", "obsolete").WithLocation(5, 52) ); } [Fact] public void TestEqualOnNullableVsNullableTuples() { var source = @" class C { public static void Main() { Compare(null, null); Compare(null, (1, 2)); Compare((2, 3), null); Compare((4, 4), (4, 4)); Compare((5, 5), (10, 10)); } private static void Compare((int, int)? nt1, (int, int)? nt2) { System.Console.Write($""{nt1 == nt2} ""); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "True False False True False"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var comparison = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); var nt1 = comparison.Left; var nt1Type = model.GetTypeInfo(nt1); Assert.Equal("nt1", nt1.ToString()); Assert.Equal("(System.Int32, System.Int32)?", nt1Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", nt1Type.ConvertedType.ToTestDisplayString()); var nt2 = comparison.Right; var nt2Type = model.GetTypeInfo(nt2); Assert.Equal("nt2", nt2.ToString()); Assert.Equal("(System.Int32, System.Int32)?", nt2Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", nt2Type.ConvertedType.ToTestDisplayString()); verifier.VerifyIL("C.Compare", @"{ // Code size 104 (0x68) .maxstack 3 .locals init (System.ValueTuple<int, int>? V_0, System.ValueTuple<int, int>? V_1, bool V_2, System.ValueTuple<int, int> V_3, System.ValueTuple<int, int> V_4) IL_0000: nop IL_0001: ldstr ""{0} "" IL_0006: ldarg.0 IL_0007: stloc.0 IL_0008: ldarg.1 IL_0009: stloc.1 IL_000a: ldloca.s V_0 IL_000c: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldloca.s V_1 IL_0015: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_001a: beq.s IL_001f IL_001c: ldc.i4.0 IL_001d: br.s IL_0057 IL_001f: ldloc.2 IL_0020: brtrue.s IL_0025 IL_0022: ldc.i4.1 IL_0023: br.s IL_0057 IL_0025: ldloca.s V_0 IL_0027: call ""System.ValueTuple<int, int> System.ValueTuple<int, int>?.GetValueOrDefault()"" IL_002c: stloc.3 IL_002d: ldloca.s V_1 IL_002f: call ""System.ValueTuple<int, int> System.ValueTuple<int, int>?.GetValueOrDefault()"" IL_0034: stloc.s V_4 IL_0036: ldloc.3 IL_0037: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_003c: ldloc.s V_4 IL_003e: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0043: bne.un.s IL_0056 IL_0045: ldloc.3 IL_0046: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_004b: ldloc.s V_4 IL_004d: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0052: ceq IL_0054: br.s IL_0057 IL_0056: ldc.i4.0 IL_0057: box ""bool"" IL_005c: call ""string string.Format(string, object)"" IL_0061: call ""void System.Console.Write(string)"" IL_0066: nop IL_0067: ret }"); } [Fact] public void TestEqualOnNullableVsNullableTuples_NeverNull() { var source = @" class C { public static void Main() { System.Console.Write(((int, int)?) (1, 2) == ((int, int)?) (1, 2)); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "True"); verifier.VerifyIL("C.Main", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.1 IL_0003: bne.un.s IL_000b IL_0005: ldc.i4.2 IL_0006: ldc.i4.2 IL_0007: ceq IL_0009: br.s IL_000c IL_000b: ldc.i4.0 IL_000c: call ""void System.Console.Write(bool)"" IL_0011: nop IL_0012: ret } "); } [Fact] public void TestEqualOnNullableVsNullableTuples_OneSideNeverNull() { var source = @" class C { public static void Main() { System.Console.Write(((int, int)?) (1, 2) == (1, 2)); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "True"); verifier.VerifyIL("C.Main", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.1 IL_0003: bne.un.s IL_000b IL_0005: ldc.i4.2 IL_0006: ldc.i4.2 IL_0007: ceq IL_0009: br.s IL_000c IL_000b: ldc.i4.0 IL_000c: call ""void System.Console.Write(bool)"" IL_0011: nop IL_0012: ret } "); } [Fact] public void TestEqualOnNullableVsNullableTuples_Tuple_AlwaysNull_AlwaysNull() { var source = @" class C { public static void Main() { System.Console.Write(((int, int)?)null == ((int, int)?)null); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "True"); verifier.VerifyIL("C.Main", @"{ // Code size 9 (0x9) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: call ""void System.Console.Write(bool)"" IL_0007: nop IL_0008: ret } "); CompileAndVerify(source, options: TestOptions.ReleaseExe).VerifyIL("C.Main", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: call ""void System.Console.Write(bool)"" IL_0006: ret } "); } [Fact] public void TestEqualOnNullableVsNullableTuples_Tuple_MaybeNull_AlwaysNull() { var source = @" class C { public static void Main() { M(null); M((1, 2)); } public static void M((int, int)? t) { System.Console.Write(t == ((int, int)?)null); } } "; CompileAndVerify(source, expectedOutput: "TrueFalse", options: TestOptions.ReleaseExe).VerifyIL("C.M", @"{ // Code size 18 (0x12) .maxstack 2 .locals init (System.ValueTuple<int, int>? V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_0009: ldc.i4.0 IL_000a: ceq IL_000c: call ""void System.Console.Write(bool)"" IL_0011: ret } "); } [Fact] public void TestNotEqualOnNullableVsNullableTuples_Tuple_MaybeNull_AlwaysNull() { var source = @" class C { public static void Main() { M(null); M((1, 2)); } public static void M((int, int)? t) { System.Console.Write(t != ((int, int)?)null); } } "; CompileAndVerify(source, expectedOutput: "FalseTrue", options: TestOptions.ReleaseExe).VerifyIL("C.M", @"{ // Code size 15 (0xf) .maxstack 1 .locals init (System.ValueTuple<int, int>? V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_0009: call ""void System.Console.Write(bool)"" IL_000e: ret } "); } [Fact] public void TestNotEqualOnNullableVsNullableTuples_Tuple_AlwaysNull_MaybeNull() { var source = @" class C { public static void Main() { M(null); M((1, 2)); } public static void M((int, int)? t) { System.Console.Write(((int, int)?)null == t); } } "; CompileAndVerify(source, expectedOutput: "TrueFalse", options: TestOptions.ReleaseExe).VerifyIL("C.M", @"{ // Code size 18 (0x12) .maxstack 2 .locals init (System.ValueTuple<int, int>? V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_0009: ldc.i4.0 IL_000a: ceq IL_000c: call ""void System.Console.Write(bool)"" IL_0011: ret } "); } [Fact] public void TestEqualOnNullableVsNullableTuples_Tuple_NeverNull_AlwaysNull() { var source = @" class C { public static void Main() { System.Console.Write((1, 2) == ((int, int)?)null); } } "; CompileAndVerify(source, expectedOutput: "False", options: TestOptions.ReleaseExe).VerifyIL("C.Main", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: call ""void System.Console.Write(bool)"" IL_0006: ret } "); } [Fact] public void TestEqualOnNullableVsNullableTuples_Tuple_AlwaysNull_MaybeNull() { var source = @" class C { public static void Main() { M(null); M((1, 2)); } public static void M((int, int)? t) { System.Console.Write(((int, int)?)null == t); } } "; CompileAndVerify(source, expectedOutput: "TrueFalse", options: TestOptions.ReleaseExe).VerifyIL("C.M", @"{ // Code size 18 (0x12) .maxstack 2 .locals init (System.ValueTuple<int, int>? V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_0009: ldc.i4.0 IL_000a: ceq IL_000c: call ""void System.Console.Write(bool)"" IL_0011: ret } "); } [Fact] public void TestEqualOnNullableVsNullableTuples_Tuple_AlwaysNull_NeverNull() { var source = @" class C { public static void Main() { System.Console.Write(((int, int)?)null == (1, 2)); } } "; CompileAndVerify(source, expectedOutput: "False", options: TestOptions.ReleaseExe).VerifyIL("C.Main", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: call ""void System.Console.Write(bool)"" IL_0006: ret } "); } [Fact] public void TestEqualOnNullableVsNullableTuples_ElementAlwaysNull() { var source = @" class C { public static void Main() { System.Console.Write((null, null) == (new int?(), new int?())); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "True"); verifier.VerifyIL("C.Main", @"{ // Code size 9 (0x9) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: call ""void System.Console.Write(bool)"" IL_0007: nop IL_0008: ret } "); } [Fact] public void TestNotEqualOnNullableVsNullableTuples() { var source = @" class C { public static void Main() { Compare(null, null); Compare(null, (1, 2)); Compare((2, 3), null); Compare((4, 4), (4, 4)); Compare((5, 5), (10, 10)); } private static void Compare((int, int)? nt1, (int, int)? nt2) { System.Console.Write($""{nt1 != nt2} ""); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "False True True False True"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var comparison = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); var nt1 = comparison.Left; var nt1Type = model.GetTypeInfo(nt1); Assert.Equal("nt1", nt1.ToString()); Assert.Equal("(System.Int32, System.Int32)?", nt1Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", nt1Type.ConvertedType.ToTestDisplayString()); var nt2 = comparison.Right; var nt2Type = model.GetTypeInfo(nt2); Assert.Equal("nt2", nt2.ToString()); Assert.Equal("(System.Int32, System.Int32)?", nt2Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", nt2Type.ConvertedType.ToTestDisplayString()); verifier.VerifyIL("C.Compare", @"{ // Code size 107 (0x6b) .maxstack 3 .locals init (System.ValueTuple<int, int>? V_0, System.ValueTuple<int, int>? V_1, bool V_2, System.ValueTuple<int, int> V_3, System.ValueTuple<int, int> V_4) IL_0000: nop IL_0001: ldstr ""{0} "" IL_0006: ldarg.0 IL_0007: stloc.0 IL_0008: ldarg.1 IL_0009: stloc.1 IL_000a: ldloca.s V_0 IL_000c: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldloca.s V_1 IL_0015: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_001a: beq.s IL_001f IL_001c: ldc.i4.1 IL_001d: br.s IL_005a IL_001f: ldloc.2 IL_0020: brtrue.s IL_0025 IL_0022: ldc.i4.0 IL_0023: br.s IL_005a IL_0025: ldloca.s V_0 IL_0027: call ""System.ValueTuple<int, int> System.ValueTuple<int, int>?.GetValueOrDefault()"" IL_002c: stloc.3 IL_002d: ldloca.s V_1 IL_002f: call ""System.ValueTuple<int, int> System.ValueTuple<int, int>?.GetValueOrDefault()"" IL_0034: stloc.s V_4 IL_0036: ldloc.3 IL_0037: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_003c: ldloc.s V_4 IL_003e: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0043: bne.un.s IL_0059 IL_0045: ldloc.3 IL_0046: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_004b: ldloc.s V_4 IL_004d: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0052: ceq IL_0054: ldc.i4.0 IL_0055: ceq IL_0057: br.s IL_005a IL_0059: ldc.i4.1 IL_005a: box ""bool"" IL_005f: call ""string string.Format(string, object)"" IL_0064: call ""void System.Console.Write(string)"" IL_0069: nop IL_006a: ret }"); } [Fact] public void TestNotEqualOnNullableVsNullableNestedTuples() { var source = @" class C { public static void Main() { Compare((1, null), (1, null), true); Compare(null, (1, (2, 3)), false); Compare((1, (2, 3)), (1, null), false); Compare((1, (4, 4)), (1, (4, 4)), true); Compare((1, (5, 5)), (1, (10, 10)), false); System.Console.Write(""Success""); } private static void Compare((int, (int, int)?)? nt1, (int, (int, int)?)? nt2, bool expectMatch) { if (expectMatch != (nt1 == nt2) || expectMatch == (nt1 != nt2)) { throw null; } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Success"); } [Fact] public void TestEqualOnNullableVsNullableTuples_WithImplicitConversion() { var source = @" class C { public static void Main() { Compare(null, null); Compare(null, (1, 2)); Compare((2, 3), null); Compare((4, 4), (4, 4)); Compare((5, 5), (10, 10)); } private static void Compare((int, int)? nt1, (byte, long)? nt2) { System.Console.Write($""{nt1 == nt2} ""); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "True False False True False"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var comparison = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); var nt1 = comparison.Left; var nt1Type = model.GetTypeInfo(nt1); Assert.Equal("nt1", nt1.ToString()); Assert.Equal("(System.Int32, System.Int32)?", nt1Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int64)?", nt1Type.ConvertedType.ToTestDisplayString()); var nt2 = comparison.Right; var nt2Type = model.GetTypeInfo(nt2); Assert.Equal("nt2", nt2.ToString()); Assert.Equal("(System.Byte, System.Int64)?", nt2Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int64)?", nt2Type.ConvertedType.ToTestDisplayString()); verifier.VerifyIL("C.Compare", @"{ // Code size 105 (0x69) .maxstack 3 .locals init (System.ValueTuple<int, int>? V_0, System.ValueTuple<byte, long>? V_1, bool V_2, System.ValueTuple<int, int> V_3, System.ValueTuple<byte, long> V_4) IL_0000: nop IL_0001: ldstr ""{0} "" IL_0006: ldarg.0 IL_0007: stloc.0 IL_0008: ldarg.1 IL_0009: stloc.1 IL_000a: ldloca.s V_0 IL_000c: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldloca.s V_1 IL_0015: call ""bool System.ValueTuple<byte, long>?.HasValue.get"" IL_001a: beq.s IL_001f IL_001c: ldc.i4.0 IL_001d: br.s IL_0058 IL_001f: ldloc.2 IL_0020: brtrue.s IL_0025 IL_0022: ldc.i4.1 IL_0023: br.s IL_0058 IL_0025: ldloca.s V_0 IL_0027: call ""System.ValueTuple<int, int> System.ValueTuple<int, int>?.GetValueOrDefault()"" IL_002c: stloc.3 IL_002d: ldloca.s V_1 IL_002f: call ""System.ValueTuple<byte, long> System.ValueTuple<byte, long>?.GetValueOrDefault()"" IL_0034: stloc.s V_4 IL_0036: ldloc.3 IL_0037: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_003c: ldloc.s V_4 IL_003e: ldfld ""byte System.ValueTuple<byte, long>.Item1"" IL_0043: bne.un.s IL_0057 IL_0045: ldloc.3 IL_0046: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_004b: conv.i8 IL_004c: ldloc.s V_4 IL_004e: ldfld ""long System.ValueTuple<byte, long>.Item2"" IL_0053: ceq IL_0055: br.s IL_0058 IL_0057: ldc.i4.0 IL_0058: box ""bool"" IL_005d: call ""string string.Format(string, object)"" IL_0062: call ""void System.Console.Write(string)"" IL_0067: nop IL_0068: ret }"); } [Fact] public void TestOnNullableVsNullableTuples_WithImplicitCustomConversion() { var source = @" class C { int _value; public C(int v) { _value = v; } public static void Main() { Compare(null, null); Compare(null, (1, new C(20))); Compare((new C(30), 3), null); Compare((new C(4), 4), (4, new C(4))); Compare((new C(5), 5), (10, new C(10))); Compare((new C(6), 6), (6, new C(20))); } private static void Compare((C, int)? nt1, (int, C)? nt2) { System.Console.Write($""{nt1 == nt2} ""); } public static implicit operator int(C c) { System.Console.Write($""Convert{c._value} ""); return c._value; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "True False False Convert4 Convert4 True Convert5 False Convert6 Convert20 False "); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var comparison = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); var nt1 = comparison.Left; var nt1Type = model.GetTypeInfo(nt1); Assert.Equal("nt1", nt1.ToString()); Assert.Equal("(C, System.Int32)?", nt1Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", nt1Type.ConvertedType.ToTestDisplayString()); var nt2 = comparison.Right; var nt2Type = model.GetTypeInfo(nt2); Assert.Equal("nt2", nt2.ToString()); Assert.Equal("(System.Int32, C)?", nt2Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", nt2Type.ConvertedType.ToTestDisplayString()); verifier.VerifyIL("C.Compare", @"{ // Code size 114 (0x72) .maxstack 3 .locals init (System.ValueTuple<C, int>? V_0, System.ValueTuple<int, C>? V_1, bool V_2, System.ValueTuple<C, int> V_3, System.ValueTuple<int, C> V_4) IL_0000: nop IL_0001: ldstr ""{0} "" IL_0006: ldarg.0 IL_0007: stloc.0 IL_0008: ldarg.1 IL_0009: stloc.1 IL_000a: ldloca.s V_0 IL_000c: call ""bool System.ValueTuple<C, int>?.HasValue.get"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldloca.s V_1 IL_0015: call ""bool System.ValueTuple<int, C>?.HasValue.get"" IL_001a: beq.s IL_001f IL_001c: ldc.i4.0 IL_001d: br.s IL_0061 IL_001f: ldloc.2 IL_0020: brtrue.s IL_0025 IL_0022: ldc.i4.1 IL_0023: br.s IL_0061 IL_0025: ldloca.s V_0 IL_0027: call ""System.ValueTuple<C, int> System.ValueTuple<C, int>?.GetValueOrDefault()"" IL_002c: stloc.3 IL_002d: ldloca.s V_1 IL_002f: call ""System.ValueTuple<int, C> System.ValueTuple<int, C>?.GetValueOrDefault()"" IL_0034: stloc.s V_4 IL_0036: ldloc.3 IL_0037: ldfld ""C System.ValueTuple<C, int>.Item1"" IL_003c: call ""int C.op_Implicit(C)"" IL_0041: ldloc.s V_4 IL_0043: ldfld ""int System.ValueTuple<int, C>.Item1"" IL_0048: bne.un.s IL_0060 IL_004a: ldloc.3 IL_004b: ldfld ""int System.ValueTuple<C, int>.Item2"" IL_0050: ldloc.s V_4 IL_0052: ldfld ""C System.ValueTuple<int, C>.Item2"" IL_0057: call ""int C.op_Implicit(C)"" IL_005c: ceq IL_005e: br.s IL_0061 IL_0060: ldc.i4.0 IL_0061: box ""bool"" IL_0066: call ""string string.Format(string, object)"" IL_006b: call ""void System.Console.Write(string)"" IL_0070: nop IL_0071: ret }"); } [Fact] public void TestOnNullableVsNonNullableTuples() { var source = @" class C { public static void Main() { M(null); M((1, 2)); M((10, 20)); } private static void M((byte, int)? nt) { System.Console.Write((1, 2) == nt); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "FalseTrueFalse"); verifier.VerifyIL("C.M", @"{ // Code size 53 (0x35) .maxstack 2 .locals init (System.ValueTuple<byte, int>? V_0, System.ValueTuple<byte, int> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""bool System.ValueTuple<byte, int>?.HasValue.get"" IL_000a: brtrue.s IL_000f IL_000c: ldc.i4.0 IL_000d: br.s IL_002e IL_000f: br.s IL_0011 IL_0011: ldloca.s V_0 IL_0013: call ""System.ValueTuple<byte, int> System.ValueTuple<byte, int>?.GetValueOrDefault()"" IL_0018: stloc.1 IL_0019: ldc.i4.1 IL_001a: ldloc.1 IL_001b: ldfld ""byte System.ValueTuple<byte, int>.Item1"" IL_0020: bne.un.s IL_002d IL_0022: ldc.i4.2 IL_0023: ldloc.1 IL_0024: ldfld ""int System.ValueTuple<byte, int>.Item2"" IL_0029: ceq IL_002b: br.s IL_002e IL_002d: ldc.i4.0 IL_002e: call ""void System.Console.Write(bool)"" IL_0033: nop IL_0034: ret }"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var comparison = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); var tuple = comparison.Left; var tupleType = model.GetTypeInfo(tuple); Assert.Equal("(1, 2)", tuple.ToString()); Assert.Equal("(System.Int32, System.Int32)", tupleType.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", tupleType.ConvertedType.ToTestDisplayString()); var nt = comparison.Right; var ntType = model.GetTypeInfo(nt); Assert.Equal("nt", nt.ToString()); Assert.Equal("(System.Byte, System.Int32)?", ntType.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", ntType.ConvertedType.ToTestDisplayString()); } [Fact] public void TestOnNullableVsNonNullableTuples_WithCustomConversion() { var source = @" class C { int _value; public C(int v) { _value = v; } public static void Main() { M(null); M((new C(1), 2)); M((new C(10), 20)); } private static void M((C, int)? nt) { System.Console.Write($""{(1, 2) == nt} ""); System.Console.Write($""{nt == (1, 2)} ""); } public static implicit operator int(C c) { System.Console.Write($""Convert{c._value} ""); return c._value; } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "False False Convert1 True Convert1 True Convert10 False Convert10 False"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var comparison = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); Assert.Equal("(1, 2) == nt", comparison.ToString()); var tuple = comparison.Left; var tupleType = model.GetTypeInfo(tuple); Assert.Equal("(1, 2)", tuple.ToString()); Assert.Equal("(System.Int32, System.Int32)", tupleType.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", tupleType.ConvertedType.ToTestDisplayString()); var nt = comparison.Right; var ntType = model.GetTypeInfo(nt); Assert.Equal("nt", nt.ToString()); Assert.Equal("(C, System.Int32)?", ntType.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", ntType.ConvertedType.ToTestDisplayString()); } [Fact] public void TestOnNullableVsNonNullableTuples3() { var source = @" class C { public static void Main() { M(null); M((1, 2)); M((10, 20)); } private static void M((int, int)? nt) { System.Console.Write(nt == (1, 2)); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "FalseTrueFalse"); verifier.VerifyIL("C.M", @"{ // Code size 59 (0x3b) .maxstack 2 .locals init (System.ValueTuple<int, int>? V_0, bool V_1, System.ValueTuple<int, int> V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_000a: stloc.1 IL_000b: ldloc.1 IL_000c: brtrue.s IL_0011 IL_000e: ldc.i4.0 IL_000f: br.s IL_0034 IL_0011: ldloc.1 IL_0012: brtrue.s IL_0017 IL_0014: ldc.i4.1 IL_0015: br.s IL_0034 IL_0017: ldloca.s V_0 IL_0019: call ""System.ValueTuple<int, int> System.ValueTuple<int, int>?.GetValueOrDefault()"" IL_001e: stloc.2 IL_001f: ldloc.2 IL_0020: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0025: ldc.i4.1 IL_0026: bne.un.s IL_0033 IL_0028: ldloc.2 IL_0029: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_002e: ldc.i4.2 IL_002f: ceq IL_0031: br.s IL_0034 IL_0033: ldc.i4.0 IL_0034: call ""void System.Console.Write(bool)"" IL_0039: nop IL_003a: ret }"); } [Fact] public void TestOnNullableVsLiteralTuples() { var source = @" class C { public static void Main() { CheckNull(null); CheckNull((1, 2)); } private static void CheckNull((int, int)? nt) { System.Console.Write($""{nt == null} ""); System.Console.Write($""{nt != null} ""); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True False False True"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var lastNull = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Last(); Assert.Equal("null", lastNull.ToString()); var nullType = model.GetTypeInfo(lastNull); Assert.Null(nullType.Type); Assert.Null(nullType.ConvertedType); // In nullable-null comparison, the null literal remains typeless } [Fact] public void TestOnLongTuple() { var source = @" class C { public static void Main() { Assert(MakeLongTuple(1) == MakeLongTuple(1)); Assert(!(MakeLongTuple(1) != MakeLongTuple(1))); Assert(MakeLongTuple(1) == (1, 1, 1, 1, 1, 1, 1, 1, 1)); Assert(!(MakeLongTuple(1) != (1, 1, 1, 1, 1, 1, 1, 1, 1))); Assert(MakeLongTuple(1) == MakeLongTuple(1, 1)); Assert(!(MakeLongTuple(1) != MakeLongTuple(1, 1))); Assert(!(MakeLongTuple(1) == MakeLongTuple(1, 2))); Assert(!(MakeLongTuple(1) == MakeLongTuple(2, 1))); Assert(MakeLongTuple(1) != MakeLongTuple(1, 2)); Assert(MakeLongTuple(1) != MakeLongTuple(2, 1)); System.Console.Write(""Success""); } private static (int, int, int, int, int, int, int, int, int) MakeLongTuple(int x) => (x, x, x, x, x, x, x, x, x); private static (int?, int, int?, int, int?, int, int?, int, int?)? MakeLongTuple(int? x, int y) => (x, y, x, y, x, y, x, y, x); private static void Assert(bool test) { if (!test) { throw null; } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Success"); } [Fact] public void TestOn1Tuple_FromRest() { var source = @" class C { public static bool M() { var x1 = MakeLongTuple(1).Rest; bool b1 = x1 == x1; bool b2 = x1 != x1; return b1 && b2; } private static (int, int, int, int, int, int, int, int?) MakeLongTuple(int? x) => throw null; public bool Unused((int, int, int, int, int, int, int, int?) t) { return t.Rest == t.Rest; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,19): error CS0019: Operator '==' cannot be applied to operands of type 'ValueTuple<int?>' and 'ValueTuple<int?>' // bool b1 = x1 == x1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x1 == x1").WithArguments("==", "System.ValueTuple<int?>", "System.ValueTuple<int?>").WithLocation(8, 19), // (9,19): error CS0019: Operator '!=' cannot be applied to operands of type 'ValueTuple<int?>' and 'ValueTuple<int?>' // bool b2 = x1 != x1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x1 != x1").WithArguments("!=", "System.ValueTuple<int?>", "System.ValueTuple<int?>").WithLocation(9, 19), // (18,16): error CS0019: Operator '==' cannot be applied to operands of type 'ValueTuple<int?>' and 'ValueTuple<int?>' // return t.Rest == t.Rest; Diagnostic(ErrorCode.ERR_BadBinaryOps, "t.Rest == t.Rest").WithArguments("==", "System.ValueTuple<int?>", "System.ValueTuple<int?>").WithLocation(18, 16) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var comparison = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Last(); Assert.Equal("t.Rest == t.Rest", comparison.ToString()); var left = model.GetTypeInfo(comparison.Left); Assert.Equal("System.ValueTuple<System.Int32?>", left.Type.ToTestDisplayString()); Assert.Equal("System.ValueTuple<System.Int32?>", left.ConvertedType.ToTestDisplayString()); Assert.True(left.Type.IsTupleType); } [Fact] public void TestOn1Tuple_FromValueTuple() { var source = @" using System; class C { public static bool M() { var x1 = ValueTuple.Create((int?)1); bool b1 = x1 == x1; bool b2 = x1 != x1; return b1 && b2; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,19): error CS0019: Operator '==' cannot be applied to operands of type 'ValueTuple<int?>' and 'ValueTuple<int?>' // bool b1 = x1 == x1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x1 == x1").WithArguments("==", "System.ValueTuple<int?>", "System.ValueTuple<int?>").WithLocation(9, 19), // (10,19): error CS0019: Operator '!=' cannot be applied to operands of type 'ValueTuple<int?>' and 'ValueTuple<int?>' // bool b2 = x1 != x1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x1 != x1").WithArguments("!=", "System.ValueTuple<int?>", "System.ValueTuple<int?>").WithLocation(10, 19) ); } [Fact] public void TestOnTupleOfDecimals() { var source = @" class C { public static void Main() { System.Console.Write(Compare((1, 2), (1, 2))); System.Console.Write(Compare((1, 2), (10, 20))); } public static bool Compare((decimal, decimal) t1, (decimal, decimal) t2) { return t1 == t2; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "TrueFalse"); verifier.VerifyIL("C.Compare", @"{ // Code size 49 (0x31) .maxstack 2 .locals init (System.ValueTuple<decimal, decimal> V_0, System.ValueTuple<decimal, decimal> V_1, bool V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.1 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""decimal System.ValueTuple<decimal, decimal>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""decimal System.ValueTuple<decimal, decimal>.Item1"" IL_0011: call ""bool decimal.op_Equality(decimal, decimal)"" IL_0016: brfalse.s IL_002b IL_0018: ldloc.0 IL_0019: ldfld ""decimal System.ValueTuple<decimal, decimal>.Item2"" IL_001e: ldloc.1 IL_001f: ldfld ""decimal System.ValueTuple<decimal, decimal>.Item2"" IL_0024: call ""bool decimal.op_Equality(decimal, decimal)"" IL_0029: br.s IL_002c IL_002b: ldc.i4.0 IL_002c: stloc.2 IL_002d: br.s IL_002f IL_002f: ldloc.2 IL_0030: ret }"); } [Fact] public void TestSideEffectsAreSavedToTemps() { var source = @" class C { public static void Main() { int i = 0; System.Console.Write((i++, i++, i++) == (0, 1, 2)); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "True"); } [Fact] public void TestNonBoolComparisonResult_WithTrueFalseOperators() { var source = @" using static System.Console; public class C { public static void Main() { Write($""{REPLACE}""); } } public class Base { public int I; public Base(int i) { I = i; } } public class A : Base { public A(int i) : base(i) { Write($""A:{i}, ""); } public static NotBool operator ==(A a, Y y) { Write(""A == Y, ""); return new NotBool(a.I == y.I); } public static NotBool operator !=(A a, Y y) { Write(""A != Y, ""); return new NotBool(a.I != y.I); } public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) { Write($""X:{i}, ""); } } public class Y : Base { public Y(int i) : base(i) { Write($""Y:{i}, ""); } public static implicit operator Y(X x) { Write(""X -> ""); return new Y(x.I); } } public class NotBool { public bool B; public NotBool(bool value) { B = value; } public static bool operator true(NotBool b) { Write($""NotBool.true -> {b.B}, ""); return b.B; } public static bool operator false(NotBool b) { Write($""NotBool.false -> {!b.B}, ""); return !b.B; } } "; validate("(new A(1), new A(2)) == (new X(1), new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A == Y, NotBool.false -> False, A == Y, NotBool.false -> False, True"); validate("(new A(1), new A(2)) == (new X(1), new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A == Y, NotBool.false -> False, A == Y, NotBool.false -> True, False"); validate("(new A(1), new A(2)) != (new X(1), new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A != Y, NotBool.true -> False, A != Y, NotBool.true -> False, False"); validate("(new A(1), new A(2)) != (new X(1), new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A != Y, NotBool.true -> False, A != Y, NotBool.true -> True, True"); validate("((dynamic)new A(1), new A(2)) == (new X(1), (dynamic)new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A == Y, NotBool.false -> False, A == Y, NotBool.false -> False, True"); validate("((dynamic)new A(1), new A(2)) == (new X(1), (dynamic)new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A == Y, NotBool.false -> False, A == Y, NotBool.false -> True, False"); validate("((dynamic)new A(1), new A(2)) != (new X(1), (dynamic)new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A != Y, NotBool.true -> False, A != Y, NotBool.true -> False, False"); validate("((dynamic)new A(1), new A(2)) != (new X(1), (dynamic)new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A != Y, NotBool.true -> False, A != Y, NotBool.true -> True, True"); void validate(string expression, string expected) { var comp = CreateCompilation(source.Replace("REPLACE", expression), targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: expected); } } [Fact] public void TestNonBoolComparisonResult_WithTrueFalseOperatorsOnBase() { var source = @" using static System.Console; public class C { public static void Main() { Write($""{REPLACE}""); } } public class Base { public int I; public Base(int i) { I = i; } } public class A : Base { public A(int i) : base(i) { Write($""A:{i}, ""); } public static NotBool operator ==(A a, Y y) { Write(""A == Y, ""); return new NotBool(a.I == y.I); } public static NotBool operator !=(A a, Y y) { Write(""A != Y, ""); return new NotBool(a.I != y.I); } public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) { Write($""X:{i}, ""); } } public class Y : Base { public Y(int i) : base(i) { Write($""Y:{i}, ""); } public static implicit operator Y(X x) { Write(""X -> ""); return new Y(x.I); } } public class NotBoolBase { public bool B; public NotBoolBase(bool value) { B = value; } public static bool operator true(NotBoolBase b) { Write($""NotBoolBase.true -> {b.B}, ""); return b.B; } public static bool operator false(NotBoolBase b) { Write($""NotBoolBase.false -> {!b.B}, ""); return !b.B; } } public class NotBool : NotBoolBase { public NotBool(bool value) : base(value) { } } "; // This tests the case where the custom operators false/true need an input conversion that's not just an identity conversion (in this case, it's an implicit reference conversion) validate("(new A(1), new A(2)) == (new X(1), new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A == Y, NotBoolBase.false -> False, A == Y, NotBoolBase.false -> False, True"); validate("(new A(1), new A(2)) == (new X(1), new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A == Y, NotBoolBase.false -> False, A == Y, NotBoolBase.false -> True, False"); validate("(new A(1), new A(2)) != (new X(1), new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A != Y, NotBoolBase.true -> False, A != Y, NotBoolBase.true -> False, False"); validate("(new A(1), new A(2)) != (new X(1), new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A != Y, NotBoolBase.true -> False, A != Y, NotBoolBase.true -> True, True"); validate("((dynamic)new A(1), new A(2)) == (new X(1), (dynamic)new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A == Y, NotBoolBase.false -> False, A == Y, NotBoolBase.false -> False, True"); validate("((dynamic)new A(1), new A(2)) == (new X(1), (dynamic)new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A == Y, NotBoolBase.false -> False, A == Y, NotBoolBase.false -> True, False"); validate("((dynamic)new A(1), new A(2)) != (new X(1), (dynamic)new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A != Y, NotBoolBase.true -> False, A != Y, NotBoolBase.true -> False, False"); validate("((dynamic)new A(1), new A(2)) != (new X(1), (dynamic)new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A != Y, NotBoolBase.true -> False, A != Y, NotBoolBase.true -> True, True"); void validate(string expression, string expected) { var comp = CreateCompilation(source.Replace("REPLACE", expression), targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: expected); } } [Fact] public void TestNonBoolComparisonResult_WithImplicitBoolConversion() { var source = @" using static System.Console; public class C { public static void Main() { Write($""{REPLACE}""); } } public class Base { public int I; public Base(int i) { I = i; } } public class A : Base { public A(int i) : base(i) { Write($""A:{i}, ""); } public static NotBool operator ==(A a, Y y) { Write(""A == Y, ""); return new NotBool(a.I == y.I); } public static NotBool operator !=(A a, Y y) { Write(""A != Y, ""); return new NotBool(a.I != y.I); } public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) { Write($""X:{i}, ""); } } public class Y : Base { public Y(int i) : base(i) { Write($""Y:{i}, ""); } public static implicit operator Y(X x) { Write(""X -> ""); return new Y(x.I); } } public class NotBool { public bool B; public NotBool(bool value) { B = value; } public static implicit operator bool(NotBool b) { Write($""NotBool -> bool:{b.B}, ""); return b.B; } } "; validate("(new A(1), new A(2)) == (new X(1), new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A == Y, NotBool -> bool:True, A == Y, NotBool -> bool:True, True"); validate("(new A(1), new A(2)) == (new X(10), new Y(2))", "A:1, A:2, X:10, Y:2, X -> Y:10, A == Y, NotBool -> bool:False, False"); validate("(new A(1), new A(2)) == (new X(1), new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A == Y, NotBool -> bool:True, A == Y, NotBool -> bool:False, False"); validate("(new A(1), new A(2)) != (new X(1), new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A != Y, NotBool -> bool:False, A != Y, NotBool -> bool:False, False"); validate("(new A(1), new A(2)) != (new X(10), new Y(2))", "A:1, A:2, X:10, Y:2, X -> Y:10, A != Y, NotBool -> bool:True, True"); validate("(new A(1), new A(2)) != (new X(1), new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A != Y, NotBool -> bool:False, A != Y, NotBool -> bool:True, True"); void validate(string expression, string expected) { var comp = CreateCompilation(source.Replace("REPLACE", expression), options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: expected); } } [Fact] public void TestNonBoolComparisonResult_WithoutImplicitBoolConversion() { var source = @" using static System.Console; public class C { public static void Main() { Write($""{REPLACE}""); } } public class Base { public Base(int i) { } } public class A : Base { public A(int i) : base(i) => throw null; public static NotBool operator ==(A a, Y y) => throw null; public static NotBool operator !=(A a, Y y) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) => throw null; } public class Y : Base { public Y(int i) : base(i) => throw null; public static implicit operator Y(X x) => throw null; } public class NotBool { } "; validate("(new A(1), new A(2)) == (new X(1), new Y(2))", // (7,18): error CS0029: Cannot implicitly convert type 'NotBool' to 'bool' // Write($"{(new A(1), new A(2)) == (new X(1), new Y(2))}"); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(new A(1), new A(2)) == (new X(1), new Y(2))").WithArguments("NotBool", "bool").WithLocation(7, 18), // (7,18): error CS0029: Cannot implicitly convert type 'NotBool' to 'bool' // Write($"{(new A(1), new A(2)) == (new X(1), new Y(2))}"); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(new A(1), new A(2)) == (new X(1), new Y(2))").WithArguments("NotBool", "bool").WithLocation(7, 18) ); validate("(new A(1), 2) != (new X(1), 2)", // (7,18): error CS0029: Cannot implicitly convert type 'NotBool' to 'bool' // Write($"{(new A(1), 2) != (new X(1), 2)}"); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(new A(1), 2) != (new X(1), 2)").WithArguments("NotBool", "bool").WithLocation(7, 18) ); void validate(string expression, params DiagnosticDescription[] expected) { var comp = CreateCompilation(source.Replace("REPLACE", expression)); comp.VerifyDiagnostics(expected); } } [Fact] public void TestNonBoolComparisonResult_WithExplicitBoolConversion() { var source = @" using static System.Console; public class C { public static void Main() { Write($""{(new A(1), new A(2)) == (new X(1), new Y(2))}""); } } public class Base { public int I; public Base(int i) { I = i; } } public class A : Base { public A(int i) : base(i) => throw null; public static NotBool operator ==(A a, Y y) => throw null; public static NotBool operator !=(A a, Y y) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) => throw null; } public class Y : Base { public Y(int i) : base(i) => throw null; public static implicit operator Y(X x) => throw null; } public class NotBool { public NotBool(bool value) => throw null; public static explicit operator bool(NotBool b) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,18): error CS0029: Cannot implicitly convert type 'NotBool' to 'bool' // Write($"{(new A(1), new A(2)) == (new X(1), new Y(2))}"); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(new A(1), new A(2)) == (new X(1), new Y(2))").WithArguments("NotBool", "bool").WithLocation(7, 18), // (7,18): error CS0029: Cannot implicitly convert type 'NotBool' to 'bool' // Write($"{(new A(1), new A(2)) == (new X(1), new Y(2))}"); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(new A(1), new A(2)) == (new X(1), new Y(2))").WithArguments("NotBool", "bool").WithLocation(7, 18) ); } [Fact] public void TestNullableBoolComparisonResult_WithTrueFalseOperators() { var source = @" public class C { public static void M(A a) { _ = (a, a) == (a, a); if (a == a) { } } } public class A { public A(int i) => throw null; public static bool? operator ==(A a1, A a2) => throw null; public static bool? operator !=(A a1, A a2) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,13): error CS0029: Cannot implicitly convert type 'bool?' to 'bool' // _ = (a, a) == (a, a); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(a, a) == (a, a)").WithArguments("bool?", "bool").WithLocation(6, 13), // (6,13): error CS0029: Cannot implicitly convert type 'bool?' to 'bool' // _ = (a, a) == (a, a); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(a, a) == (a, a)").WithArguments("bool?", "bool").WithLocation(6, 13), // (7,13): error CS0266: Cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?) // if (a == a) { } Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "a == a").WithArguments("bool?", "bool").WithLocation(7, 13), // (7,13): warning CS1718: Comparison made to same variable; did you mean to compare something else? // if (a == a) { } Diagnostic(ErrorCode.WRN_ComparisonToSelf, "a == a").WithLocation(7, 13) ); } [Fact] public void TestElementNames() { var source = @" #pragma warning disable CS0219 using static System.Console; public class C { public static void Main() { int a = 1; int b = 2; int c = 3; int d = 4; int x = 5; int y = 6; (int x, int y) t1 = (1, 2); (int, int) t2 = (1, 2); Write($""{REPLACE}""); } } "; // tuple expression vs tuple expression validate("t1 == t2"); // tuple expression vs tuple literal validate("t1 == (x: 1, y: 2)"); validate("t1 == (1, 2)"); validate("(1, 2) == t1"); validate("(x: 1, d) == t1"); validate("t2 == (x: 1, y: 2)", // (16,25): warning CS8375: The tuple element name 'x' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{t2 == (x: 1, y: 2)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "x: 1").WithArguments("x").WithLocation(16, 25), // (16,31): warning CS8375: The tuple element name 'y' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{t2 == (x: 1, y: 2)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "y: 2").WithArguments("y").WithLocation(16, 31) ); // tuple literal vs tuple literal // - warnings reported on the right when both sides could complain // - no warnings on inferred names validate("((a, b), c: 3) == ((1, x: 2), 3)", // (16,27): warning CS8375: The tuple element name 'c' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{((a, b), c: 3) == ((1, x: 2), 3)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "c: 3").WithArguments("c").WithLocation(16, 27), // (16,41): warning CS8375: The tuple element name 'x' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{((a, b), c: 3) == ((1, x: 2), 3)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "x: 2").WithArguments("x").WithLocation(16, 41) ); validate("(a, b) == (a: 1, b: 2)"); validate("(a, b) == (c: 1, d)", // (16,29): warning CS8375: The tuple element name 'c' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{(a, b) == (c: 1, d)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "c: 1").WithArguments("c").WithLocation(16, 29) ); validate("(a: 1, b: 2) == (c: 1, d)", // (16,35): warning CS8375: The tuple element name 'c' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{(a: 1, b: 2) == (c: 1, d)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "c: 1").WithArguments("c").WithLocation(16, 35), // (16,25): warning CS8375: The tuple element name 'b' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{(a: 1, b: 2) == (c: 1, d)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "b: 2").WithArguments("b").WithLocation(16, 25) ); validate("(null, b) == (c: null, d: 2)", // (16,32): warning CS8375: The tuple element name 'c' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{(null, b) == (c: null, d: 2)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "c: null").WithArguments("c").WithLocation(16, 32), // (16,41): warning CS8375: The tuple element name 'd' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{(null, b) == (c: null, d: 2)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "d: 2").WithArguments("d").WithLocation(16, 41) ); void validate(string expression, params DiagnosticDescription[] diagnostics) { var comp = CreateCompilation(source.Replace("REPLACE", expression)); comp.VerifyDiagnostics(diagnostics); } } [Fact] void TestValueTupleWithObsoleteEqualityOperator() { string source = @" public class C { public static void Main() { System.Console.Write((1, 2) == (3, 4)); } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } [System.Obsolete] public static bool operator==(ValueTuple<T1, T2> t1, ValueTuple<T1, T2> t2) => throw null; public static bool operator!=(ValueTuple<T1, T2> t1, ValueTuple<T1, T2> t2) => throw null; public override bool Equals(object other) => throw null; public override int GetHashCode() => throw null; } } "; var comp = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); // Note: tuple equality picked ahead of custom operator== CompileAndVerify(comp, expectedOutput: "False"); } [Fact] public void TestInExpressionTree() { var source = @" using System; using System.Linq.Expressions; public class C { public static void Main() { Expression<Func<int, bool>> expr = i => (i, i) == (i, i); Expression<Func<(int, int), bool>> expr2 = t => t != t; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,49): error CS8374: An expression tree may not contain a tuple == or != operator // Expression<Func<int, bool>> expr = i => (i, i) == (i, i); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleBinOp, "(i, i) == (i, i)").WithLocation(8, 49), // (8,49): error CS8143: An expression tree may not contain a tuple literal. // Expression<Func<int, bool>> expr = i => (i, i) == (i, i); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, "(i, i)").WithLocation(8, 49), // (8,59): error CS8143: An expression tree may not contain a tuple literal. // Expression<Func<int, bool>> expr = i => (i, i) == (i, i); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, "(i, i)").WithLocation(8, 59), // (9,57): error CS8374: An expression tree may not contain a tuple == or != operator // Expression<Func<(int, int), bool>> expr2 = t => t != t; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleBinOp, "t != t").WithLocation(9, 57) ); } [Fact] public void TestComparisonOfDynamicAndTuple() { var source = @" public class C { (long, string) _t; public C(long l, string s) { _t = (l, s); } public static void Main() { dynamic d = new C(1, ""hello""); (long, string) tuple1 = (1, ""hello""); (long, string) tuple2 = (2, ""world""); System.Console.Write($""{d == tuple1} {d != tuple1} {d == tuple2} {d != tuple2}""); } public static bool operator==(C c, (long, string) t) { return c._t.Item1 == t.Item1 && c._t.Item2 == t.Item2; } public static bool operator!=(C c, (long, string) t) { return !(c == t); } public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } "; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True False False True"); } [Fact] public void TestComparisonOfDynamicTuple() { var source = @" public class C { public static void Main() { dynamic d1 = (1, ""hello""); dynamic d2 = (1, ""hello""); dynamic d3 = ((byte)1, 2); PrintException(() => d1 == d2); PrintException(() => d1 == d3); } public static void PrintException(System.Func<bool> action) { System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture; try { action(); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { System.Console.WriteLine(e.Message); } finally { System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture; } } } "; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"Operator '==' cannot be applied to operands of type 'System.ValueTuple<int,string>' and 'System.ValueTuple<int,string>' Operator '==' cannot be applied to operands of type 'System.ValueTuple<int,string>' and 'System.ValueTuple<byte,int>'"); } [Fact] public void TestComparisonWithTupleElementNames() { var source = @" public class C { public static void Main() { int Bob = 1; System.Console.Write((Alice: 0, (Bob, 2)) == (Bob: 0, (1, Other: 2))); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (7,55): warning CS8375: The tuple element name 'Bob' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // System.Console.Write((Alice: 0, (Bob, 2)) == (Bob: 0, (1, Other: 2))); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "Bob: 0").WithArguments("Bob").WithLocation(7, 55), // (7,67): warning CS8375: The tuple element name 'Other' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // System.Console.Write((Alice: 0, (Bob, 2)) == (Bob: 0, (1, Other: 2))); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "Other: 2").WithArguments("Other").WithLocation(7, 67) ); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var equals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); // check left tuple var leftTuple = equals.Left; var leftInfo = model.GetTypeInfo(leftTuple); Assert.Equal("(System.Int32 Alice, (System.Int32 Bob, System.Int32))", leftInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int32 Alice, (System.Int32 Bob, System.Int32))", leftInfo.ConvertedType.ToTestDisplayString()); // check right tuple var rightTuple = equals.Right; var rightInfo = model.GetTypeInfo(rightTuple); Assert.Equal("(System.Int32 Bob, (System.Int32, System.Int32 Other))", rightInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int32 Bob, (System.Int32, System.Int32 Other))", rightInfo.ConvertedType.ToTestDisplayString()); } [Fact] public void TestComparisonWithCastedTuples() { var source = @" public class C { public static void Main() { System.Console.Write( ((string, (byte, long))) (null, (1, 2L)) == ((string, (long, byte))) (null, (1L, 2)) ); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var equals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); // check left cast ... var leftCast = (CastExpressionSyntax)equals.Left; Assert.Equal("((string, (byte, long))) (null, (1, 2L))", leftCast.ToString()); var leftCastInfo = model.GetTypeInfo(leftCast); Assert.Equal("(System.String, (System.Byte, System.Int64))", leftCastInfo.Type.ToTestDisplayString()); Assert.Equal("(System.String, (System.Int64, System.Int64))", leftCastInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTuple, model.GetConversion(leftCast).Kind); // ... its tuple ... var leftTuple = (TupleExpressionSyntax)leftCast.Expression; Assert.Equal("(null, (1, 2L))", leftTuple.ToString()); var leftTupleInfo = model.GetTypeInfo(leftTuple); Assert.Null(leftTupleInfo.Type); Assert.Equal("(System.String, (System.Byte, System.Int64))", leftTupleInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ExplicitTupleLiteral, model.GetConversion(leftTuple).Kind); // ... its null ... var leftNull = leftTuple.Arguments[0].Expression; Assert.Equal("null", leftNull.ToString()); var leftNullInfo = model.GetTypeInfo(leftNull); Assert.Null(leftNullInfo.Type); Assert.Equal("System.String", leftNullInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitReference, model.GetConversion(leftNull).Kind); // ... its nested tuple var leftNestedTuple = leftTuple.Arguments[1].Expression; Assert.Equal("(1, 2L)", leftNestedTuple.ToString()); var leftNestedTupleInfo = model.GetTypeInfo(leftNestedTuple); Assert.Equal("(System.Int32, System.Int64)", leftNestedTupleInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Byte, System.Int64)", leftNestedTupleInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, model.GetConversion(leftNestedTuple).Kind); // check right cast ... var rightCast = (CastExpressionSyntax)equals.Right; var rightCastInfo = model.GetTypeInfo(rightCast); Assert.Equal("(System.String, (System.Int64, System.Byte))", rightCastInfo.Type.ToTestDisplayString()); Assert.Equal("(System.String, (System.Int64, System.Int64))", rightCastInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTuple, model.GetConversion(rightCast).Kind); // ... its tuple var rightTuple = rightCast.Expression; var rightTupleInfo = model.GetTypeInfo(rightTuple); Assert.Null(rightTupleInfo.Type); Assert.Equal("(System.String, (System.Int64, System.Byte))", rightTupleInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ExplicitTupleLiteral, model.GetConversion(rightTuple).Kind); } [Fact] public void TestGenericElement() { var source = @" public class C { public void M<T>(T t) { _ = (t, t) == (t, t); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,13): error CS0019: Operator '==' cannot be applied to operands of type 'T' and 'T' // _ = (t, t) == (t, t); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(t, t) == (t, t)").WithArguments("==", "T", "T").WithLocation(6, 13), // (6,13): error CS0019: Operator '==' cannot be applied to operands of type 'T' and 'T' // _ = (t, t) == (t, t); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(t, t) == (t, t)").WithArguments("==", "T", "T").WithLocation(6, 13) ); } [Fact] public void TestNameofEquality() { var source = @" public class C { public void M() { _ = nameof((1, 2) == (3, 4)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,20): error CS8081: Expression does not have a name. // _ = nameof((1, 2) == (3, 4)); Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "(1, 2) == (3, 4)").WithLocation(6, 20) ); } [Fact] public void TestAsRefOrOutArgument() { var source = @" public class C { public void M(ref bool x, out bool y) { x = true; y = true; M(ref (1, 2) == (3, 4), out (1, 2) == (3, 4)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,15): error CS1510: A ref or out value must be an assignable variable // M(ref (1, 2) == (3, 4), out (1, 2) == (3, 4)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "(1, 2) == (3, 4)").WithLocation(8, 15), // (8,37): error CS1510: A ref or out value must be an assignable variable // M(ref (1, 2) == (3, 4), out (1, 2) == (3, 4)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "(1, 2) == (3, 4)").WithLocation(8, 37) ); } [Fact] public void TestWithAnonymousTypes() { var source = @" public class C { public static void Main() { var a = new { A = 1 }; var b = new { B = 2 }; var c = new { A = 1 }; var d = new { B = 2 }; System.Console.Write((a, b) == (a, b)); System.Console.Write((a, b) == (c, d)); System.Console.Write((a, b) != (c, d)); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueFalseTrue"); } [Fact] public void TestWithAnonymousTypes2() { var source = @" public class C { public static void Main() { var a = new { A = 1 }; var b = new { B = 2 }; System.Console.Write((a, b) == (b, a)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,30): error CS0019: Operator '==' cannot be applied to operands of type '<anonymous type: int A>' and '<anonymous type: int B>' // System.Console.Write((a, b) == (b, a)); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(a, b) == (b, a)").WithArguments("==", "<anonymous type: int A>", "<anonymous type: int B>").WithLocation(9, 30), // (9,30): error CS0019: Operator '==' cannot be applied to operands of type '<anonymous type: int B>' and '<anonymous type: int A>' // System.Console.Write((a, b) == (b, a)); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(a, b) == (b, a)").WithArguments("==", "<anonymous type: int B>", "<anonymous type: int A>").WithLocation(9, 30) ); } [Fact] public void TestRefReturningElements() { var source = @" public class C { public static void Main() { System.Console.Write((P, S()) == (1, ""hello"")); } public static int p = 1; public static ref int P => ref p; public static string s = ""hello""; public static ref string S() => ref s; } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); } [Fact] public void TestChecked() { var source = @" public class C { public static void Main() { try { checked { int ten = 10; System.Console.Write((2147483647 + ten, 1) == (0, 1)); } } catch (System.OverflowException) { System.Console.Write(""overflow""); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "overflow"); } [Fact] public void TestUnchecked() { var source = @" public class C { public static void Main() { unchecked { int ten = 10; System.Console.Write((2147483647 + ten, 1) == (-2147483639, 1)); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); } [Fact] public void TestInQuery() { var source = @" using System.Linq; public class C { public static void Main() { var query = from a in new int[] { 1, 2, 2} where (a, 2) == (2, a) select a; foreach (var i in query) { System.Console.Write(i); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "22"); } [Fact] public void TestWithPointer() { var source = @" public class C { public unsafe static void M() { int x = 234; int y = 236; int* p1 = &x; int* p2 = &y; _ = (p1, p2) == (p1, p2); } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (10,14): error CS0306: The type 'int*' may not be used as a type argument // _ = (p1, p2) == (p1, p2); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p1").WithArguments("int*").WithLocation(10, 14), // (10,18): error CS0306: The type 'int*' may not be used as a type argument // _ = (p1, p2) == (p1, p2); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p2").WithArguments("int*").WithLocation(10, 18), // (10,26): error CS0306: The type 'int*' may not be used as a type argument // _ = (p1, p2) == (p1, p2); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p1").WithArguments("int*").WithLocation(10, 26), // (10,30): error CS0306: The type 'int*' may not be used as a type argument // _ = (p1, p2) == (p1, p2); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p2").WithArguments("int*").WithLocation(10, 30), // (10,14): error CS0306: The type 'void*' may not be used as a type argument // _ = (p1, p2) == (p1, p2); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p1").WithArguments("void*").WithLocation(10, 14), // (10,18): error CS0306: The type 'void*' may not be used as a type argument // _ = (p1, p2) == (p1, p2); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p2").WithArguments("void*").WithLocation(10, 18), // (10,26): error CS0306: The type 'void*' may not be used as a type argument // _ = (p1, p2) == (p1, p2); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p1").WithArguments("void*").WithLocation(10, 26), // (10,30): error CS0306: The type 'void*' may not be used as a type argument // _ = (p1, p2) == (p1, p2); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p2").WithArguments("void*").WithLocation(10, 30) ); } [Fact] public void TestOrder01() { var source = @" using System; public class C { public static void Main() { X x = new X(); Y y = new Y(); Console.WriteLine((1, ((int, int))x) == (y, (1, 1))); } } class X { public static implicit operator (short, short)(X x) { Console.WriteLine(""X-> (short, short)""); return (1, 1); } } class Y { public static implicit operator int(Y x) { Console.WriteLine(""Y -> int""); return 1; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"X-> (short, short) Y -> int True"); } [Fact] public void TestOrder02() { var source = @" using System; public class C { public static void Main() { var result = (new B(1), new Nullable<B>(new A(2))) == (new A(3), new B(4)); Console.WriteLine(); Console.WriteLine(result); } } struct A { public readonly int N; public A(int n) { this.N = n; Console.Write($""new A({ n }); ""); } } struct B { public readonly int N; public B(int n) { this.N = n; Console.Write($""new B({n}); ""); } public static implicit operator B(A a) { Console.Write($""A({a.N})->""); return new B(a.N); } public static bool operator ==(B b1, B b2) { Console.Write($""B({b1.N})==B({b2.N}); ""); return b1.N == b2.N; } public static bool operator !=(B b1, B b2) { Console.Write($""B({b1.N})!=B({b2.N}); ""); return b1.N != b2.N; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (22,8): warning CS0660: 'B' defines operator == or operator != but does not override Object.Equals(object o) // struct B Diagnostic(ErrorCode.WRN_EqualityOpWithoutEquals, "B").WithArguments("B").WithLocation(22, 8), // (22,8): warning CS0661: 'B' defines operator == or operator != but does not override Object.GetHashCode() // struct B Diagnostic(ErrorCode.WRN_EqualityOpWithoutGetHashCode, "B").WithArguments("B").WithLocation(22, 8) ); CompileAndVerify(comp, expectedOutput: @"new B(1); new A(2); A(2)->new B(2); new A(3); new B(4); A(3)->new B(3); B(1)==B(3); False "); } [Fact, WorkItem(35958, "https://github.com/dotnet/roslyn/issues/35958")] public void TestMethodGroupConversionInTupleEquality_01() { var source = @" using System; public class C { public static void Main() { Action a = M; Console.WriteLine((a, M) == (M, a)); } static void M() {} }"; var comp = CompileAndVerify(source, expectedOutput: "True"); comp.VerifyDiagnostics(); } [Fact, WorkItem(35958, "https://github.com/dotnet/roslyn/issues/35958")] public void TestMethodGroupConversionInTupleEquality_02() { var source = @" using System; public class C { public static void Main() { Action a = () => {}; Console.WriteLine((a, M) == (M, a)); } static void M() {} }"; var comp = CompileAndVerify(source, expectedOutput: "False"); comp.VerifyDiagnostics(); } [Fact, WorkItem(35958, "https://github.com/dotnet/roslyn/issues/35958")] public void TestMethodGroupConversionInTupleEquality_03() { var source = @" using System; public class C { public static void Main() { K k = null; Console.WriteLine((k, 1) == (M, 1)); } static void M() {} } class K { public static bool operator ==(K k, System.Action a) => true; public static bool operator !=(K k, System.Action a) => false; public override bool Equals(object other) => false; public override int GetHashCode() => 1; } "; var comp = CompileAndVerify(source, expectedOutput: "True"); comp.VerifyDiagnostics(); } [Fact, WorkItem(35958, "https://github.com/dotnet/roslyn/issues/35958")] public void TestInterpolatedStringConversionInTupleEquality_01() { var source = @" using System; public class C { public static void Main() { K k = null; Console.WriteLine((k, 1) == ($""frog"", 1)); } static void M() {} } class K { public static bool operator ==(K k, IFormattable a) => a.ToString() == ""frog""; public static bool operator !=(K k, IFormattable a) => false; public override bool Equals(object other) => false; public override int GetHashCode() => 1; } "; var comp = CompileAndVerify(source, expectedOutput: "True"); comp.VerifyDiagnostics(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { [CompilerTrait(CompilerFeature.TupleEquality)] public class CodeGenTupleEqualityTests : CSharpTestBase { [Fact] public void TestCSharp7_2() { var source = @" class C { static void Main() { var t = (1, 2); System.Console.Write(t == (1, 2)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_2); comp.VerifyDiagnostics( // (7,30): error CS8320: Feature 'tuple equality' is not available in C# 7.2. Please use language version 7.3 or greater. // System.Console.Write(t == (1, 2)); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "t == (1, 2)").WithArguments("tuple equality", "7.3").WithLocation(7, 30) ); } [Theory] [InlineData("(1, 2)", "(1L, 2L)", true)] [InlineData("(1, 2)", "(1, 0)", false)] [InlineData("(1, 2)", "(0, 2)", false)] [InlineData("(1, 2)", "((long, long))(1, 2)", true)] [InlineData("((1, 2L), (3, 4))", "((1L, 2), (3L, 4))", true)] [InlineData("((1, 2L), (3, 4))", "((0L, 2), (3L, 4))", false)] [InlineData("((1, 2L), (3, 4))", "((1L, 0), (3L, 4))", false)] [InlineData("((1, 2L), (3, 4))", "((1L, 0), (0L, 4))", false)] [InlineData("((1, 2L), (3, 4))", "((1L, 0), (3L, 0))", false)] void TestSimple(string change1, string change2, bool expectedMatch) { var sourceTemplate = @" class C { static void Main() { var t1 = CHANGE1; var t2 = CHANGE2; System.Console.Write($""{(t1 == t2) == EXPECTED} {(t1 != t2) != EXPECTED}""); } }"; string source = sourceTemplate .Replace("CHANGE1", change1) .Replace("CHANGE2", change2) .Replace("EXPECTED", expectedMatch ? "true" : "false"); string name = GetUniqueName(); var comp = CreateCompilation(source, options: TestOptions.DebugExe, assemblyName: name); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True True"); } [Fact] public void TestTupleLiteralsWithDifferentCardinalities() { var source = @" class C { static bool M() { return (1, 1) == (2, 2, 2); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,16): error CS8373: Tuple types used as operands of an == or != operator must have matching cardinalities. But this operator has tuple types of cardinality 2 on the left and 3 on the right. // return (1, 1) == (2, 2, 2); Diagnostic(ErrorCode.ERR_TupleSizesMismatchForBinOps, "(1, 1) == (2, 2, 2)").WithArguments("2", "3").WithLocation(6, 16) ); } [Fact] public void TestTuplesWithDifferentCardinalities() { var source = @" class C { static bool M() { var t1 = (1, 1); var t2 = (2, 2, 2); return t1 == t2; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,16): error CS8355: Tuple types used as operands of a binary operator must have matching cardinalities. But this operator has tuple types of cardinality 2 on the left and 3 on the right. // return t1 == t2; Diagnostic(ErrorCode.ERR_TupleSizesMismatchForBinOps, "t1 == t2").WithArguments("2", "3").WithLocation(8, 16) ); } [Fact] public void TestNestedTuplesWithDifferentCardinalities() { var source = @" class C { static bool M() { var t1 = (1, (1, 1)); var t2 = (2, (2, 2, 2)); return t1 == t2; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,16): error CS8355: Tuple types used as operands of a binary operator must have matching cardinalities. But this operator has tuple types of cardinality 2 on the left and 3 on the right. // return t1 == t2; Diagnostic(ErrorCode.ERR_TupleSizesMismatchForBinOps, "t1 == t2").WithArguments("2", "3").WithLocation(8, 16) ); } [Fact, WorkItem(25295, "https://github.com/dotnet/roslyn/issues/25295")] public void TestWithoutValueTuple() { var source = @" class C { static bool M() { return (1, 2) == (3, 4); } }"; var comp = CreateCompilationWithMscorlib40(source); // https://github.com/dotnet/roslyn/issues/25295 // Can we relax the requirement on ValueTuple types being found? comp.VerifyDiagnostics( // (6,16): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // return (1, 2) == (3, 4); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(1, 2)").WithArguments("System.ValueTuple`2").WithLocation(6, 16), // (6,26): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // return (1, 2) == (3, 4); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(3, 4)").WithArguments("System.ValueTuple`2").WithLocation(6, 26) ); } [Fact] public void TestNestedNullableTuplesWithDifferentCardinalities() { var source = @" class C { static bool M() { (int, int)? nt = (1, 1); var t1 = (1, nt); var t2 = (2, (2, 2, 2)); return t1 == t2; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,16): error CS8373: Tuple types used as operands of a binary operator must have matching cardinalities. But this operator has tuple types of cardinality 2 on the left and 3 on the right. // return t1 == t2; Diagnostic(ErrorCode.ERR_TupleSizesMismatchForBinOps, "t1 == t2").WithArguments("2", "3").WithLocation(9, 16) ); } [Fact] public void TestILForSimpleEqual() { var source = @" class C { static bool M() { var t1 = (1, 1); var t2 = (2, 2); return t1 == t2; } }"; var comp = CompileAndVerify(source); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @"{ // Code size 50 (0x32) .maxstack 3 .locals init (System.ValueTuple<int, int> V_0, //t1 System.ValueTuple<int, int> V_1, System.ValueTuple<int, int> V_2) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldc.i4.1 IL_0004: call ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0009: ldc.i4.2 IL_000a: ldc.i4.2 IL_000b: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0010: ldloc.0 IL_0011: stloc.1 IL_0012: stloc.2 IL_0013: ldloc.1 IL_0014: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0019: ldloc.2 IL_001a: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_001f: bne.un.s IL_0030 IL_0021: ldloc.1 IL_0022: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0027: ldloc.2 IL_0028: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_002d: ceq IL_002f: ret IL_0030: ldc.i4.0 IL_0031: ret }"); } [Fact] public void TestILForSimpleNotEqual() { var source = @" class C { static bool M((int, int) t1, (int, int) t2) { return t1 != t2; } }"; var comp = CompileAndVerify(source); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @"{ // Code size 38 (0x26) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0, System.ValueTuple<int, int> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.1 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0010: bne.un.s IL_0024 IL_0012: ldloc.0 IL_0013: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_001e: ceq IL_0020: ldc.i4.0 IL_0021: ceq IL_0023: ret IL_0024: ldc.i4.1 IL_0025: ret }"); } [Fact] public void TestILForSimpleEqualOnInTuple() { var source = @" class C { static bool M(in (int, int) t1, in (int, int) t2) { return t1 == t2; } }"; var comp = CompileAndVerify(source); comp.VerifyDiagnostics(); // note: the logic to save variables and side-effects results in copying the inputs comp.VerifyIL("C.M", @"{ // Code size 45 (0x2d) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0, System.ValueTuple<int, int> V_1) IL_0000: ldarg.0 IL_0001: ldobj ""System.ValueTuple<int, int>"" IL_0006: stloc.0 IL_0007: ldarg.1 IL_0008: ldobj ""System.ValueTuple<int, int>"" IL_000d: stloc.1 IL_000e: ldloc.0 IL_000f: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0014: ldloc.1 IL_0015: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_001a: bne.un.s IL_002b IL_001c: ldloc.0 IL_001d: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0022: ldloc.1 IL_0023: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0028: ceq IL_002a: ret IL_002b: ldc.i4.0 IL_002c: ret }"); } [Fact] public void TestILForSimpleEqualOnTupleLiterals() { var source = @" class C { static void Main() { M(1, 1); M(1, 2); M(2, 1); } static void M(int x, byte y) { System.Console.Write($""{(x, x) == (y, y)} ""); } }"; var comp = CompileAndVerify(source, expectedOutput: "True False False"); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @"{ // Code size 38 (0x26) .maxstack 3 .locals init (int V_0, byte V_1, byte V_2) IL_0000: ldstr ""{0} "" IL_0005: ldarg.0 IL_0006: ldarg.0 IL_0007: stloc.0 IL_0008: ldarg.1 IL_0009: stloc.1 IL_000a: ldarg.1 IL_000b: stloc.2 IL_000c: ldloc.1 IL_000d: bne.un.s IL_0015 IL_000f: ldloc.0 IL_0010: ldloc.2 IL_0011: ceq IL_0013: br.s IL_0016 IL_0015: ldc.i4.0 IL_0016: box ""bool"" IL_001b: call ""string string.Format(string, object)"" IL_0020: call ""void System.Console.Write(string)"" IL_0025: ret }"); var tree = comp.Compilation.SyntaxTrees.First(); var model = comp.Compilation.GetSemanticModel(tree); // check x var tupleX = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal("(x, x)", tupleX.ToString()); Assert.Equal(Conversion.Identity, model.GetConversion(tupleX)); Assert.Null(model.GetSymbolInfo(tupleX).Symbol); var lastX = tupleX.Arguments[1].Expression; Assert.Equal("x", lastX.ToString()); Assert.Equal(Conversion.Identity, model.GetConversion(lastX)); Assert.Equal("System.Int32 x", model.GetSymbolInfo(lastX).Symbol.ToTestDisplayString()); var xSymbol = model.GetTypeInfo(lastX); Assert.Equal("System.Int32", xSymbol.Type.ToTestDisplayString()); Assert.Equal("System.Int32", xSymbol.ConvertedType.ToTestDisplayString()); var tupleXSymbol = model.GetTypeInfo(tupleX); Assert.Equal("(System.Int32, System.Int32)", tupleXSymbol.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)", tupleXSymbol.ConvertedType.ToTestDisplayString()); // check y var tupleY = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().Last(); Assert.Equal("(y, y)", tupleY.ToString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(tupleY).Kind); var lastY = tupleY.Arguments[1].Expression; Assert.Equal("y", lastY.ToString()); Assert.Equal(Conversion.ImplicitNumeric, model.GetConversion(lastY)); var ySymbol = model.GetTypeInfo(lastY); Assert.Equal("System.Byte", ySymbol.Type.ToTestDisplayString()); Assert.Equal("System.Int32", ySymbol.ConvertedType.ToTestDisplayString()); var tupleYSymbol = model.GetTypeInfo(tupleY); Assert.Equal("(System.Byte, System.Byte)", tupleYSymbol.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)", tupleYSymbol.ConvertedType.ToTestDisplayString()); } [Fact] public void TestILForAlwaysValuedNullable() { var source = @" class C { static void Main() { System.Console.Write($""{(new int?(Identity(42)), (int?)2) == (new int?(42), new int?(2))} ""); } static int Identity(int x) => x; }"; var comp = CompileAndVerify(source, expectedOutput: "True"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 39 (0x27) .maxstack 3 IL_0000: ldstr ""{0} "" IL_0005: ldc.i4.s 42 IL_0007: call ""int C.Identity(int)"" IL_000c: ldc.i4.s 42 IL_000e: bne.un.s IL_0016 IL_0010: ldc.i4.2 IL_0011: ldc.i4.2 IL_0012: ceq IL_0014: br.s IL_0017 IL_0016: ldc.i4.0 IL_0017: box ""bool"" IL_001c: call ""string string.Format(string, object)"" IL_0021: call ""void System.Console.Write(string)"" IL_0026: ret }"); } [Fact] public void TestILForNullableElementsEqualsToNull() { var source = @" class C { static void Main() { System.Console.Write(M(null, null)); System.Console.Write(M(1, true)); } static bool M(int? i1, bool? b1) { var t1 = (i1, b1); return t1 == (null, null); } }"; var comp = CompileAndVerify(source, expectedOutput: "TrueFalse"); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @"{ // Code size 40 (0x28) .maxstack 2 .locals init (System.ValueTuple<int?, bool?> V_0) IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: newobj ""System.ValueTuple<int?, bool?>..ctor(int?, bool?)"" IL_0007: stloc.0 IL_0008: ldloca.s V_0 IL_000a: ldflda ""int? System.ValueTuple<int?, bool?>.Item1"" IL_000f: call ""bool int?.HasValue.get"" IL_0014: brtrue.s IL_0026 IL_0016: ldloca.s V_0 IL_0018: ldflda ""bool? System.ValueTuple<int?, bool?>.Item2"" IL_001d: call ""bool bool?.HasValue.get"" IL_0022: ldc.i4.0 IL_0023: ceq IL_0025: ret IL_0026: ldc.i4.0 IL_0027: ret }"); } [Fact] public void TestILForNullableElementsNotEqualsToNull() { var source = @" class C { static void Main() { System.Console.Write(M(null, null)); System.Console.Write(M(1, true)); } static bool M(int? i1, bool? b1) { var t1 = (i1, b1); return t1 != (null, null); } }"; var comp = CompileAndVerify(source, expectedOutput: "FalseTrue"); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @"{ // Code size 37 (0x25) .maxstack 2 .locals init (System.ValueTuple<int?, bool?> V_0) IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: newobj ""System.ValueTuple<int?, bool?>..ctor(int?, bool?)"" IL_0007: stloc.0 IL_0008: ldloca.s V_0 IL_000a: ldflda ""int? System.ValueTuple<int?, bool?>.Item1"" IL_000f: call ""bool int?.HasValue.get"" IL_0014: brtrue.s IL_0023 IL_0016: ldloca.s V_0 IL_0018: ldflda ""bool? System.ValueTuple<int?, bool?>.Item2"" IL_001d: call ""bool bool?.HasValue.get"" IL_0022: ret IL_0023: ldc.i4.1 IL_0024: ret }"); } [Fact] public void TestILForNullableElementsComparedToNonNullValues() { var source = @" class C { static void Main() { System.Console.Write(M((null, null))); System.Console.Write(M((2, true))); } static bool M((int?, bool?) t1) { return t1 == (2, true); } }"; var comp = CompileAndVerify(source, expectedOutput: "FalseTrue"); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @"{ // Code size 63 (0x3f) .maxstack 2 .locals init (System.ValueTuple<int?, bool?> V_0, int? V_1, int V_2, bool? V_3, bool V_4) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldfld ""int? System.ValueTuple<int?, bool?>.Item1"" IL_0008: stloc.1 IL_0009: ldc.i4.2 IL_000a: stloc.2 IL_000b: ldloca.s V_1 IL_000d: call ""int int?.GetValueOrDefault()"" IL_0012: ldloc.2 IL_0013: ceq IL_0015: ldloca.s V_1 IL_0017: call ""bool int?.HasValue.get"" IL_001c: and IL_001d: brfalse.s IL_003d IL_001f: ldloc.0 IL_0020: ldfld ""bool? System.ValueTuple<int?, bool?>.Item2"" IL_0025: stloc.3 IL_0026: ldc.i4.1 IL_0027: stloc.s V_4 IL_0029: ldloca.s V_3 IL_002b: call ""bool bool?.GetValueOrDefault()"" IL_0030: ldloc.s V_4 IL_0032: ceq IL_0034: ldloca.s V_3 IL_0036: call ""bool bool?.HasValue.get"" IL_003b: and IL_003c: ret IL_003d: ldc.i4.0 IL_003e: ret }"); } [Fact] public void TestILForNullableStructEqualsToNull() { var source = @" struct S { static void Main() { S? s = null; _ = s == null; System.Console.Write((s, null) == (null, s)); } }"; var comp = CompileAndVerify(source, expectedOutput: "True"); comp.VerifyDiagnostics(); comp.VerifyIL("S.Main", @"{ // Code size 48 (0x30) .maxstack 2 .locals init (S? V_0, //s S? V_1, S? V_2) IL_0000: ldloca.s V_0 IL_0002: initobj ""S?"" IL_0008: ldloca.s V_0 IL_000a: call ""bool S?.HasValue.get"" IL_000f: pop IL_0010: ldloc.0 IL_0011: stloc.1 IL_0012: ldloc.0 IL_0013: stloc.2 IL_0014: ldloca.s V_1 IL_0016: call ""bool S?.HasValue.get"" IL_001b: brtrue.s IL_0029 IL_001d: ldloca.s V_2 IL_001f: call ""bool S?.HasValue.get"" IL_0024: ldc.i4.0 IL_0025: ceq IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: call ""void System.Console.Write(bool)"" IL_002f: ret }"); } [Fact, WorkItem(25488, "https://github.com/dotnet/roslyn/issues/25488")] public void TestThisStruct() { var source = @" public struct S { public int I; public static void Main() { S s = new S() { I = 1 }; s.M(); } void M() { System.Console.Write((this, 2) == (1, this.Mutate())); } S Mutate() { I++; return this; } public static implicit operator S(int value) { return new S() { I = value }; } public static bool operator==(S s1, S s2) { System.Console.Write($""{s1.I} == {s2.I}, ""); return s1.I == s2.I; } public static bool operator!=(S s1, S s2) { throw null; } public override bool Equals(object o) { throw null; } public override int GetHashCode() { throw null; } }"; var comp = CompileAndVerify(source, expectedOutput: "1 == 1, 2 == 2, True"); comp.VerifyDiagnostics(); } [Fact] public void TestThisClass() { var source = @" public class C { public int I; public static void Main() { C c = new C() { I = 1 }; c.M(); } void M() { System.Console.Write((this, 2) == (2, this.Mutate())); } C Mutate() { I++; return this; } public static implicit operator C(int value) { return new C() { I = value }; } public static bool operator==(C c1, C c2) { System.Console.Write($""{c1.I} == {c2.I}, ""); return c1.I == c2.I; } public static bool operator!=(C c1, C c2) { throw null; } public override bool Equals(object o) { throw null; } public override int GetHashCode() { throw null; } }"; var comp = CompileAndVerify(source, expectedOutput: "2 == 2, 2 == 2, True"); comp.VerifyDiagnostics(); } [Fact] public void TestSimpleEqualOnTypelessTupleLiteral() { var source = @" class C { static bool M((string, long) t) { return t == (null, 1) && t == (""hello"", 1); } }"; var comp = CompileAndVerify(source); comp.VerifyDiagnostics(); var tree = comp.Compilation.SyntaxTrees.First(); var model = comp.Compilation.GetSemanticModel(tree); var tuple1 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(0); var symbol1 = model.GetTypeInfo(tuple1); Assert.Null(symbol1.Type); Assert.Equal("(System.String, System.Int64)", symbol1.ConvertedType.ToTestDisplayString()); Assert.Equal("(System.String, System.Int64)", model.GetDeclaredSymbol(tuple1).ToTestDisplayString()); var tuple2 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); var symbol2 = model.GetTypeInfo(tuple2); Assert.Equal("(System.String, System.Int32)", symbol2.Type.ToTestDisplayString()); Assert.Equal("(System.String, System.Int64)", symbol2.ConvertedType.ToTestDisplayString()); Assert.False(model.GetConstantValue(tuple2).HasValue); Assert.Equal(1, model.GetConstantValue(tuple2.Arguments[1].Expression).Value); } [Fact] public void TestConversionOnTupleExpression() { var source = @" class C { static bool M((int, byte) t) { return t == (1L, 2); } }"; var comp = CompileAndVerify(source); comp.VerifyDiagnostics(); var tree = comp.Compilation.SyntaxTrees.First(); var model = comp.Compilation.GetSemanticModel(tree); var equals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); // check t var t = equals.Left; Assert.Equal("t", t.ToString()); Assert.Equal("(System.Int32, System.Byte) t", model.GetSymbolInfo(t).Symbol.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTuple, model.GetConversion(t).Kind); var tTypeInfo = model.GetTypeInfo(t); Assert.Equal("(System.Int32, System.Byte)", tTypeInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, System.Int32)", tTypeInfo.ConvertedType.ToTestDisplayString()); // check tuple var tuple = equals.Right; Assert.Equal("(1L, 2)", tuple.ToString()); Assert.Null(model.GetSymbolInfo(tuple).Symbol); Assert.Equal(Conversion.Identity, model.GetConversion(tuple)); var tupleTypeInfo = model.GetTypeInfo(tuple); Assert.Equal("(System.Int64, System.Int32)", tupleTypeInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, System.Int32)", tupleTypeInfo.ConvertedType.ToTestDisplayString()); } [Fact] public void TestOtherOperatorsOnTuples() { var source = @" class C { void M() { var t1 = (1, 2); _ = t1 + t1; // error 1 _ = t1 > t1; // error 2 _ = t1 >= t1; // error 3 _ = !t1; // error 4 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,13): error CS0019: Operator '+' cannot be applied to operands of type '(int, int)' and '(int, int)' // _ = t1 + t1; // error 1 Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 + t1").WithArguments("+", "(int, int)", "(int, int)").WithLocation(7, 13), // (8,13): error CS0019: Operator '>' cannot be applied to operands of type '(int, int)' and '(int, int)' // _ = t1 > t1; // error 2 Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 > t1").WithArguments(">", "(int, int)", "(int, int)").WithLocation(8, 13), // (9,13): error CS0019: Operator '>=' cannot be applied to operands of type '(int, int)' and '(int, int)' // _ = t1 >= t1; // error 3 Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 >= t1").WithArguments(">=", "(int, int)", "(int, int)").WithLocation(9, 13), // (10,13): error CS0023: Operator '!' cannot be applied to operand of type '(int, int)' // _ = !t1; // error 4 Diagnostic(ErrorCode.ERR_BadUnaryOp, "!t1").WithArguments("!", "(int, int)").WithLocation(10, 13) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var tuple = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().Single(); Assert.Equal("(System.Int32, System.Int32)", model.GetDeclaredSymbol(tuple).ToTestDisplayString()); } [Fact] public void TestTypelessTuples() { var source = @" class C { static void Main() { string s = null; System.Console.Write((s, null) == (null, s)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); // check first tuple and its null var tuple1 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal("(s, null)", tuple1.ToString()); var tupleType1 = model.GetTypeInfo(tuple1); Assert.Null(tupleType1.Type); Assert.Equal("(System.String s, System.String)", tupleType1.ConvertedType.ToTestDisplayString()); var tuple1Null = tuple1.Arguments[1].Expression; var tuple1NullTypeInfo = model.GetTypeInfo(tuple1Null); Assert.Null(tuple1NullTypeInfo.Type); Assert.Equal("System.String", tuple1NullTypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitReference, model.GetConversion(tuple1Null).Kind); // check second tuple and its null var tuple2 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal("(null, s)", tuple2.ToString()); var tupleType2 = model.GetTypeInfo(tuple2); Assert.Null(tupleType2.Type); Assert.Equal("(System.String, System.String s)", tupleType2.ConvertedType.ToTestDisplayString()); var tuple2Null = tuple2.Arguments[0].Expression; var tuple2NullTypeInfo = model.GetTypeInfo(tuple2Null); Assert.Null(tuple2NullTypeInfo.Type); Assert.Equal("System.String", tuple2NullTypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitReference, model.GetConversion(tuple2Null).Kind); } [Fact] public void TestWithNoSideEffectsOrTemps() { var source = @" class C { static void Main() { System.Console.Write((1, 2) == (1, 3)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "False"); } [Fact] public void TestSimpleTupleAndTupleType_01() { var source = @" class C { static void Main() { var t1 = (1, 2L); System.Console.Write(t1 == (1L, 2)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var equals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); // check t1 var t1 = equals.Left; Assert.Equal("t1", t1.ToString()); var t1TypeInfo = model.GetTypeInfo(t1); Assert.Equal("(System.Int32, System.Int64)", t1TypeInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, System.Int64)", t1TypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTuple, model.GetConversion(t1).Kind); // check tuple and its literal 2 var tuple = (TupleExpressionSyntax)equals.Right; Assert.Equal("(1L, 2)", tuple.ToString()); var tupleType = model.GetTypeInfo(tuple); Assert.Equal("(System.Int64, System.Int32)", tupleType.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, System.Int64)", tupleType.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(tuple).Kind); var two = tuple.Arguments[1].Expression; Assert.Equal("2", two.ToString()); var twoType = model.GetTypeInfo(two); Assert.Equal("System.Int32", twoType.Type.ToTestDisplayString()); Assert.Equal("System.Int64", twoType.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitNumeric, model.GetConversion(two).Kind); } [Fact] public void TestSimpleTupleAndTupleType_02() { var source = @" class C { static void Main() { var t1 = (1, 2UL); System.Console.Write(t1 == (1L, 2)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var equals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); // check t1 var t1 = equals.Left; Assert.Equal("t1", t1.ToString()); var t1TypeInfo = model.GetTypeInfo(t1); Assert.Equal("(System.Int32, System.UInt64)", t1TypeInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, System.UInt64)", t1TypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTuple, model.GetConversion(t1).Kind); // check tuple and its literal 2 var tuple = (TupleExpressionSyntax)equals.Right; Assert.Equal("(1L, 2)", tuple.ToString()); var tupleType = model.GetTypeInfo(tuple); Assert.Equal("(System.Int64, System.Int32)", tupleType.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, System.UInt64)", tupleType.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(tuple).Kind); var two = tuple.Arguments[1].Expression; Assert.Equal("2", two.ToString()); var twoType = model.GetTypeInfo(two); Assert.Equal("System.Int32", twoType.Type.ToTestDisplayString()); Assert.Equal("System.UInt64", twoType.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitConstant, model.GetConversion(two).Kind); } [Fact] public void TestNestedTupleAndTupleType() { var source = @" class C { static void Main() { var t1 = (1, (2L, ""hello"")); var t2 = (2, ""hello""); System.Console.Write(t1 == (1L, t2)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var equals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); // check t1 var t1 = equals.Left; Assert.Equal("t1", t1.ToString()); var t1TypeInfo = model.GetTypeInfo(t1); Assert.Equal("(System.Int32, (System.Int64, System.String))", t1TypeInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, (System.Int64, System.String))", t1TypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTuple, model.GetConversion(t1).Kind); Assert.Equal("(System.Int32, (System.Int64, System.String)) t1", model.GetSymbolInfo(t1).Symbol.ToTestDisplayString()); // check tuple and its t2 var tuple = (TupleExpressionSyntax)equals.Right; Assert.Equal("(1L, t2)", tuple.ToString()); var tupleType = model.GetTypeInfo(tuple); Assert.Equal("(System.Int64, (System.Int32, System.String) t2)", tupleType.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, (System.Int64, System.String) t2)", tupleType.ConvertedType.ToTestDisplayString()); var t2 = tuple.Arguments[1].Expression; Assert.Equal("t2", t2.ToString()); var t2TypeInfo = model.GetTypeInfo(t2); Assert.Equal("(System.Int32, System.String)", t2TypeInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, System.String)", t2TypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTuple, model.GetConversion(t2).Kind); Assert.Equal("(System.Int32, System.String) t2", model.GetSymbolInfo(t2).Symbol.ToTestDisplayString()); } [Fact] public void TestTypelessTupleAndTupleType() { var source = @" class C { static void Main() { (string, string) t = (null, null); System.Console.Write(t == (null, null)); System.Console.Write(t != (null, null)); System.Console.Write((1, t) == (1, (null, null))); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueFalseTrue"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var tuple = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal("(null, null)", tuple.ToString()); var tupleType = model.GetTypeInfo(tuple); Assert.Null(tupleType.Type); Assert.Equal("(System.String, System.String)", tupleType.ConvertedType.ToTestDisplayString()); // check last tuple ... var lastEquals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Last(); var lastTuple = (TupleExpressionSyntax)lastEquals.Right; Assert.Equal("(1, (null, null))", lastTuple.ToString()); TypeInfo lastTupleTypeInfo = model.GetTypeInfo(lastTuple); Assert.Null(lastTupleTypeInfo.Type); Assert.Equal("(System.Int32, (System.String, System.String))", lastTupleTypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(lastTuple).Kind); // ... and its nested (null, null) tuple ... var nullNull = (TupleExpressionSyntax)lastTuple.Arguments[1].Expression; TypeInfo nullNullTypeInfo = model.GetTypeInfo(nullNull); Assert.Null(nullNullTypeInfo.Type); Assert.Equal("(System.String, System.String)", nullNullTypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(nullNull).Kind); // ... and its last null. var lastNull = nullNull.Arguments[1].Expression; TypeInfo lastNullTypeInfo = model.GetTypeInfo(lastNull); Assert.Null(lastNullTypeInfo.Type); Assert.Equal("System.String", lastNullTypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitReference, model.GetConversion(lastNull).Kind); } [Fact] public void TestTypedTupleAndDefault() { var source = @" class C { static void Main() { (string, string) t = (null, null); System.Console.Write(t == default); System.Console.Write(t != default); (string, string) t2 = (null, ""hello""); System.Console.Write(t2 == default); System.Console.Write(t2 != default); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueFalseFalseTrue"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var defaultLiterals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>() .Where(e => e.Kind() == SyntaxKind.DefaultLiteralExpression); foreach (var literal in defaultLiterals) { Assert.Equal("default", literal.ToString()); var info = model.GetTypeInfo(literal); Assert.Equal("(System.String, System.String)", info.Type.ToTestDisplayString()); Assert.Equal("(System.String, System.String)", info.ConvertedType.ToTestDisplayString()); } } [Fact] public void TestNullableTupleAndDefault() { var source = @" class C { static void Main() { (string, string)? t = (null, null); System.Console.Write(t == default); System.Console.Write(t != default); System.Console.Write(default == t); System.Console.Write(default != t); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "FalseTrueFalseTrue"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var defaultLiterals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>() .Where(e => e.Kind() == SyntaxKind.DefaultLiteralExpression); foreach (var literal in defaultLiterals) { Assert.Equal("default", literal.ToString()); var info = model.GetTypeInfo(literal); Assert.Equal("(System.String, System.String)?", info.Type.ToTestDisplayString()); Assert.Equal("(System.String, System.String)?", info.ConvertedType.ToTestDisplayString()); } } [Fact] public void TestNullableTupleAndDefault_Nested() { var source = @" class C { static void Main() { (string, string)? t = (null, null); System.Console.Write((null, t) == (null, default)); System.Console.Write((t, null) != (default, null)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "FalseTrue"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var defaultLiterals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>() .Where(e => e.Kind() == SyntaxKind.DefaultLiteralExpression); foreach (var literal in defaultLiterals) { Assert.Equal("default", literal.ToString()); var info = model.GetTypeInfo(literal); Assert.Equal("(System.String, System.String)?", info.Type.ToTestDisplayString()); Assert.Equal("(System.String, System.String)?", info.ConvertedType.ToTestDisplayString()); } } [Fact] public void TestNestedDefaultWithNonTupleType() { var source = @" class C { static void Main() { System.Console.Write((null, 1) == (null, default)); System.Console.Write((0, null) != (default, null)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "FalseFalse"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var defaultLiterals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>() .Where(e => e.Kind() == SyntaxKind.DefaultLiteralExpression); foreach (var literal in defaultLiterals) { Assert.Equal("default", literal.ToString()); var info = model.GetTypeInfo(literal); Assert.Equal("System.Int32", info.Type.ToTestDisplayString()); Assert.Equal("System.Int32", info.ConvertedType.ToTestDisplayString()); } } [Fact] public void TestNestedDefaultWithNullableNonTupleType() { var source = @" struct S { static void Main() { S? ns = null; _ = (null, ns) == (null, default); _ = (ns, null) != (default, null); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'default' // _ = (null, ns) == (null, default); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(null, ns) == (null, default)").WithArguments("==", "S?", "default").WithLocation(7, 13), // (8,13): error CS0019: Operator '!=' cannot be applied to operands of type 'S?' and 'default' // _ = (ns, null) != (default, null); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, null) != (default, null)").WithArguments("!=", "S?", "default").WithLocation(8, 13) ); } [Fact] public void TestNestedDefaultWithNullableNonTupleType_WithComparisonOperator() { var source = @" public struct S { public static void Main() { S? ns = new S(); System.Console.Write((null, ns) == (null, default)); System.Console.Write((ns, null) != (default, null)); } public static bool operator==(S s1, S s2) => throw null; public static bool operator!=(S s1, S s2) => throw null; public override int GetHashCode() => throw null; public override bool Equals(object o) => throw null; }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "FalseTrue"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var defaults = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>() .Where(e => e.Kind() == SyntaxKind.DefaultLiteralExpression); foreach (var literal in defaults) { var type = model.GetTypeInfo(literal); Assert.Equal("S?", type.Type.ToTestDisplayString()); Assert.Equal("S?", type.ConvertedType.ToTestDisplayString()); } } [Fact] public void TestAllDefaults() { var source = @" class C { static void Main() { System.Console.Write((default, default) == (default, default)); System.Console.Write(default == (default, default)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,30): error CS8315: Operator '==' is ambiguous on operands 'default' and 'default' // System.Console.Write((default, default) == (default, default)); Diagnostic(ErrorCode.ERR_AmbigBinaryOpsOnDefault, "(default, default) == (default, default)").WithArguments("==", "default", "default").WithLocation(6, 30), // (6,30): error CS8315: Operator '==' is ambiguous on operands 'default' and 'default' // System.Console.Write((default, default) == (default, default)); Diagnostic(ErrorCode.ERR_AmbigBinaryOpsOnDefault, "(default, default) == (default, default)").WithArguments("==", "default", "default").WithLocation(6, 30), // (7,30): error CS0034: Operator '==' is ambiguous on operands of type 'default' and '(default, default)' // System.Console.Write(default == (default, default)); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "default == (default, default)").WithArguments("==", "default", "(default, default)").WithLocation(7, 30) ); } [Fact] public void TestNullsAndDefaults() { var source = @" class C { static void Main() { _ = (null, default) != (default, null); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,13): error CS0034: Operator '!=' is ambiguous on operands of type '<null>' and 'default' // _ = (null, default) != (default, null); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "(null, default) != (default, null)").WithArguments("!=", "<null>", "default").WithLocation(6, 13), // (6,13): error CS0034: Operator '!=' is ambiguous on operands of type 'default' and '<null>' // _ = (null, default) != (default, null); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "(null, default) != (default, null)").WithArguments("!=", "default", "<null>").WithLocation(6, 13) ); } [Fact] public void TestAllDefaults_Nested() { var source = @" class C { static void Main() { System.Console.Write((null, (default, default)) == (null, (default, default))); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,30): error CS8315: Operator '==' is ambiguous on operands 'default' and 'default' // System.Console.Write((null, (default, default)) == (null, (default, default))); Diagnostic(ErrorCode.ERR_AmbigBinaryOpsOnDefault, "(null, (default, default)) == (null, (default, default))").WithArguments("==", "default", "default").WithLocation(6, 30), // (6,30): error CS8315: Operator '==' is ambiguous on operands 'default' and 'default' // System.Console.Write((null, (default, default)) == (null, (default, default))); Diagnostic(ErrorCode.ERR_AmbigBinaryOpsOnDefault, "(null, (default, default)) == (null, (default, default))").WithArguments("==", "default", "default").WithLocation(6, 30) ); } [Fact] public void TestTypedTupleAndTupleOfDefaults() { var source = @" class C { static void Main() { (string, string)? t = (null, null); System.Console.Write(t == (default, default)); System.Console.Write(t != (default, default)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueFalse"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var lastTuple = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().Last(); Assert.Equal("(default, default)", lastTuple.ToString()); Assert.Null(model.GetTypeInfo(lastTuple).Type); Assert.Equal("(System.String, System.String)?", model.GetTypeInfo(lastTuple).ConvertedType.ToTestDisplayString()); var lastDefault = lastTuple.Arguments[1].Expression; Assert.Equal("default", lastDefault.ToString()); Assert.Equal("System.String", model.GetTypeInfo(lastDefault).Type.ToTestDisplayString()); Assert.Equal("System.String", model.GetTypeInfo(lastDefault).ConvertedType.ToTestDisplayString()); } [Fact] public void TestTypelessTupleAndTupleOfDefaults() { var source = @" class C { static void Main() { System.Console.Write((null, () => 1) == (default, default)); System.Console.Write((null, () => 2) == default); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,30): error CS0034: Operator '==' is ambiguous on operands of type '<null>' and 'default' // System.Console.Write((null, () => 1) == (default, default)); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "(null, () => 1) == (default, default)").WithArguments("==", "<null>", "default").WithLocation(6, 30), // (6,30): error CS0019: Operator '==' cannot be applied to operands of type 'lambda expression' and 'default' // System.Console.Write((null, () => 1) == (default, default)); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(null, () => 1) == (default, default)").WithArguments("==", "lambda expression", "default").WithLocation(6, 30), // (7,30): error CS0034: Operator '==' is ambiguous on operands of type '(<null>, lambda expression)' and 'default' // System.Console.Write((null, () => 2) == default); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "(null, () => 2) == default").WithArguments("==", "(<null>, lambda expression)", "default").WithLocation(7, 30) ); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,30): error CS0034: Operator '==' is ambiguous on operands of type '<null>' and 'default' // System.Console.Write((null, () => 1) == (default, default)); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "(null, () => 1) == (default, default)").WithArguments("==", "<null>", "default").WithLocation(6, 30), // (7,30): error CS0034: Operator '==' is ambiguous on operands of type '(<null>, lambda expression)' and 'default' // System.Console.Write((null, () => 2) == default); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "(null, () => 2) == default").WithArguments("==", "(<null>, lambda expression)", "default").WithLocation(7, 30) ); } [Fact] public void TestNullableStructAndDefault() { var source = @" struct S { static void M(string s) { S? ns = new S(); _ = ns == null; _ = s == null; _ = ns == default; // error 1 _ = (ns, ns) == (null, null); _ = (ns, ns) == (default, default); // errors 2 and 3 _ = (ns, ns) == default; // error 4 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'default' // _ = ns == default; // error 1 Diagnostic(ErrorCode.ERR_BadBinaryOps, "ns == default").WithArguments("==", "S?", "default").WithLocation(9, 13), // (11,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'default' // _ = (ns, ns) == (default, default); // errors 2 and 3 Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, ns) == (default, default)").WithArguments("==", "S?", "default").WithLocation(11, 13), // (11,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'default' // _ = (ns, ns) == (default, default); // errors 2 and 3 Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, ns) == (default, default)").WithArguments("==", "S?", "default").WithLocation(11, 13), // (12,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'S?' // _ = (ns, ns) == default; // error 4 Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, ns) == default").WithArguments("==", "S?", "S?").WithLocation(12, 13), // (12,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'S?' // _ = (ns, ns) == default; // error 4 Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, ns) == default").WithArguments("==", "S?", "S?").WithLocation(12, 13) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var literals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>(); var nullLiteral = literals.ElementAt(0); Assert.Equal("null", nullLiteral.ToString()); Assert.Null(model.GetTypeInfo(nullLiteral).ConvertedType); var nullLiteral2 = literals.ElementAt(1); Assert.Equal("null", nullLiteral2.ToString()); Assert.Null(model.GetTypeInfo(nullLiteral2).Type); Assert.Equal("System.String", model.GetTypeInfo(nullLiteral2).ConvertedType.ToTestDisplayString()); var defaultLiterals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>() .Where(e => e.Kind() == SyntaxKind.DelegateDeclaration); foreach (var defaultLiteral in defaultLiterals) { Assert.Equal("default", defaultLiteral.ToString()); Assert.Null(model.GetTypeInfo(defaultLiteral).Type); Assert.Null(model.GetTypeInfo(defaultLiteral).ConvertedType); } } [Fact, WorkItem(25318, "https://github.com/dotnet/roslyn/issues/25318")] public void TestNullableStructAndDefault_WithComparisonOperator() { var source = @" public struct S { static void M(string s) { S? ns = new S(); _ = ns == 1; _ = (ns, ns) == (default, default); _ = (ns, ns) == default; } public static bool operator==(S s, byte b) => throw null; public static bool operator!=(S s, byte b) => throw null; public override bool Equals(object other) => throw null; public override int GetHashCode() => throw null; }"; var comp = CreateCompilation(source); // https://github.com/dotnet/roslyn/issues/25318 // This should be allowed comp.VerifyDiagnostics( // (7,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'int' // _ = ns == 1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "ns == 1").WithArguments("==", "S?", "int").WithLocation(7, 13), // (8,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'default' // _ = (ns, ns) == (default, default); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, ns) == (default, default)").WithArguments("==", "S?", "default").WithLocation(8, 13), // (8,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'default' // _ = (ns, ns) == (default, default); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, ns) == (default, default)").WithArguments("==", "S?", "default").WithLocation(8, 13), // (9,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'S?' // _ = (ns, ns) == default; Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, ns) == default").WithArguments("==", "S?", "S?").WithLocation(9, 13), // (9,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'S?' // _ = (ns, ns) == default; Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, ns) == default").WithArguments("==", "S?", "S?").WithLocation(9, 13) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var defaultLiterals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>() .Where(e => e.Kind() == SyntaxKind.DelegateDeclaration); // Should have types foreach (var defaultLiteral in defaultLiterals) { Assert.Equal("default", defaultLiteral.ToString()); Assert.Null(model.GetTypeInfo(defaultLiteral).Type); Assert.Null(model.GetTypeInfo(defaultLiteral).ConvertedType); // https://github.com/dotnet/roslyn/issues/25318 // default should become int } } [Fact] public void TestMixedTupleLiteralsAndTypes() { var source = @" class C { static void Main() { (string, string) t = (null, null); System.Console.Write((t, (null, null)) == ((null, null), t)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); // check last tuple ... var tuple = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(3); Assert.Equal("((null, null), t)", tuple.ToString()); var tupleType = model.GetTypeInfo(tuple); Assert.Null(tupleType.Type); Assert.Equal("((System.String, System.String), (System.String, System.String) t)", tupleType.ConvertedType.ToTestDisplayString()); // ... its t ... var t = tuple.Arguments[1].Expression; Assert.Equal("t", t.ToString()); var tType = model.GetTypeInfo(t); Assert.Equal("(System.String, System.String)", tType.Type.ToTestDisplayString()); Assert.Equal("(System.String, System.String)", tType.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, model.GetConversion(t).Kind); Assert.Equal("(System.String, System.String) t", model.GetSymbolInfo(t).Symbol.ToTestDisplayString()); Assert.Null(model.GetDeclaredSymbol(t)); // ... its nested tuple ... var nestedTuple = (TupleExpressionSyntax)tuple.Arguments[0].Expression; Assert.Equal("(null, null)", nestedTuple.ToString()); var nestedTupleType = model.GetTypeInfo(nestedTuple); Assert.Null(nestedTupleType.Type); Assert.Equal("(System.String, System.String)", nestedTupleType.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(nestedTuple).Kind); Assert.Null(model.GetSymbolInfo(nestedTuple).Symbol); Assert.Equal("(System.String, System.String)", model.GetDeclaredSymbol(nestedTuple).ToTestDisplayString()); // ... a nested null. var nestedNull = nestedTuple.Arguments[0].Expression; Assert.Equal("null", nestedNull.ToString()); var nestedNullType = model.GetTypeInfo(nestedNull); Assert.Null(nestedNullType.Type); Assert.Equal("System.String", nestedNullType.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitReference, model.GetConversion(nestedNull).Kind); } [Fact] public void TestAllNulls() { var source = @" class C { static void Main() { System.Console.Write(null == null); System.Console.Write((null, null) == (null, null)); System.Console.Write((null, null) != (null, null)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueTrueFalse"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var nulls = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>(); foreach (var literal in nulls) { Assert.Equal("null", literal.ToString()); var symbol = model.GetTypeInfo(literal); Assert.Null(symbol.Type); Assert.Null(symbol.ConvertedType); } var tuples = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>(); foreach (var tuple in tuples) { Assert.Equal("(null, null)", tuple.ToString()); var symbol = model.GetTypeInfo(tuple); Assert.Null(symbol.Type); Assert.Null(symbol.ConvertedType); } } [Fact] public void TestConvertedElementInTypelessTuple() { var source = @" class C { static void Main() { System.Console.Write((null, 1L) == (null, 2)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "False"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var lastLiteral = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Last(); Assert.Equal("2", lastLiteral.ToString()); var literalInfo = model.GetTypeInfo(lastLiteral); Assert.Equal("System.Int32", literalInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int64", literalInfo.ConvertedType.ToTestDisplayString()); } [Fact] public void TestConvertedElementInTypelessTuple_Nested() { var source = @" class C { static void Main() { System.Console.Write(((null, 1L), null) == ((null, 2), null)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "False"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var rightTuple = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(2); Assert.Equal("((null, 2), null)", rightTuple.ToString()); var literalInfo = model.GetTypeInfo(rightTuple); Assert.Null(literalInfo.Type); Assert.Null(literalInfo.ConvertedType); var nestedTuple = (TupleExpressionSyntax)rightTuple.Arguments[0].Expression; Assert.Equal("(null, 2)", nestedTuple.ToString()); var nestedLiteralInfo = model.GetTypeInfo(rightTuple); Assert.Null(nestedLiteralInfo.Type); Assert.Null(nestedLiteralInfo.ConvertedType); var two = nestedTuple.Arguments[1].Expression; Assert.Equal("2", two.ToString()); var twoInfo = model.GetTypeInfo(two); Assert.Equal("System.Int32", twoInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int64", twoInfo.ConvertedType.ToTestDisplayString()); } [Fact] public void TestFailedInference() { var source = @" class C { static void Main() { System.Console.Write((null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,30): error CS0019: Operator '==' cannot be applied to operands of type '<null>' and 'lambda expression' // System.Console.Write((null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })").WithArguments("==", "<null>", "lambda expression").WithLocation(6, 30), // (6,30): error CS0019: Operator '==' cannot be applied to operands of type '<null>' and 'method group' // System.Console.Write((null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })").WithArguments("==", "<null>", "method group").WithLocation(6, 30), // (6,30): error CS0019: Operator '==' cannot be applied to operands of type '<null>' and 'lambda expression' // System.Console.Write((null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })").WithArguments("==", "<null>", "lambda expression").WithLocation(6, 30)); verify(comp, inferDelegate: false); comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,30): error CS0019: Operator '==' cannot be applied to operands of type '<null>' and 'lambda expression' // System.Console.Write((null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })").WithArguments("==", "<null>", "lambda expression").WithLocation(6, 30)); verify(comp, inferDelegate: true); static void verify(CSharpCompilation comp, bool inferDelegate) { var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); // check tuple on the left var tuple1 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal("(null, null, null, null)", tuple1.ToString()); var tupleType1 = model.GetTypeInfo(tuple1); Assert.Null(tupleType1.Type); Assert.Null(tupleType1.ConvertedType); // check tuple on the right ... var tuple2 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal("(null, x => x, Main, (int i) => { int j = 0; return i + j; })", tuple2.ToString()); var tupleType2 = model.GetTypeInfo(tuple2); Assert.Null(tupleType2.Type); Assert.Null(tupleType2.ConvertedType); // ... its first lambda ... var firstLambda = tuple2.Arguments[1].Expression; Assert.Null(model.GetTypeInfo(firstLambda).Type); verifyType("System.Delegate", model.GetTypeInfo(firstLambda).ConvertedType, inferDelegate: false); // cannot infer delegate type for x => x // ... its method group ... var methodGroup = tuple2.Arguments[2].Expression; Assert.Null(model.GetTypeInfo(methodGroup).Type); verifyType("System.Delegate", model.GetTypeInfo(methodGroup).ConvertedType, inferDelegate); Assert.Null(model.GetSymbolInfo(methodGroup).Symbol); Assert.Equal(new[] { "void C.Main()" }, model.GetSymbolInfo(methodGroup).CandidateSymbols.Select(s => s.ToTestDisplayString())); // ... its second lambda and the symbols it uses var secondLambda = tuple2.Arguments[3].Expression; verifyType("System.Func<System.Int32, System.Int32>", model.GetTypeInfo(secondLambda).Type, inferDelegate); verifyType("System.Delegate", model.GetTypeInfo(secondLambda).ConvertedType, inferDelegate); var addition = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Last(); Assert.Equal("i + j", addition.ToString()); var i = addition.Left; Assert.Equal("System.Int32 i", model.GetSymbolInfo(i).Symbol.ToTestDisplayString()); var j = addition.Right; Assert.Equal("System.Int32 j", model.GetSymbolInfo(j).Symbol.ToTestDisplayString()); } static void verifyType(string expectedType, ITypeSymbol type, bool inferDelegate) { if (inferDelegate) { Assert.Equal(expectedType, type.ToTestDisplayString()); } else { Assert.Null(type); } } } [Fact] public void TestVoidTypeElement() { var source = @" class C { static void Main() { System.Console.Write((Main(), null) != (null, Main())); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,31): error CS8210: A tuple may not contain a value of type 'void'. // System.Console.Write((Main(), null) != (null, Main())); Diagnostic(ErrorCode.ERR_VoidInTuple, "Main()").WithLocation(6, 31), // (6,55): error CS8210: A tuple may not contain a value of type 'void'. // System.Console.Write((Main(), null) != (null, Main())); Diagnostic(ErrorCode.ERR_VoidInTuple, "Main()").WithLocation(6, 55) ); } [Fact] public void TestFailedConversion() { var source = @" class C { static void M(string s) { System.Console.Write((s, s) == (1, () => { })); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,30): error CS0019: Operator '==' cannot be applied to operands of type 'string' and 'int' // System.Console.Write((s, s) == (1, () => { })); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(s, s) == (1, () => { })").WithArguments("==", "string", "int").WithLocation(6, 30), // (6,30): error CS0019: Operator '==' cannot be applied to operands of type 'string' and 'lambda expression' // System.Console.Write((s, s) == (1, () => { })); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(s, s) == (1, () => { })").WithArguments("==", "string", "lambda expression").WithLocation(6, 30) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var tuple1 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal("(s, s)", tuple1.ToString()); var tupleType1 = model.GetTypeInfo(tuple1); Assert.Equal("(System.String, System.String)", tupleType1.Type.ToTestDisplayString()); Assert.Equal("(System.String, System.String)", tupleType1.ConvertedType.ToTestDisplayString()); var tuple2 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal("(1, () => { })", tuple2.ToString()); var tupleType2 = model.GetTypeInfo(tuple2); Assert.Null(tupleType2.Type); Assert.Null(tupleType2.ConvertedType); } [Fact] public void TestDynamic() { var source = @" public class C { public static void Main() { dynamic d1 = 1; dynamic d2 = 2; System.Console.Write($""{(d1, 2) == (1, d2)} ""); System.Console.Write($""{(d1, 2) != (1, d2)} ""); System.Console.Write($""{(d1, 20) == (10, d2)} ""); System.Console.Write($""{(d1, 20) != (10, d2)} ""); } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True False False True"); } [Fact] public void TestDynamicWithConstants() { var source = @" public class C { public static void Main() { System.Console.Write($""{((dynamic)true, (dynamic)false) == ((dynamic)true, (dynamic)false)} ""); } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); } [Fact] public void TestDynamic_WithTypelessExpression() { var source = @" public class C { public static void Main() { dynamic d1 = 1; dynamic d2 = 2; System.Console.Write((d1, 2) == (() => 1, d2)); } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (8,30): error CS0019: Operator '==' cannot be applied to operands of type 'dynamic' and 'lambda expression' // System.Console.Write((d1, 2) == (() => 1, d2)); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(d1, 2) == (() => 1, d2)").WithArguments("==", "dynamic", "lambda expression").WithLocation(8, 30) ); } [Fact] public void TestDynamic_WithBooleanConstants() { var source = @" public class C { public static void Main() { System.Console.Write(((dynamic)true, (dynamic)false) == (true, false)); System.Console.Write(((dynamic)true, (dynamic)false) != (true, false)); } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueFalse"); } [Fact] public void TestDynamic_WithBadType() { var source = @" public class C { public static void Main() { System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture; dynamic d1 = 1; dynamic d2 = 2; try { bool b = ((d1, 2) == (""hello"", d2)); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { System.Console.Write(e.Message); } finally { System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture; } } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Operator '==' cannot be applied to operands of type 'int' and 'string'"); } [Fact] public void TestDynamic_WithNull() { var source = @" public class C { public static void Main() { dynamic d1 = null; dynamic d2 = null; System.Console.Write((d1, null) == (null, d2)); } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var tuple1 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal("(d1, null)", tuple1.ToString()); var tupleType1 = model.GetTypeInfo(tuple1); Assert.Null(tupleType1.Type); Assert.Equal("(dynamic d1, dynamic)", tupleType1.ConvertedType.ToTestDisplayString()); var tuple2 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal("(null, d2)", tuple2.ToString()); var tupleType2 = model.GetTypeInfo(tuple2); Assert.Null(tupleType2.Type); Assert.Equal("(dynamic, dynamic d2)", tupleType2.ConvertedType.ToTestDisplayString()); } [Fact] public void TestBadConstraintOnTuple() { // https://github.com/dotnet/roslyn/issues/37121 : This test appears to produce a duplicate diagnostic at (6, 35) var source = @" ref struct S { void M(S s1, S s2) { System.Console.Write(("""", s1) == (null, s2)); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,35): error CS0306: The type 'S' may not be used as a type argument // System.Console.Write(("", s1) == (null, s2)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "s1").WithArguments("S").WithLocation(6, 35), // (6,30): error CS0019: Operator '==' cannot be applied to operands of type 'S' and 'S' // System.Console.Write(("", s1) == (null, s2)); Diagnostic(ErrorCode.ERR_BadBinaryOps, @"("""", s1) == (null, s2)").WithArguments("==", "S", "S").WithLocation(6, 30), // (6,35): error CS0306: The type 'S' may not be used as a type argument // System.Console.Write(("", s1) == (null, s2)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "s1").WithArguments("S").WithLocation(6, 35), // (6,49): error CS0306: The type 'S' may not be used as a type argument // System.Console.Write(("", s1) == (null, s2)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "s2").WithArguments("S").WithLocation(6, 49) ); } [Fact] public void TestErrorInTuple() { var source = @" public class C { public void M() { if (error1 == (error2, 3)) { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,13): error CS0103: The name 'error1' does not exist in the current context // if (error1 == (error2, 3)) { } Diagnostic(ErrorCode.ERR_NameNotInContext, "error1").WithArguments("error1").WithLocation(6, 13), // (6,24): error CS0103: The name 'error2' does not exist in the current context // if (error1 == (error2, 3)) { } Diagnostic(ErrorCode.ERR_NameNotInContext, "error2").WithArguments("error2").WithLocation(6, 24) ); } [Fact] public void TestWithTypelessTuple() { var source = @" public class C { public void M() { var t = (null, null); if (null == (() => {}) ) {} if ("""" == 1) {} } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,13): error CS0815: Cannot assign (<null>, <null>) to an implicitly-typed variable // var t = (null, null); Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "t = (null, null)").WithArguments("(<null>, <null>)").WithLocation(6, 13), // (7,13): error CS0019: Operator '==' cannot be applied to operands of type '<null>' and 'lambda expression' // if (null == (() => {}) ) {} Diagnostic(ErrorCode.ERR_BadBinaryOps, "null == (() => {})").WithArguments("==", "<null>", "lambda expression").WithLocation(7, 13), // (8,13): error CS0019: Operator '==' cannot be applied to operands of type 'string' and 'int' // if ("" == 1) {} Diagnostic(ErrorCode.ERR_BadBinaryOps, @""""" == 1").WithArguments("==", "string", "int").WithLocation(8, 13) ); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,13): error CS0815: Cannot assign (<null>, <null>) to an implicitly-typed variable // var t = (null, null); Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "t = (null, null)").WithArguments("(<null>, <null>)").WithLocation(6, 13), // (8,13): error CS0019: Operator '==' cannot be applied to operands of type 'string' and 'int' // if ("" == 1) {} Diagnostic(ErrorCode.ERR_BadBinaryOps, @""""" == 1").WithArguments("==", "string", "int").WithLocation(8, 13) ); } [Fact] public void TestTupleEqualityPreferredOverCustomOperator() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public static bool operator ==(ValueTuple<T1, T2> t1, ValueTuple<T1, T2> t2) => throw null; public static bool operator !=(ValueTuple<T1, T2> t1, ValueTuple<T1, T2> t2) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } } public class C { public static void Main() { var t1 = (1, 1); var t2 = (2, 2); System.Console.Write(t1 == t2); System.Console.Write(t1 != t2); } } "; var comp = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); // Note: tuple equality picked ahead of custom operator== (small compat break) CompileAndVerify(comp, expectedOutput: "FalseTrue"); } [Fact] public void TestCustomOperatorPlusAllowed() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public static ValueTuple<T1, T2> operator +(ValueTuple<T1, T2> t1, ValueTuple<T1, T2> t2) => (default(T1), default(T2)); public override string ToString() => $""({Item1}, {Item2})""; } } public class C { public static void Main() { var t1 = (0, 1); var t2 = (2, 3); System.Console.Write(t1 + t2); } } "; var comp = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "(0, 0)"); } [Fact] void TestTupleEqualityPreferredOverCustomOperator_Nested() { string source = @" public class C { public static void Main() { System.Console.Write( (1, 2, (3, 4)) == (1, 2, (3, 4)) ); } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public static bool operator ==(ValueTuple<T1, T2> t1, ValueTuple<T1, T2> t2) => throw null; public static bool operator !=(ValueTuple<T1, T2> t1, ValueTuple<T1, T2> t2) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public struct ValueTuple<T1, T2, T3> { public T1 Item1; public T2 Item2; public T3 Item3; public ValueTuple(T1 item1, T2 item2, T3 item3) { this.Item1 = item1; this.Item2 = item2; this.Item3 = item3; } } } "; var comp = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); // Note: tuple equality picked ahead of custom operator== CompileAndVerify(comp, expectedOutput: "True"); } [Fact] public void TestNaN() { var source = @" public class C { public static void Main() { var t1 = (System.Double.NaN, 1); var t2 = (System.Double.NaN, 1); System.Console.Write($""{t1 == t2} {t1.Equals(t2)} {t1 != t2} {t1 == (System.Double.NaN, 1)}""); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "False True True False"); } [Fact] public void TestTopLevelDynamic() { var source = @" public class C { public static void Main() { System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture; dynamic d1 = (1, 1); try { try { _ = d1 == (1, 1); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { System.Console.WriteLine(e.Message); } try { _ = d1 != (1, 2); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { System.Console.WriteLine(e.Message); } } finally { System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture; } } } "; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"Operator '==' cannot be applied to operands of type 'System.ValueTuple<int,int>' and 'System.ValueTuple<int,int>' Operator '!=' cannot be applied to operands of type 'System.ValueTuple<int,int>' and 'System.ValueTuple<int,int>'"); } [Fact] public void TestNestedDynamic() { var source = @" public class C { public static void Main() { System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture; dynamic d1 = (1, 1, 1); try { try { _ = (2, d1) == (2, (1, 1, 1)); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { System.Console.WriteLine(e.Message); } try { _ = (3, d1) != (3, (1, 2, 3)); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { System.Console.WriteLine(e.Message); } } finally { System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture; } } } "; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"Operator '==' cannot be applied to operands of type 'System.ValueTuple<int,int,int>' and 'System.ValueTuple<int,int,int>' Operator '!=' cannot be applied to operands of type 'System.ValueTuple<int,int,int>' and 'System.ValueTuple<int,int,int>'"); } [Fact] public void TestComparisonWithDeconstructionResult() { var source = @" public class C { public static void Main() { var b1 = (1, 2) == ((_, _) = new C()); var b2 = (1, 42) != ((_, _) = new C()); var b3 = (1, 42) == ((_, _) = new C()); // false var b4 = ((_, _) = new C()) == (1, 2); var b5 = ((_, _) = new C()) != (1, 42); var b6 = ((_, _) = new C()) == (1, 42); // false System.Console.Write($""{b1} {b2} {b3} {b4} {b5} {b6}""); } public void Deconstruct(out int x, out int y) { x = 1; y = 2; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"True True False True True False"); } [Fact] public void TestComparisonWithDeconstruction() { var source = @" public class C { public static void Main() { var b1 = (1, 2) == new C(); } public void Deconstruct(out int x, out int y) { x = 1; y = 2; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): error CS0019: Operator '==' cannot be applied to operands of type '(int, int)' and 'C' // var b1 = (1, 2) == new C(); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(1, 2) == new C()").WithArguments("==", "(int, int)", "C").WithLocation(6, 18) ); } [Fact] public void TestEvaluationOrderOnTupleLiteral() { var source = @" public class C { public static void Main() { System.Console.Write($""{EXPRESSION}""); } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; throw null; } } } public class Base { public int I; public Base(int i) { I = i; } } public class A : Base { public A(int i) : base(i) { System.Console.Write($""A:{i}, ""); } public static bool operator ==(A a, Y y) { System.Console.Write($""A({a.I}) == Y({y.I}), ""); return a.I == y.I; } public static bool operator !=(A a, Y y) { System.Console.Write($""A({a.I}) != Y({y.I}), ""); return a.I != y.I; } public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) { System.Console.Write($""X:{i}, ""); } } public class Y : Base { public Y(int i) : base(i) { System.Console.Write($""Y:{i}, ""); } public static implicit operator Y(X x) { System.Console.Write(""X -> ""); return new Y(x.I); } } "; validate("(new A(1), new A(2)) == (new X(1), new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A(1) == Y(1), A(2) == Y(2), True"); validate("(new A(1), new A(2)) == (new X(30), new Y(40))", "A:1, A:2, X:30, Y:40, X -> Y:30, A(1) == Y(30), False"); validate("(new A(1), new A(2)) == (new X(1), new Y(50))", "A:1, A:2, X:1, Y:50, X -> Y:1, A(1) == Y(1), A(2) == Y(50), False"); validate("(new A(1), new A(2)) != (new X(1), new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A(1) != Y(1), A(2) != Y(2), False"); validate("(new A(1), new A(2)) != (new Y(1), new X(2))", "A:1, A:2, Y:1, X:2, A(1) != Y(1), X -> Y:2, A(2) != Y(2), False"); validate("(new A(1), new A(2)) != (new X(30), new Y(40))", "A:1, A:2, X:30, Y:40, X -> Y:30, A(1) != Y(30), True"); validate("(new A(1), new A(2)) != (new X(50), new Y(2))", "A:1, A:2, X:50, Y:2, X -> Y:50, A(1) != Y(50), True"); validate("(new A(1), new A(2)) != (new X(1), new Y(60))", "A:1, A:2, X:1, Y:60, X -> Y:1, A(1) != Y(1), A(2) != Y(60), True"); void validate(string expression, string expected) { var comp = CreateCompilation(source.Replace("EXPRESSION", expression), options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: expected); } } [Fact] public void TestEvaluationOrderOnTupleType() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { System.Console.Write(""ValueTuple2, ""); this.Item1 = item1; this.Item2 = item2; } } public struct ValueTuple<T1, T2, T3> { public ValueTuple(T1 item1, T2 item2, T3 item3) { // ValueTuple'3 required (constructed in bound tree), but not emitted throw null; } } } public class Base { public int I; public Base(int i) { I = i; } } public class A : Base { public A(int i) : base(i) { System.Console.Write($""A:{i}, ""); } public static bool operator ==(A a, Y y) { System.Console.Write($""A({a.I}) == Y({y.I}), ""); return true; } public static bool operator !=(A a, Y y) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) { System.Console.Write($""X:{i}, ""); } } public class Y : Base { public Y(int i) : base(i) { System.Console.Write($""Y:{i}, ""); } public static implicit operator Y(X x) { System.Console.Write(""X -> ""); return new Y(x.I); } } public class C { public static void Main() { System.Console.Write($""{(new A(1), GetTuple(), new A(4)) == (new X(5), (new X(6), new Y(7)), new Y(8))}""); } public static (A, A) GetTuple() { System.Console.Write($""GetTuple, ""); return (new A(30), new A(40)); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "A:1, GetTuple, A:30, A:40, ValueTuple2, A:4, X:5, X:6, Y:7, Y:8, X -> Y:5, A(1) == Y(5), X -> Y:6, A(30) == Y(6), A(40) == Y(7), A(4) == Y(8), True"); } [Fact] public void TestConstrainedValueTuple() { var source = @" class C { void M() { _ = (this, this) == (0, 1); // constraint violated by tuple in source _ = (this, this) == (this, this); // constraint violated by converted tuple } public static bool operator ==(C c, int i) => throw null; public static bool operator !=(C c, int i) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; public static implicit operator int(C c) => throw null; } namespace System { public struct ValueTuple<T1, T2> where T1 : class where T2 : class { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; throw null; } } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,30): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T1' in the generic type or method '(T1, T2)' // _ = (this, this) == (0, 1); // constraint violated by tuple in source Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "0").WithArguments("(T1, T2)", "T1", "int").WithLocation(6, 30), // (6,30): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T1' in the generic type or method '(T1, T2)' // _ = (this, this) == (0, 1); // constraint violated by tuple in source Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "0").WithArguments("(T1, T2)", "T1", "int").WithLocation(6, 30), // (6,33): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T2' in the generic type or method '(T1, T2)' // _ = (this, this) == (0, 1); // constraint violated by tuple in source Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "1").WithArguments("(T1, T2)", "T2", "int").WithLocation(6, 33), // (6,33): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T2' in the generic type or method '(T1, T2)' // _ = (this, this) == (0, 1); // constraint violated by tuple in source Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "1").WithArguments("(T1, T2)", "T2", "int").WithLocation(6, 33), // (7,30): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T1' in the generic type or method '(T1, T2)' // _ = (this, this) == (this, this); // constraint violated by converted tuple Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "this").WithArguments("(T1, T2)", "T1", "int").WithLocation(7, 30), // (7,36): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T2' in the generic type or method '(T1, T2)' // _ = (this, this) == (this, this); // constraint violated by converted tuple Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "this").WithArguments("(T1, T2)", "T2", "int").WithLocation(7, 36) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); // check the int tuple var firstEquals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); var intTuple = firstEquals.Right; Assert.Equal("(0, 1)", intTuple.ToString()); var intTupleType = model.GetTypeInfo(intTuple); Assert.Equal("(System.Int32, System.Int32)", intTupleType.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)", intTupleType.ConvertedType.ToTestDisplayString()); // check the last tuple var secondEquals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Last(); var lastTuple = secondEquals.Right; Assert.Equal("(this, this)", lastTuple.ToString()); var lastTupleType = model.GetTypeInfo(lastTuple); Assert.Equal("(C, C)", lastTupleType.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)", lastTupleType.ConvertedType.ToTestDisplayString()); } [Fact] public void TestConstrainedNullable() { var source = @" class C { void M((int, int)? t1, (long, long)? t2) { _ = t1 == t2; } } public interface IInterface { } namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Int32 { } public struct Int64 { } public struct Nullable<T> where T : struct, IInterface { public T GetValueOrDefault() => default(T); } public class Exception { } public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; throw null; } } } "; var comp = CreateEmptyCompilation(source); comp.VerifyDiagnostics( // (4,24): error CS0315: The type '(int, int)' cannot be used as type parameter 'T' in the generic type or method 'Nullable<T>'. There is no boxing conversion from '(int, int)' to 'IInterface'. // void M((int, int)? t1, (long, long)? t2) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "t1").WithArguments("System.Nullable<T>", "IInterface", "T", "(int, int)").WithLocation(4, 24), // (4,42): error CS0315: The type '(long, long)' cannot be used as type parameter 'T' in the generic type or method 'Nullable<T>'. There is no boxing conversion from '(long, long)' to 'IInterface'. // void M((int, int)? t1, (long, long)? t2) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "t2").WithArguments("System.Nullable<T>", "IInterface", "T", "(long, long)").WithLocation(4, 42) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); // check t1 var equals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Last(); var t1 = equals.Left; Assert.Equal("t1", t1.ToString()); var t1Type = model.GetTypeInfo(t1); Assert.Equal("(System.Int32, System.Int32)?", t1Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, System.Int64)?", t1Type.ConvertedType.ToTestDisplayString()); } [Fact] public void TestEvaluationOrderOnTupleType2() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { System.Console.Write(""ValueTuple2, ""); this.Item1 = item1; this.Item2 = item2; } } public struct ValueTuple<T1, T2, T3> { public ValueTuple(T1 item1, T2 item2, T3 item3) { // ValueTuple'3 required (constructed in bound tree), but not emitted throw null; } } } public class Base { public int I; public Base(int i) { I = i; } } public class A : Base { public A(int i) : base(i) { System.Console.Write($""A:{i}, ""); } public static bool operator ==(A a, Y y) { System.Console.Write($""A({a.I}) == Y({y.I}), ""); return true; } public static bool operator !=(A a, Y y) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) { System.Console.Write($""X:{i}, ""); } } public class Y : Base { public Y(int i) : base(i) { System.Console.Write($""Y:{i}, ""); } public static implicit operator Y(X x) { System.Console.Write($""X:{x.I} -> ""); return new Y(x.I); } } public class C { public static void Main() { System.Console.Write($""{(new A(1), (new A(2), new A(3)), new A(4)) == (new X(5), GetTuple(), new Y(8))}""); } public static (X, Y) GetTuple() { System.Console.Write($""GetTuple, ""); return (new X(6), new Y(7)); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"A:1, A:2, A:3, A:4, X:5, GetTuple, X:6, Y:7, ValueTuple2, Y:8, X:5 -> Y:5, A(1) == Y(5), X:6 -> Y:6, A(2) == Y(6), A(3) == Y(7), A(4) == Y(8), True"); } [Fact] public void TestEvaluationOrderOnTupleType3() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { System.Console.Write(""ValueTuple2, ""); this.Item1 = item1; this.Item2 = item2; } } public struct ValueTuple<T1, T2, T3> { public ValueTuple(T1 item1, T2 item2, T3 item3) { // ValueTuple'3 required (constructed in bound tree), but not emitted throw null; } } } public class Base { public int I; public Base(int i) { I = i; } } public class A : Base { public A(int i) : base(i) { System.Console.Write($""A:{i}, ""); } public static bool operator ==(A a, Y y) { System.Console.Write($""A({a.I}) == Y({y.I}), ""); return true; } public static bool operator !=(A a, Y y) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) { System.Console.Write($""X:{i}, ""); } } public class Y : Base { public Y(int i) : base(i) { System.Console.Write($""Y:{i}, ""); } public static implicit operator Y(X x) { System.Console.Write(""X -> ""); return new Y(x.I); } } public class C { public static void Main() { System.Console.Write($""{GetTuple() == (new X(6), new Y(7))}""); } public static (A, A) GetTuple() { System.Console.Write($""GetTuple, ""); return (new A(30), new A(40)); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "GetTuple, A:30, A:40, ValueTuple2, X:6, Y:7, X -> Y:6, A(30) == Y(6), A(40) == Y(7), True"); } [Fact] public void TestObsoleteEqualityOperator() { var source = @" class C { void M() { System.Console.WriteLine($""{(new A(), new A()) == (new X(), new Y())}""); System.Console.WriteLine($""{(new A(), new A()) != (new X(), new Y())}""); } } public class A { [System.Obsolete(""obsolete"", true)] public static bool operator ==(A a, Y y) => throw null; [System.Obsolete(""obsolete too"", true)] public static bool operator !=(A a, Y y) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X { } public class Y { public static implicit operator Y(X x) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,37): error CS0619: 'A.operator ==(A, Y)' is obsolete: 'obsolete' // System.Console.WriteLine($"{(new A(), new A()) == (new X(), new Y())}"); Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "(new A(), new A()) == (new X(), new Y())").WithArguments("A.operator ==(A, Y)", "obsolete").WithLocation(6, 37), // (6,37): error CS0619: 'A.operator ==(A, Y)' is obsolete: 'obsolete' // System.Console.WriteLine($"{(new A(), new A()) == (new X(), new Y())}"); Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "(new A(), new A()) == (new X(), new Y())").WithArguments("A.operator ==(A, Y)", "obsolete").WithLocation(6, 37), // (7,37): error CS0619: 'A.operator !=(A, Y)' is obsolete: 'obsolete too' // System.Console.WriteLine($"{(new A(), new A()) != (new X(), new Y())}"); Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "(new A(), new A()) != (new X(), new Y())").WithArguments("A.operator !=(A, Y)", "obsolete too").WithLocation(7, 37), // (7,37): error CS0619: 'A.operator !=(A, Y)' is obsolete: 'obsolete too' // System.Console.WriteLine($"{(new A(), new A()) != (new X(), new Y())}"); Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "(new A(), new A()) != (new X(), new Y())").WithArguments("A.operator !=(A, Y)", "obsolete too").WithLocation(7, 37) ); } [Fact] public void TestDefiniteAssignment() { var source = @" class C { void M() { int error1; System.Console.Write((1, 2) == (error1, 2)); int error2; System.Console.Write((1, (error2, 3)) == (1, (2, 3))); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,41): error CS0165: Use of unassigned local variable 'error1' // System.Console.Write((1, 2) == (error1, 2)); Diagnostic(ErrorCode.ERR_UseDefViolation, "error1").WithArguments("error1").WithLocation(7, 41), // (10,35): error CS0165: Use of unassigned local variable 'error2' // System.Console.Write((1, (error2, 3)) == (1, (2, 3))); Diagnostic(ErrorCode.ERR_UseDefViolation, "error2").WithArguments("error2").WithLocation(10, 35) ); } [Fact] public void TestDefiniteAssignment2() { var source = @" class C { int M(out int x) { _ = (M(out int y), y) == (1, 2); // ok _ = (z, M(out int z)) == (1, 2); // error x = 1; return 2; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,14): error CS0841: Cannot use local variable 'z' before it is declared // _ = (z, M(out int z)) == (1, 2); // error Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "z").WithArguments("z").WithLocation(7, 14) ); } [Fact] public void TestEqualityOfTypeConvertingToTuple() { var source = @" class C { private int i; void M() { System.Console.Write(this == (1, 1)); System.Console.Write((1, 1) == this); } public static implicit operator (int, int)(C c) { return (c.i, c.i); } C(int i) { this.i = i; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,30): error CS0019: Operator '==' cannot be applied to operands of type 'C' and '(int, int)' // System.Console.Write(this == (1, 1)); Diagnostic(ErrorCode.ERR_BadBinaryOps, "this == (1, 1)").WithArguments("==", "C", "(int, int)").WithLocation(7, 30), // (8,30): error CS0019: Operator '==' cannot be applied to operands of type '(int, int)' and 'C' // System.Console.Write((1, 1) == this); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(1, 1) == this").WithArguments("==", "(int, int)", "C").WithLocation(8, 30) ); } [Fact] public void TestEqualityOfTypeConvertingFromTuple() { var source = @" class C { private int i; public static void Main() { var c = new C(2); System.Console.Write(c == (1, 1)); System.Console.Write((1, 1) == c); } public static implicit operator C((int, int) x) { return new C(x.Item1 + x.Item2); } public static bool operator ==(C c1, C c2) => c1.i == c2.i; public static bool operator !=(C c1, C c2) => throw null; public override int GetHashCode() => throw null; public override bool Equals(object other) => throw null; C(int i) { this.i = i; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueTrue"); } [Fact] public void TestEqualityOfTypeComparableWithTuple() { var source = @" class C { private static void Main() { System.Console.Write(new C() == (1, 1)); System.Console.Write(new C() != (1, 1)); } public static bool operator ==(C c, (int, int) t) { return t.Item1 + t.Item2 == 2; } public static bool operator !=(C c, (int, int) t) { return t.Item1 + t.Item2 != 2; } public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueFalse"); } [Fact] public void TestOfTwoUnrelatedTypes() { var source = @" class A { } class C { static void M() { System.Console.Write(new C() == new A()); System.Console.Write((1, new C()) == (1, new A())); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,30): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'A' // System.Console.Write(new C() == new A()); Diagnostic(ErrorCode.ERR_BadBinaryOps, "new C() == new A()").WithArguments("==", "C", "A").WithLocation(7, 30), // (8,30): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'A' // System.Console.Write((1, new C()) == (1, new A())); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(1, new C()) == (1, new A())").WithArguments("==", "C", "A").WithLocation(8, 30) ); } [Fact] public void TestOfTwoUnrelatedTypes2() { var source = @" class A { } class C { static void M(string s, System.Exception e) { System.Console.Write(s == 3); System.Console.Write((1, s) == (1, e)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,30): error CS0019: Operator '==' cannot be applied to operands of type 'string' and 'int' // System.Console.Write(s == 3); Diagnostic(ErrorCode.ERR_BadBinaryOps, "s == 3").WithArguments("==", "string", "int").WithLocation(7, 30), // (8,30): error CS0019: Operator '==' cannot be applied to operands of type 'string' and 'Exception' // System.Console.Write((1, s) == (1, e)); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(1, s) == (1, e)").WithArguments("==", "string", "System.Exception").WithLocation(8, 30) ); } [Fact] public void TestBadRefCompare() { var source = @" class C { static void M() { string s = ""11""; object o = s + s; (object, object) t = default; bool b = o == s; bool b2 = t == (s, s); // no warning } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,18): warning CS0252: Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string' // bool b = o == s; Diagnostic(ErrorCode.WRN_BadRefCompareLeft, "o == s").WithArguments("string").WithLocation(10, 18) ); } [Fact, WorkItem(27047, "https://github.com/dotnet/roslyn/issues/27047")] public void TestWithObsoleteImplicitConversion() { var source = @" class C { private static bool TupleEquals((C, int)? nt1, (int, C) nt2) => nt1 == nt2; // warn 1 and 2 private static bool TupleNotEquals((C, int)? nt1, (int, C) nt2) => nt1 != nt2; // warn 3 and 4 [System.Obsolete(""obsolete"", error: true)] public static implicit operator int(C c) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,12): error CS0619: 'C.implicit operator int(C)' is obsolete: 'obsolete' // => nt1 == nt2; // warn 1 and 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "nt1").WithArguments("C.implicit operator int(C)", "obsolete").WithLocation(5, 12), // (5,19): error CS0619: 'C.implicit operator int(C)' is obsolete: 'obsolete' // => nt1 == nt2; // warn 1 and 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "nt2").WithArguments("C.implicit operator int(C)", "obsolete").WithLocation(5, 19), // (8,12): error CS0619: 'C.implicit operator int(C)' is obsolete: 'obsolete' // => nt1 != nt2; // warn 3 and 4 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "nt1").WithArguments("C.implicit operator int(C)", "obsolete").WithLocation(8, 12), // (8,19): error CS0619: 'C.implicit operator int(C)' is obsolete: 'obsolete' // => nt1 != nt2; // warn 3 and 4 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "nt2").WithArguments("C.implicit operator int(C)", "obsolete").WithLocation(8, 19) ); } [Fact, WorkItem(27047, "https://github.com/dotnet/roslyn/issues/27047")] public void TestWithObsoleteBoolConversion() { var source = @" public class A { public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 public static NotBool operator ==(A a1, A a2) => throw null; public static NotBool operator !=(A a1, A a2) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class NotBool { [System.Obsolete(""obsolete"", error: true)] public static implicit operator bool(NotBool b) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,49): error CS0619: 'NotBool.implicit operator bool(NotBool)' is obsolete: 'obsolete' // public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t == t").WithArguments("NotBool.implicit operator bool(NotBool)", "obsolete").WithLocation(4, 49), // (4,49): error CS0619: 'NotBool.implicit operator bool(NotBool)' is obsolete: 'obsolete' // public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t == t").WithArguments("NotBool.implicit operator bool(NotBool)", "obsolete").WithLocation(4, 49), // (5,52): error CS0619: 'NotBool.implicit operator bool(NotBool)' is obsolete: 'obsolete' // public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t != t").WithArguments("NotBool.implicit operator bool(NotBool)", "obsolete").WithLocation(5, 52), // (5,52): error CS0619: 'NotBool.implicit operator bool(NotBool)' is obsolete: 'obsolete' // public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t != t").WithArguments("NotBool.implicit operator bool(NotBool)", "obsolete").WithLocation(5, 52) ); } [Fact, WorkItem(27047, "https://github.com/dotnet/roslyn/issues/27047")] public void TestWithObsoleteComparisonOperators() { var source = @" public class A { public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 [System.Obsolete("""", error: true)] public static bool operator ==(A a1, A a2) => throw null; [System.Obsolete("""", error: true)] public static bool operator !=(A a1, A a2) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,49): error CS0619: 'A.operator ==(A, A)' is obsolete: '' // public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t == t").WithArguments("A.operator ==(A, A)", "").WithLocation(4, 49), // (4,49): error CS0619: 'A.operator ==(A, A)' is obsolete: '' // public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t == t").WithArguments("A.operator ==(A, A)", "").WithLocation(4, 49), // (5,52): error CS0619: 'A.operator !=(A, A)' is obsolete: '' // public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t != t").WithArguments("A.operator !=(A, A)", "").WithLocation(5, 52), // (5,52): error CS0619: 'A.operator !=(A, A)' is obsolete: '' // public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t != t").WithArguments("A.operator !=(A, A)", "").WithLocation(5, 52) ); } [Fact, WorkItem(27047, "https://github.com/dotnet/roslyn/issues/27047")] public void TestWithObsoleteTruthOperators() { var source = @" public class A { public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 public static NotBool operator ==(A a1, A a2) => throw null; public static NotBool operator !=(A a1, A a2) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class NotBool { [System.Obsolete(""obsolete"", error: true)] public static bool operator true(NotBool b) => throw null; [System.Obsolete(""obsolete"", error: true)] public static bool operator false(NotBool b) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,49): error CS0619: 'NotBool.operator false(NotBool)' is obsolete: 'obsolete' // public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t == t").WithArguments("NotBool.operator false(NotBool)", "obsolete").WithLocation(4, 49), // (4,49): error CS0619: 'NotBool.operator false(NotBool)' is obsolete: 'obsolete' // public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t == t").WithArguments("NotBool.operator false(NotBool)", "obsolete").WithLocation(4, 49), // (5,52): error CS0619: 'NotBool.operator true(NotBool)' is obsolete: 'obsolete' // public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t != t").WithArguments("NotBool.operator true(NotBool)", "obsolete").WithLocation(5, 52), // (5,52): error CS0619: 'NotBool.operator true(NotBool)' is obsolete: 'obsolete' // public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t != t").WithArguments("NotBool.operator true(NotBool)", "obsolete").WithLocation(5, 52) ); } [Fact] public void TestEqualOnNullableVsNullableTuples() { var source = @" class C { public static void Main() { Compare(null, null); Compare(null, (1, 2)); Compare((2, 3), null); Compare((4, 4), (4, 4)); Compare((5, 5), (10, 10)); } private static void Compare((int, int)? nt1, (int, int)? nt2) { System.Console.Write($""{nt1 == nt2} ""); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "True False False True False"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var comparison = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); var nt1 = comparison.Left; var nt1Type = model.GetTypeInfo(nt1); Assert.Equal("nt1", nt1.ToString()); Assert.Equal("(System.Int32, System.Int32)?", nt1Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", nt1Type.ConvertedType.ToTestDisplayString()); var nt2 = comparison.Right; var nt2Type = model.GetTypeInfo(nt2); Assert.Equal("nt2", nt2.ToString()); Assert.Equal("(System.Int32, System.Int32)?", nt2Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", nt2Type.ConvertedType.ToTestDisplayString()); verifier.VerifyIL("C.Compare", @"{ // Code size 104 (0x68) .maxstack 3 .locals init (System.ValueTuple<int, int>? V_0, System.ValueTuple<int, int>? V_1, bool V_2, System.ValueTuple<int, int> V_3, System.ValueTuple<int, int> V_4) IL_0000: nop IL_0001: ldstr ""{0} "" IL_0006: ldarg.0 IL_0007: stloc.0 IL_0008: ldarg.1 IL_0009: stloc.1 IL_000a: ldloca.s V_0 IL_000c: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldloca.s V_1 IL_0015: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_001a: beq.s IL_001f IL_001c: ldc.i4.0 IL_001d: br.s IL_0057 IL_001f: ldloc.2 IL_0020: brtrue.s IL_0025 IL_0022: ldc.i4.1 IL_0023: br.s IL_0057 IL_0025: ldloca.s V_0 IL_0027: call ""System.ValueTuple<int, int> System.ValueTuple<int, int>?.GetValueOrDefault()"" IL_002c: stloc.3 IL_002d: ldloca.s V_1 IL_002f: call ""System.ValueTuple<int, int> System.ValueTuple<int, int>?.GetValueOrDefault()"" IL_0034: stloc.s V_4 IL_0036: ldloc.3 IL_0037: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_003c: ldloc.s V_4 IL_003e: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0043: bne.un.s IL_0056 IL_0045: ldloc.3 IL_0046: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_004b: ldloc.s V_4 IL_004d: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0052: ceq IL_0054: br.s IL_0057 IL_0056: ldc.i4.0 IL_0057: box ""bool"" IL_005c: call ""string string.Format(string, object)"" IL_0061: call ""void System.Console.Write(string)"" IL_0066: nop IL_0067: ret }"); } [Fact] public void TestEqualOnNullableVsNullableTuples_NeverNull() { var source = @" class C { public static void Main() { System.Console.Write(((int, int)?) (1, 2) == ((int, int)?) (1, 2)); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "True"); verifier.VerifyIL("C.Main", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.1 IL_0003: bne.un.s IL_000b IL_0005: ldc.i4.2 IL_0006: ldc.i4.2 IL_0007: ceq IL_0009: br.s IL_000c IL_000b: ldc.i4.0 IL_000c: call ""void System.Console.Write(bool)"" IL_0011: nop IL_0012: ret } "); } [Fact] public void TestEqualOnNullableVsNullableTuples_OneSideNeverNull() { var source = @" class C { public static void Main() { System.Console.Write(((int, int)?) (1, 2) == (1, 2)); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "True"); verifier.VerifyIL("C.Main", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.1 IL_0003: bne.un.s IL_000b IL_0005: ldc.i4.2 IL_0006: ldc.i4.2 IL_0007: ceq IL_0009: br.s IL_000c IL_000b: ldc.i4.0 IL_000c: call ""void System.Console.Write(bool)"" IL_0011: nop IL_0012: ret } "); } [Fact] public void TestEqualOnNullableVsNullableTuples_Tuple_AlwaysNull_AlwaysNull() { var source = @" class C { public static void Main() { System.Console.Write(((int, int)?)null == ((int, int)?)null); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "True"); verifier.VerifyIL("C.Main", @"{ // Code size 9 (0x9) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: call ""void System.Console.Write(bool)"" IL_0007: nop IL_0008: ret } "); CompileAndVerify(source, options: TestOptions.ReleaseExe).VerifyIL("C.Main", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: call ""void System.Console.Write(bool)"" IL_0006: ret } "); } [Fact] public void TestEqualOnNullableVsNullableTuples_Tuple_MaybeNull_AlwaysNull() { var source = @" class C { public static void Main() { M(null); M((1, 2)); } public static void M((int, int)? t) { System.Console.Write(t == ((int, int)?)null); } } "; CompileAndVerify(source, expectedOutput: "TrueFalse", options: TestOptions.ReleaseExe).VerifyIL("C.M", @"{ // Code size 18 (0x12) .maxstack 2 .locals init (System.ValueTuple<int, int>? V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_0009: ldc.i4.0 IL_000a: ceq IL_000c: call ""void System.Console.Write(bool)"" IL_0011: ret } "); } [Fact] public void TestNotEqualOnNullableVsNullableTuples_Tuple_MaybeNull_AlwaysNull() { var source = @" class C { public static void Main() { M(null); M((1, 2)); } public static void M((int, int)? t) { System.Console.Write(t != ((int, int)?)null); } } "; CompileAndVerify(source, expectedOutput: "FalseTrue", options: TestOptions.ReleaseExe).VerifyIL("C.M", @"{ // Code size 15 (0xf) .maxstack 1 .locals init (System.ValueTuple<int, int>? V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_0009: call ""void System.Console.Write(bool)"" IL_000e: ret } "); } [Fact] public void TestNotEqualOnNullableVsNullableTuples_Tuple_AlwaysNull_MaybeNull() { var source = @" class C { public static void Main() { M(null); M((1, 2)); } public static void M((int, int)? t) { System.Console.Write(((int, int)?)null == t); } } "; CompileAndVerify(source, expectedOutput: "TrueFalse", options: TestOptions.ReleaseExe).VerifyIL("C.M", @"{ // Code size 18 (0x12) .maxstack 2 .locals init (System.ValueTuple<int, int>? V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_0009: ldc.i4.0 IL_000a: ceq IL_000c: call ""void System.Console.Write(bool)"" IL_0011: ret } "); } [Fact] public void TestEqualOnNullableVsNullableTuples_Tuple_NeverNull_AlwaysNull() { var source = @" class C { public static void Main() { System.Console.Write((1, 2) == ((int, int)?)null); } } "; CompileAndVerify(source, expectedOutput: "False", options: TestOptions.ReleaseExe).VerifyIL("C.Main", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: call ""void System.Console.Write(bool)"" IL_0006: ret } "); } [Fact] public void TestEqualOnNullableVsNullableTuples_Tuple_AlwaysNull_MaybeNull() { var source = @" class C { public static void Main() { M(null); M((1, 2)); } public static void M((int, int)? t) { System.Console.Write(((int, int)?)null == t); } } "; CompileAndVerify(source, expectedOutput: "TrueFalse", options: TestOptions.ReleaseExe).VerifyIL("C.M", @"{ // Code size 18 (0x12) .maxstack 2 .locals init (System.ValueTuple<int, int>? V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_0009: ldc.i4.0 IL_000a: ceq IL_000c: call ""void System.Console.Write(bool)"" IL_0011: ret } "); } [Fact] public void TestEqualOnNullableVsNullableTuples_Tuple_AlwaysNull_NeverNull() { var source = @" class C { public static void Main() { System.Console.Write(((int, int)?)null == (1, 2)); } } "; CompileAndVerify(source, expectedOutput: "False", options: TestOptions.ReleaseExe).VerifyIL("C.Main", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: call ""void System.Console.Write(bool)"" IL_0006: ret } "); } [Fact] public void TestEqualOnNullableVsNullableTuples_ElementAlwaysNull() { var source = @" class C { public static void Main() { System.Console.Write((null, null) == (new int?(), new int?())); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "True"); verifier.VerifyIL("C.Main", @"{ // Code size 9 (0x9) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: call ""void System.Console.Write(bool)"" IL_0007: nop IL_0008: ret } "); } [Fact] public void TestNotEqualOnNullableVsNullableTuples() { var source = @" class C { public static void Main() { Compare(null, null); Compare(null, (1, 2)); Compare((2, 3), null); Compare((4, 4), (4, 4)); Compare((5, 5), (10, 10)); } private static void Compare((int, int)? nt1, (int, int)? nt2) { System.Console.Write($""{nt1 != nt2} ""); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "False True True False True"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var comparison = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); var nt1 = comparison.Left; var nt1Type = model.GetTypeInfo(nt1); Assert.Equal("nt1", nt1.ToString()); Assert.Equal("(System.Int32, System.Int32)?", nt1Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", nt1Type.ConvertedType.ToTestDisplayString()); var nt2 = comparison.Right; var nt2Type = model.GetTypeInfo(nt2); Assert.Equal("nt2", nt2.ToString()); Assert.Equal("(System.Int32, System.Int32)?", nt2Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", nt2Type.ConvertedType.ToTestDisplayString()); verifier.VerifyIL("C.Compare", @"{ // Code size 107 (0x6b) .maxstack 3 .locals init (System.ValueTuple<int, int>? V_0, System.ValueTuple<int, int>? V_1, bool V_2, System.ValueTuple<int, int> V_3, System.ValueTuple<int, int> V_4) IL_0000: nop IL_0001: ldstr ""{0} "" IL_0006: ldarg.0 IL_0007: stloc.0 IL_0008: ldarg.1 IL_0009: stloc.1 IL_000a: ldloca.s V_0 IL_000c: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldloca.s V_1 IL_0015: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_001a: beq.s IL_001f IL_001c: ldc.i4.1 IL_001d: br.s IL_005a IL_001f: ldloc.2 IL_0020: brtrue.s IL_0025 IL_0022: ldc.i4.0 IL_0023: br.s IL_005a IL_0025: ldloca.s V_0 IL_0027: call ""System.ValueTuple<int, int> System.ValueTuple<int, int>?.GetValueOrDefault()"" IL_002c: stloc.3 IL_002d: ldloca.s V_1 IL_002f: call ""System.ValueTuple<int, int> System.ValueTuple<int, int>?.GetValueOrDefault()"" IL_0034: stloc.s V_4 IL_0036: ldloc.3 IL_0037: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_003c: ldloc.s V_4 IL_003e: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0043: bne.un.s IL_0059 IL_0045: ldloc.3 IL_0046: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_004b: ldloc.s V_4 IL_004d: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0052: ceq IL_0054: ldc.i4.0 IL_0055: ceq IL_0057: br.s IL_005a IL_0059: ldc.i4.1 IL_005a: box ""bool"" IL_005f: call ""string string.Format(string, object)"" IL_0064: call ""void System.Console.Write(string)"" IL_0069: nop IL_006a: ret }"); } [Fact] public void TestNotEqualOnNullableVsNullableNestedTuples() { var source = @" class C { public static void Main() { Compare((1, null), (1, null), true); Compare(null, (1, (2, 3)), false); Compare((1, (2, 3)), (1, null), false); Compare((1, (4, 4)), (1, (4, 4)), true); Compare((1, (5, 5)), (1, (10, 10)), false); System.Console.Write(""Success""); } private static void Compare((int, (int, int)?)? nt1, (int, (int, int)?)? nt2, bool expectMatch) { if (expectMatch != (nt1 == nt2) || expectMatch == (nt1 != nt2)) { throw null; } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Success"); } [Fact] public void TestEqualOnNullableVsNullableTuples_WithImplicitConversion() { var source = @" class C { public static void Main() { Compare(null, null); Compare(null, (1, 2)); Compare((2, 3), null); Compare((4, 4), (4, 4)); Compare((5, 5), (10, 10)); } private static void Compare((int, int)? nt1, (byte, long)? nt2) { System.Console.Write($""{nt1 == nt2} ""); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "True False False True False"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var comparison = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); var nt1 = comparison.Left; var nt1Type = model.GetTypeInfo(nt1); Assert.Equal("nt1", nt1.ToString()); Assert.Equal("(System.Int32, System.Int32)?", nt1Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int64)?", nt1Type.ConvertedType.ToTestDisplayString()); var nt2 = comparison.Right; var nt2Type = model.GetTypeInfo(nt2); Assert.Equal("nt2", nt2.ToString()); Assert.Equal("(System.Byte, System.Int64)?", nt2Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int64)?", nt2Type.ConvertedType.ToTestDisplayString()); verifier.VerifyIL("C.Compare", @"{ // Code size 105 (0x69) .maxstack 3 .locals init (System.ValueTuple<int, int>? V_0, System.ValueTuple<byte, long>? V_1, bool V_2, System.ValueTuple<int, int> V_3, System.ValueTuple<byte, long> V_4) IL_0000: nop IL_0001: ldstr ""{0} "" IL_0006: ldarg.0 IL_0007: stloc.0 IL_0008: ldarg.1 IL_0009: stloc.1 IL_000a: ldloca.s V_0 IL_000c: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldloca.s V_1 IL_0015: call ""bool System.ValueTuple<byte, long>?.HasValue.get"" IL_001a: beq.s IL_001f IL_001c: ldc.i4.0 IL_001d: br.s IL_0058 IL_001f: ldloc.2 IL_0020: brtrue.s IL_0025 IL_0022: ldc.i4.1 IL_0023: br.s IL_0058 IL_0025: ldloca.s V_0 IL_0027: call ""System.ValueTuple<int, int> System.ValueTuple<int, int>?.GetValueOrDefault()"" IL_002c: stloc.3 IL_002d: ldloca.s V_1 IL_002f: call ""System.ValueTuple<byte, long> System.ValueTuple<byte, long>?.GetValueOrDefault()"" IL_0034: stloc.s V_4 IL_0036: ldloc.3 IL_0037: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_003c: ldloc.s V_4 IL_003e: ldfld ""byte System.ValueTuple<byte, long>.Item1"" IL_0043: bne.un.s IL_0057 IL_0045: ldloc.3 IL_0046: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_004b: conv.i8 IL_004c: ldloc.s V_4 IL_004e: ldfld ""long System.ValueTuple<byte, long>.Item2"" IL_0053: ceq IL_0055: br.s IL_0058 IL_0057: ldc.i4.0 IL_0058: box ""bool"" IL_005d: call ""string string.Format(string, object)"" IL_0062: call ""void System.Console.Write(string)"" IL_0067: nop IL_0068: ret }"); } [Fact] public void TestOnNullableVsNullableTuples_WithImplicitCustomConversion() { var source = @" class C { int _value; public C(int v) { _value = v; } public static void Main() { Compare(null, null); Compare(null, (1, new C(20))); Compare((new C(30), 3), null); Compare((new C(4), 4), (4, new C(4))); Compare((new C(5), 5), (10, new C(10))); Compare((new C(6), 6), (6, new C(20))); } private static void Compare((C, int)? nt1, (int, C)? nt2) { System.Console.Write($""{nt1 == nt2} ""); } public static implicit operator int(C c) { System.Console.Write($""Convert{c._value} ""); return c._value; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "True False False Convert4 Convert4 True Convert5 False Convert6 Convert20 False "); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var comparison = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); var nt1 = comparison.Left; var nt1Type = model.GetTypeInfo(nt1); Assert.Equal("nt1", nt1.ToString()); Assert.Equal("(C, System.Int32)?", nt1Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", nt1Type.ConvertedType.ToTestDisplayString()); var nt2 = comparison.Right; var nt2Type = model.GetTypeInfo(nt2); Assert.Equal("nt2", nt2.ToString()); Assert.Equal("(System.Int32, C)?", nt2Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", nt2Type.ConvertedType.ToTestDisplayString()); verifier.VerifyIL("C.Compare", @"{ // Code size 114 (0x72) .maxstack 3 .locals init (System.ValueTuple<C, int>? V_0, System.ValueTuple<int, C>? V_1, bool V_2, System.ValueTuple<C, int> V_3, System.ValueTuple<int, C> V_4) IL_0000: nop IL_0001: ldstr ""{0} "" IL_0006: ldarg.0 IL_0007: stloc.0 IL_0008: ldarg.1 IL_0009: stloc.1 IL_000a: ldloca.s V_0 IL_000c: call ""bool System.ValueTuple<C, int>?.HasValue.get"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldloca.s V_1 IL_0015: call ""bool System.ValueTuple<int, C>?.HasValue.get"" IL_001a: beq.s IL_001f IL_001c: ldc.i4.0 IL_001d: br.s IL_0061 IL_001f: ldloc.2 IL_0020: brtrue.s IL_0025 IL_0022: ldc.i4.1 IL_0023: br.s IL_0061 IL_0025: ldloca.s V_0 IL_0027: call ""System.ValueTuple<C, int> System.ValueTuple<C, int>?.GetValueOrDefault()"" IL_002c: stloc.3 IL_002d: ldloca.s V_1 IL_002f: call ""System.ValueTuple<int, C> System.ValueTuple<int, C>?.GetValueOrDefault()"" IL_0034: stloc.s V_4 IL_0036: ldloc.3 IL_0037: ldfld ""C System.ValueTuple<C, int>.Item1"" IL_003c: call ""int C.op_Implicit(C)"" IL_0041: ldloc.s V_4 IL_0043: ldfld ""int System.ValueTuple<int, C>.Item1"" IL_0048: bne.un.s IL_0060 IL_004a: ldloc.3 IL_004b: ldfld ""int System.ValueTuple<C, int>.Item2"" IL_0050: ldloc.s V_4 IL_0052: ldfld ""C System.ValueTuple<int, C>.Item2"" IL_0057: call ""int C.op_Implicit(C)"" IL_005c: ceq IL_005e: br.s IL_0061 IL_0060: ldc.i4.0 IL_0061: box ""bool"" IL_0066: call ""string string.Format(string, object)"" IL_006b: call ""void System.Console.Write(string)"" IL_0070: nop IL_0071: ret }"); } [Fact] public void TestOnNullableVsNonNullableTuples() { var source = @" class C { public static void Main() { M(null); M((1, 2)); M((10, 20)); } private static void M((byte, int)? nt) { System.Console.Write((1, 2) == nt); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "FalseTrueFalse"); verifier.VerifyIL("C.M", @"{ // Code size 53 (0x35) .maxstack 2 .locals init (System.ValueTuple<byte, int>? V_0, System.ValueTuple<byte, int> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""bool System.ValueTuple<byte, int>?.HasValue.get"" IL_000a: brtrue.s IL_000f IL_000c: ldc.i4.0 IL_000d: br.s IL_002e IL_000f: br.s IL_0011 IL_0011: ldloca.s V_0 IL_0013: call ""System.ValueTuple<byte, int> System.ValueTuple<byte, int>?.GetValueOrDefault()"" IL_0018: stloc.1 IL_0019: ldc.i4.1 IL_001a: ldloc.1 IL_001b: ldfld ""byte System.ValueTuple<byte, int>.Item1"" IL_0020: bne.un.s IL_002d IL_0022: ldc.i4.2 IL_0023: ldloc.1 IL_0024: ldfld ""int System.ValueTuple<byte, int>.Item2"" IL_0029: ceq IL_002b: br.s IL_002e IL_002d: ldc.i4.0 IL_002e: call ""void System.Console.Write(bool)"" IL_0033: nop IL_0034: ret }"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var comparison = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); var tuple = comparison.Left; var tupleType = model.GetTypeInfo(tuple); Assert.Equal("(1, 2)", tuple.ToString()); Assert.Equal("(System.Int32, System.Int32)", tupleType.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", tupleType.ConvertedType.ToTestDisplayString()); var nt = comparison.Right; var ntType = model.GetTypeInfo(nt); Assert.Equal("nt", nt.ToString()); Assert.Equal("(System.Byte, System.Int32)?", ntType.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", ntType.ConvertedType.ToTestDisplayString()); } [Fact] public void TestOnNullableVsNonNullableTuples_WithCustomConversion() { var source = @" class C { int _value; public C(int v) { _value = v; } public static void Main() { M(null); M((new C(1), 2)); M((new C(10), 20)); } private static void M((C, int)? nt) { System.Console.Write($""{(1, 2) == nt} ""); System.Console.Write($""{nt == (1, 2)} ""); } public static implicit operator int(C c) { System.Console.Write($""Convert{c._value} ""); return c._value; } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "False False Convert1 True Convert1 True Convert10 False Convert10 False"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var comparison = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); Assert.Equal("(1, 2) == nt", comparison.ToString()); var tuple = comparison.Left; var tupleType = model.GetTypeInfo(tuple); Assert.Equal("(1, 2)", tuple.ToString()); Assert.Equal("(System.Int32, System.Int32)", tupleType.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", tupleType.ConvertedType.ToTestDisplayString()); var nt = comparison.Right; var ntType = model.GetTypeInfo(nt); Assert.Equal("nt", nt.ToString()); Assert.Equal("(C, System.Int32)?", ntType.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", ntType.ConvertedType.ToTestDisplayString()); } [Fact] public void TestOnNullableVsNonNullableTuples3() { var source = @" class C { public static void Main() { M(null); M((1, 2)); M((10, 20)); } private static void M((int, int)? nt) { System.Console.Write(nt == (1, 2)); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "FalseTrueFalse"); verifier.VerifyIL("C.M", @"{ // Code size 59 (0x3b) .maxstack 2 .locals init (System.ValueTuple<int, int>? V_0, bool V_1, System.ValueTuple<int, int> V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_000a: stloc.1 IL_000b: ldloc.1 IL_000c: brtrue.s IL_0011 IL_000e: ldc.i4.0 IL_000f: br.s IL_0034 IL_0011: ldloc.1 IL_0012: brtrue.s IL_0017 IL_0014: ldc.i4.1 IL_0015: br.s IL_0034 IL_0017: ldloca.s V_0 IL_0019: call ""System.ValueTuple<int, int> System.ValueTuple<int, int>?.GetValueOrDefault()"" IL_001e: stloc.2 IL_001f: ldloc.2 IL_0020: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0025: ldc.i4.1 IL_0026: bne.un.s IL_0033 IL_0028: ldloc.2 IL_0029: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_002e: ldc.i4.2 IL_002f: ceq IL_0031: br.s IL_0034 IL_0033: ldc.i4.0 IL_0034: call ""void System.Console.Write(bool)"" IL_0039: nop IL_003a: ret }"); } [Fact] public void TestOnNullableVsLiteralTuples() { var source = @" class C { public static void Main() { CheckNull(null); CheckNull((1, 2)); } private static void CheckNull((int, int)? nt) { System.Console.Write($""{nt == null} ""); System.Console.Write($""{nt != null} ""); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True False False True"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var lastNull = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Last(); Assert.Equal("null", lastNull.ToString()); var nullType = model.GetTypeInfo(lastNull); Assert.Null(nullType.Type); Assert.Null(nullType.ConvertedType); // In nullable-null comparison, the null literal remains typeless } [Fact] public void TestOnLongTuple() { var source = @" class C { public static void Main() { Assert(MakeLongTuple(1) == MakeLongTuple(1)); Assert(!(MakeLongTuple(1) != MakeLongTuple(1))); Assert(MakeLongTuple(1) == (1, 1, 1, 1, 1, 1, 1, 1, 1)); Assert(!(MakeLongTuple(1) != (1, 1, 1, 1, 1, 1, 1, 1, 1))); Assert(MakeLongTuple(1) == MakeLongTuple(1, 1)); Assert(!(MakeLongTuple(1) != MakeLongTuple(1, 1))); Assert(!(MakeLongTuple(1) == MakeLongTuple(1, 2))); Assert(!(MakeLongTuple(1) == MakeLongTuple(2, 1))); Assert(MakeLongTuple(1) != MakeLongTuple(1, 2)); Assert(MakeLongTuple(1) != MakeLongTuple(2, 1)); System.Console.Write(""Success""); } private static (int, int, int, int, int, int, int, int, int) MakeLongTuple(int x) => (x, x, x, x, x, x, x, x, x); private static (int?, int, int?, int, int?, int, int?, int, int?)? MakeLongTuple(int? x, int y) => (x, y, x, y, x, y, x, y, x); private static void Assert(bool test) { if (!test) { throw null; } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Success"); } [Fact] public void TestOn1Tuple_FromRest() { var source = @" class C { public static bool M() { var x1 = MakeLongTuple(1).Rest; bool b1 = x1 == x1; bool b2 = x1 != x1; return b1 && b2; } private static (int, int, int, int, int, int, int, int?) MakeLongTuple(int? x) => throw null; public bool Unused((int, int, int, int, int, int, int, int?) t) { return t.Rest == t.Rest; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,19): error CS0019: Operator '==' cannot be applied to operands of type 'ValueTuple<int?>' and 'ValueTuple<int?>' // bool b1 = x1 == x1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x1 == x1").WithArguments("==", "System.ValueTuple<int?>", "System.ValueTuple<int?>").WithLocation(8, 19), // (9,19): error CS0019: Operator '!=' cannot be applied to operands of type 'ValueTuple<int?>' and 'ValueTuple<int?>' // bool b2 = x1 != x1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x1 != x1").WithArguments("!=", "System.ValueTuple<int?>", "System.ValueTuple<int?>").WithLocation(9, 19), // (18,16): error CS0019: Operator '==' cannot be applied to operands of type 'ValueTuple<int?>' and 'ValueTuple<int?>' // return t.Rest == t.Rest; Diagnostic(ErrorCode.ERR_BadBinaryOps, "t.Rest == t.Rest").WithArguments("==", "System.ValueTuple<int?>", "System.ValueTuple<int?>").WithLocation(18, 16) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var comparison = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Last(); Assert.Equal("t.Rest == t.Rest", comparison.ToString()); var left = model.GetTypeInfo(comparison.Left); Assert.Equal("System.ValueTuple<System.Int32?>", left.Type.ToTestDisplayString()); Assert.Equal("System.ValueTuple<System.Int32?>", left.ConvertedType.ToTestDisplayString()); Assert.True(left.Type.IsTupleType); } [Fact] public void TestOn1Tuple_FromValueTuple() { var source = @" using System; class C { public static bool M() { var x1 = ValueTuple.Create((int?)1); bool b1 = x1 == x1; bool b2 = x1 != x1; return b1 && b2; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,19): error CS0019: Operator '==' cannot be applied to operands of type 'ValueTuple<int?>' and 'ValueTuple<int?>' // bool b1 = x1 == x1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x1 == x1").WithArguments("==", "System.ValueTuple<int?>", "System.ValueTuple<int?>").WithLocation(9, 19), // (10,19): error CS0019: Operator '!=' cannot be applied to operands of type 'ValueTuple<int?>' and 'ValueTuple<int?>' // bool b2 = x1 != x1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x1 != x1").WithArguments("!=", "System.ValueTuple<int?>", "System.ValueTuple<int?>").WithLocation(10, 19) ); } [Fact] public void TestOnTupleOfDecimals() { var source = @" class C { public static void Main() { System.Console.Write(Compare((1, 2), (1, 2))); System.Console.Write(Compare((1, 2), (10, 20))); } public static bool Compare((decimal, decimal) t1, (decimal, decimal) t2) { return t1 == t2; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "TrueFalse"); verifier.VerifyIL("C.Compare", @"{ // Code size 49 (0x31) .maxstack 2 .locals init (System.ValueTuple<decimal, decimal> V_0, System.ValueTuple<decimal, decimal> V_1, bool V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.1 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""decimal System.ValueTuple<decimal, decimal>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""decimal System.ValueTuple<decimal, decimal>.Item1"" IL_0011: call ""bool decimal.op_Equality(decimal, decimal)"" IL_0016: brfalse.s IL_002b IL_0018: ldloc.0 IL_0019: ldfld ""decimal System.ValueTuple<decimal, decimal>.Item2"" IL_001e: ldloc.1 IL_001f: ldfld ""decimal System.ValueTuple<decimal, decimal>.Item2"" IL_0024: call ""bool decimal.op_Equality(decimal, decimal)"" IL_0029: br.s IL_002c IL_002b: ldc.i4.0 IL_002c: stloc.2 IL_002d: br.s IL_002f IL_002f: ldloc.2 IL_0030: ret }"); } [Fact] public void TestSideEffectsAreSavedToTemps() { var source = @" class C { public static void Main() { int i = 0; System.Console.Write((i++, i++, i++) == (0, 1, 2)); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "True"); } [Fact] public void TestNonBoolComparisonResult_WithTrueFalseOperators() { var source = @" using static System.Console; public class C { public static void Main() { Write($""{REPLACE}""); } } public class Base { public int I; public Base(int i) { I = i; } } public class A : Base { public A(int i) : base(i) { Write($""A:{i}, ""); } public static NotBool operator ==(A a, Y y) { Write(""A == Y, ""); return new NotBool(a.I == y.I); } public static NotBool operator !=(A a, Y y) { Write(""A != Y, ""); return new NotBool(a.I != y.I); } public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) { Write($""X:{i}, ""); } } public class Y : Base { public Y(int i) : base(i) { Write($""Y:{i}, ""); } public static implicit operator Y(X x) { Write(""X -> ""); return new Y(x.I); } } public class NotBool { public bool B; public NotBool(bool value) { B = value; } public static bool operator true(NotBool b) { Write($""NotBool.true -> {b.B}, ""); return b.B; } public static bool operator false(NotBool b) { Write($""NotBool.false -> {!b.B}, ""); return !b.B; } } "; validate("(new A(1), new A(2)) == (new X(1), new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A == Y, NotBool.false -> False, A == Y, NotBool.false -> False, True"); validate("(new A(1), new A(2)) == (new X(1), new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A == Y, NotBool.false -> False, A == Y, NotBool.false -> True, False"); validate("(new A(1), new A(2)) != (new X(1), new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A != Y, NotBool.true -> False, A != Y, NotBool.true -> False, False"); validate("(new A(1), new A(2)) != (new X(1), new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A != Y, NotBool.true -> False, A != Y, NotBool.true -> True, True"); validate("((dynamic)new A(1), new A(2)) == (new X(1), (dynamic)new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A == Y, NotBool.false -> False, A == Y, NotBool.false -> False, True"); validate("((dynamic)new A(1), new A(2)) == (new X(1), (dynamic)new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A == Y, NotBool.false -> False, A == Y, NotBool.false -> True, False"); validate("((dynamic)new A(1), new A(2)) != (new X(1), (dynamic)new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A != Y, NotBool.true -> False, A != Y, NotBool.true -> False, False"); validate("((dynamic)new A(1), new A(2)) != (new X(1), (dynamic)new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A != Y, NotBool.true -> False, A != Y, NotBool.true -> True, True"); void validate(string expression, string expected) { var comp = CreateCompilation(source.Replace("REPLACE", expression), targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: expected); } } [Fact] public void TestNonBoolComparisonResult_WithTrueFalseOperatorsOnBase() { var source = @" using static System.Console; public class C { public static void Main() { Write($""{REPLACE}""); } } public class Base { public int I; public Base(int i) { I = i; } } public class A : Base { public A(int i) : base(i) { Write($""A:{i}, ""); } public static NotBool operator ==(A a, Y y) { Write(""A == Y, ""); return new NotBool(a.I == y.I); } public static NotBool operator !=(A a, Y y) { Write(""A != Y, ""); return new NotBool(a.I != y.I); } public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) { Write($""X:{i}, ""); } } public class Y : Base { public Y(int i) : base(i) { Write($""Y:{i}, ""); } public static implicit operator Y(X x) { Write(""X -> ""); return new Y(x.I); } } public class NotBoolBase { public bool B; public NotBoolBase(bool value) { B = value; } public static bool operator true(NotBoolBase b) { Write($""NotBoolBase.true -> {b.B}, ""); return b.B; } public static bool operator false(NotBoolBase b) { Write($""NotBoolBase.false -> {!b.B}, ""); return !b.B; } } public class NotBool : NotBoolBase { public NotBool(bool value) : base(value) { } } "; // This tests the case where the custom operators false/true need an input conversion that's not just an identity conversion (in this case, it's an implicit reference conversion) validate("(new A(1), new A(2)) == (new X(1), new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A == Y, NotBoolBase.false -> False, A == Y, NotBoolBase.false -> False, True"); validate("(new A(1), new A(2)) == (new X(1), new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A == Y, NotBoolBase.false -> False, A == Y, NotBoolBase.false -> True, False"); validate("(new A(1), new A(2)) != (new X(1), new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A != Y, NotBoolBase.true -> False, A != Y, NotBoolBase.true -> False, False"); validate("(new A(1), new A(2)) != (new X(1), new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A != Y, NotBoolBase.true -> False, A != Y, NotBoolBase.true -> True, True"); validate("((dynamic)new A(1), new A(2)) == (new X(1), (dynamic)new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A == Y, NotBoolBase.false -> False, A == Y, NotBoolBase.false -> False, True"); validate("((dynamic)new A(1), new A(2)) == (new X(1), (dynamic)new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A == Y, NotBoolBase.false -> False, A == Y, NotBoolBase.false -> True, False"); validate("((dynamic)new A(1), new A(2)) != (new X(1), (dynamic)new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A != Y, NotBoolBase.true -> False, A != Y, NotBoolBase.true -> False, False"); validate("((dynamic)new A(1), new A(2)) != (new X(1), (dynamic)new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A != Y, NotBoolBase.true -> False, A != Y, NotBoolBase.true -> True, True"); void validate(string expression, string expected) { var comp = CreateCompilation(source.Replace("REPLACE", expression), targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: expected); } } [Fact] public void TestNonBoolComparisonResult_WithImplicitBoolConversion() { var source = @" using static System.Console; public class C { public static void Main() { Write($""{REPLACE}""); } } public class Base { public int I; public Base(int i) { I = i; } } public class A : Base { public A(int i) : base(i) { Write($""A:{i}, ""); } public static NotBool operator ==(A a, Y y) { Write(""A == Y, ""); return new NotBool(a.I == y.I); } public static NotBool operator !=(A a, Y y) { Write(""A != Y, ""); return new NotBool(a.I != y.I); } public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) { Write($""X:{i}, ""); } } public class Y : Base { public Y(int i) : base(i) { Write($""Y:{i}, ""); } public static implicit operator Y(X x) { Write(""X -> ""); return new Y(x.I); } } public class NotBool { public bool B; public NotBool(bool value) { B = value; } public static implicit operator bool(NotBool b) { Write($""NotBool -> bool:{b.B}, ""); return b.B; } } "; validate("(new A(1), new A(2)) == (new X(1), new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A == Y, NotBool -> bool:True, A == Y, NotBool -> bool:True, True"); validate("(new A(1), new A(2)) == (new X(10), new Y(2))", "A:1, A:2, X:10, Y:2, X -> Y:10, A == Y, NotBool -> bool:False, False"); validate("(new A(1), new A(2)) == (new X(1), new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A == Y, NotBool -> bool:True, A == Y, NotBool -> bool:False, False"); validate("(new A(1), new A(2)) != (new X(1), new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A != Y, NotBool -> bool:False, A != Y, NotBool -> bool:False, False"); validate("(new A(1), new A(2)) != (new X(10), new Y(2))", "A:1, A:2, X:10, Y:2, X -> Y:10, A != Y, NotBool -> bool:True, True"); validate("(new A(1), new A(2)) != (new X(1), new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A != Y, NotBool -> bool:False, A != Y, NotBool -> bool:True, True"); void validate(string expression, string expected) { var comp = CreateCompilation(source.Replace("REPLACE", expression), options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: expected); } } [Fact] public void TestNonBoolComparisonResult_WithoutImplicitBoolConversion() { var source = @" using static System.Console; public class C { public static void Main() { Write($""{REPLACE}""); } } public class Base { public Base(int i) { } } public class A : Base { public A(int i) : base(i) => throw null; public static NotBool operator ==(A a, Y y) => throw null; public static NotBool operator !=(A a, Y y) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) => throw null; } public class Y : Base { public Y(int i) : base(i) => throw null; public static implicit operator Y(X x) => throw null; } public class NotBool { } "; validate("(new A(1), new A(2)) == (new X(1), new Y(2))", // (7,18): error CS0029: Cannot implicitly convert type 'NotBool' to 'bool' // Write($"{(new A(1), new A(2)) == (new X(1), new Y(2))}"); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(new A(1), new A(2)) == (new X(1), new Y(2))").WithArguments("NotBool", "bool").WithLocation(7, 18), // (7,18): error CS0029: Cannot implicitly convert type 'NotBool' to 'bool' // Write($"{(new A(1), new A(2)) == (new X(1), new Y(2))}"); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(new A(1), new A(2)) == (new X(1), new Y(2))").WithArguments("NotBool", "bool").WithLocation(7, 18) ); validate("(new A(1), 2) != (new X(1), 2)", // (7,18): error CS0029: Cannot implicitly convert type 'NotBool' to 'bool' // Write($"{(new A(1), 2) != (new X(1), 2)}"); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(new A(1), 2) != (new X(1), 2)").WithArguments("NotBool", "bool").WithLocation(7, 18) ); void validate(string expression, params DiagnosticDescription[] expected) { var comp = CreateCompilation(source.Replace("REPLACE", expression)); comp.VerifyDiagnostics(expected); } } [Fact] public void TestNonBoolComparisonResult_WithExplicitBoolConversion() { var source = @" using static System.Console; public class C { public static void Main() { Write($""{(new A(1), new A(2)) == (new X(1), new Y(2))}""); } } public class Base { public int I; public Base(int i) { I = i; } } public class A : Base { public A(int i) : base(i) => throw null; public static NotBool operator ==(A a, Y y) => throw null; public static NotBool operator !=(A a, Y y) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) => throw null; } public class Y : Base { public Y(int i) : base(i) => throw null; public static implicit operator Y(X x) => throw null; } public class NotBool { public NotBool(bool value) => throw null; public static explicit operator bool(NotBool b) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,18): error CS0029: Cannot implicitly convert type 'NotBool' to 'bool' // Write($"{(new A(1), new A(2)) == (new X(1), new Y(2))}"); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(new A(1), new A(2)) == (new X(1), new Y(2))").WithArguments("NotBool", "bool").WithLocation(7, 18), // (7,18): error CS0029: Cannot implicitly convert type 'NotBool' to 'bool' // Write($"{(new A(1), new A(2)) == (new X(1), new Y(2))}"); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(new A(1), new A(2)) == (new X(1), new Y(2))").WithArguments("NotBool", "bool").WithLocation(7, 18) ); } [Fact] public void TestNullableBoolComparisonResult_WithTrueFalseOperators() { var source = @" public class C { public static void M(A a) { _ = (a, a) == (a, a); if (a == a) { } } } public class A { public A(int i) => throw null; public static bool? operator ==(A a1, A a2) => throw null; public static bool? operator !=(A a1, A a2) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,13): error CS0029: Cannot implicitly convert type 'bool?' to 'bool' // _ = (a, a) == (a, a); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(a, a) == (a, a)").WithArguments("bool?", "bool").WithLocation(6, 13), // (6,13): error CS0029: Cannot implicitly convert type 'bool?' to 'bool' // _ = (a, a) == (a, a); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(a, a) == (a, a)").WithArguments("bool?", "bool").WithLocation(6, 13), // (7,13): error CS0266: Cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?) // if (a == a) { } Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "a == a").WithArguments("bool?", "bool").WithLocation(7, 13), // (7,13): warning CS1718: Comparison made to same variable; did you mean to compare something else? // if (a == a) { } Diagnostic(ErrorCode.WRN_ComparisonToSelf, "a == a").WithLocation(7, 13) ); } [Fact] public void TestElementNames() { var source = @" #pragma warning disable CS0219 using static System.Console; public class C { public static void Main() { int a = 1; int b = 2; int c = 3; int d = 4; int x = 5; int y = 6; (int x, int y) t1 = (1, 2); (int, int) t2 = (1, 2); Write($""{REPLACE}""); } } "; // tuple expression vs tuple expression validate("t1 == t2"); // tuple expression vs tuple literal validate("t1 == (x: 1, y: 2)"); validate("t1 == (1, 2)"); validate("(1, 2) == t1"); validate("(x: 1, d) == t1"); validate("t2 == (x: 1, y: 2)", // (16,25): warning CS8375: The tuple element name 'x' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{t2 == (x: 1, y: 2)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "x: 1").WithArguments("x").WithLocation(16, 25), // (16,31): warning CS8375: The tuple element name 'y' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{t2 == (x: 1, y: 2)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "y: 2").WithArguments("y").WithLocation(16, 31) ); // tuple literal vs tuple literal // - warnings reported on the right when both sides could complain // - no warnings on inferred names validate("((a, b), c: 3) == ((1, x: 2), 3)", // (16,27): warning CS8375: The tuple element name 'c' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{((a, b), c: 3) == ((1, x: 2), 3)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "c: 3").WithArguments("c").WithLocation(16, 27), // (16,41): warning CS8375: The tuple element name 'x' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{((a, b), c: 3) == ((1, x: 2), 3)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "x: 2").WithArguments("x").WithLocation(16, 41) ); validate("(a, b) == (a: 1, b: 2)"); validate("(a, b) == (c: 1, d)", // (16,29): warning CS8375: The tuple element name 'c' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{(a, b) == (c: 1, d)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "c: 1").WithArguments("c").WithLocation(16, 29) ); validate("(a: 1, b: 2) == (c: 1, d)", // (16,35): warning CS8375: The tuple element name 'c' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{(a: 1, b: 2) == (c: 1, d)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "c: 1").WithArguments("c").WithLocation(16, 35), // (16,25): warning CS8375: The tuple element name 'b' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{(a: 1, b: 2) == (c: 1, d)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "b: 2").WithArguments("b").WithLocation(16, 25) ); validate("(null, b) == (c: null, d: 2)", // (16,32): warning CS8375: The tuple element name 'c' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{(null, b) == (c: null, d: 2)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "c: null").WithArguments("c").WithLocation(16, 32), // (16,41): warning CS8375: The tuple element name 'd' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{(null, b) == (c: null, d: 2)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "d: 2").WithArguments("d").WithLocation(16, 41) ); void validate(string expression, params DiagnosticDescription[] diagnostics) { var comp = CreateCompilation(source.Replace("REPLACE", expression)); comp.VerifyDiagnostics(diagnostics); } } [Fact] void TestValueTupleWithObsoleteEqualityOperator() { string source = @" public class C { public static void Main() { System.Console.Write((1, 2) == (3, 4)); } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } [System.Obsolete] public static bool operator==(ValueTuple<T1, T2> t1, ValueTuple<T1, T2> t2) => throw null; public static bool operator!=(ValueTuple<T1, T2> t1, ValueTuple<T1, T2> t2) => throw null; public override bool Equals(object other) => throw null; public override int GetHashCode() => throw null; } } "; var comp = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); // Note: tuple equality picked ahead of custom operator== CompileAndVerify(comp, expectedOutput: "False"); } [Fact] public void TestInExpressionTree() { var source = @" using System; using System.Linq.Expressions; public class C { public static void Main() { Expression<Func<int, bool>> expr = i => (i, i) == (i, i); Expression<Func<(int, int), bool>> expr2 = t => t != t; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,49): error CS8374: An expression tree may not contain a tuple == or != operator // Expression<Func<int, bool>> expr = i => (i, i) == (i, i); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleBinOp, "(i, i) == (i, i)").WithLocation(8, 49), // (8,49): error CS8143: An expression tree may not contain a tuple literal. // Expression<Func<int, bool>> expr = i => (i, i) == (i, i); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, "(i, i)").WithLocation(8, 49), // (8,59): error CS8143: An expression tree may not contain a tuple literal. // Expression<Func<int, bool>> expr = i => (i, i) == (i, i); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, "(i, i)").WithLocation(8, 59), // (9,57): error CS8374: An expression tree may not contain a tuple == or != operator // Expression<Func<(int, int), bool>> expr2 = t => t != t; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleBinOp, "t != t").WithLocation(9, 57) ); } [Fact] public void TestComparisonOfDynamicAndTuple() { var source = @" public class C { (long, string) _t; public C(long l, string s) { _t = (l, s); } public static void Main() { dynamic d = new C(1, ""hello""); (long, string) tuple1 = (1, ""hello""); (long, string) tuple2 = (2, ""world""); System.Console.Write($""{d == tuple1} {d != tuple1} {d == tuple2} {d != tuple2}""); } public static bool operator==(C c, (long, string) t) { return c._t.Item1 == t.Item1 && c._t.Item2 == t.Item2; } public static bool operator!=(C c, (long, string) t) { return !(c == t); } public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } "; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True False False True"); } [Fact] public void TestComparisonOfDynamicTuple() { var source = @" public class C { public static void Main() { dynamic d1 = (1, ""hello""); dynamic d2 = (1, ""hello""); dynamic d3 = ((byte)1, 2); PrintException(() => d1 == d2); PrintException(() => d1 == d3); } public static void PrintException(System.Func<bool> action) { System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture; try { action(); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { System.Console.WriteLine(e.Message); } finally { System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture; } } } "; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"Operator '==' cannot be applied to operands of type 'System.ValueTuple<int,string>' and 'System.ValueTuple<int,string>' Operator '==' cannot be applied to operands of type 'System.ValueTuple<int,string>' and 'System.ValueTuple<byte,int>'"); } [Fact] public void TestComparisonWithTupleElementNames() { var source = @" public class C { public static void Main() { int Bob = 1; System.Console.Write((Alice: 0, (Bob, 2)) == (Bob: 0, (1, Other: 2))); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (7,55): warning CS8375: The tuple element name 'Bob' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // System.Console.Write((Alice: 0, (Bob, 2)) == (Bob: 0, (1, Other: 2))); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "Bob: 0").WithArguments("Bob").WithLocation(7, 55), // (7,67): warning CS8375: The tuple element name 'Other' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // System.Console.Write((Alice: 0, (Bob, 2)) == (Bob: 0, (1, Other: 2))); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "Other: 2").WithArguments("Other").WithLocation(7, 67) ); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var equals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); // check left tuple var leftTuple = equals.Left; var leftInfo = model.GetTypeInfo(leftTuple); Assert.Equal("(System.Int32 Alice, (System.Int32 Bob, System.Int32))", leftInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int32 Alice, (System.Int32 Bob, System.Int32))", leftInfo.ConvertedType.ToTestDisplayString()); // check right tuple var rightTuple = equals.Right; var rightInfo = model.GetTypeInfo(rightTuple); Assert.Equal("(System.Int32 Bob, (System.Int32, System.Int32 Other))", rightInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int32 Bob, (System.Int32, System.Int32 Other))", rightInfo.ConvertedType.ToTestDisplayString()); } [Fact] public void TestComparisonWithCastedTuples() { var source = @" public class C { public static void Main() { System.Console.Write( ((string, (byte, long))) (null, (1, 2L)) == ((string, (long, byte))) (null, (1L, 2)) ); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var equals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); // check left cast ... var leftCast = (CastExpressionSyntax)equals.Left; Assert.Equal("((string, (byte, long))) (null, (1, 2L))", leftCast.ToString()); var leftCastInfo = model.GetTypeInfo(leftCast); Assert.Equal("(System.String, (System.Byte, System.Int64))", leftCastInfo.Type.ToTestDisplayString()); Assert.Equal("(System.String, (System.Int64, System.Int64))", leftCastInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTuple, model.GetConversion(leftCast).Kind); // ... its tuple ... var leftTuple = (TupleExpressionSyntax)leftCast.Expression; Assert.Equal("(null, (1, 2L))", leftTuple.ToString()); var leftTupleInfo = model.GetTypeInfo(leftTuple); Assert.Null(leftTupleInfo.Type); Assert.Equal("(System.String, (System.Byte, System.Int64))", leftTupleInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ExplicitTupleLiteral, model.GetConversion(leftTuple).Kind); // ... its null ... var leftNull = leftTuple.Arguments[0].Expression; Assert.Equal("null", leftNull.ToString()); var leftNullInfo = model.GetTypeInfo(leftNull); Assert.Null(leftNullInfo.Type); Assert.Equal("System.String", leftNullInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitReference, model.GetConversion(leftNull).Kind); // ... its nested tuple var leftNestedTuple = leftTuple.Arguments[1].Expression; Assert.Equal("(1, 2L)", leftNestedTuple.ToString()); var leftNestedTupleInfo = model.GetTypeInfo(leftNestedTuple); Assert.Equal("(System.Int32, System.Int64)", leftNestedTupleInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Byte, System.Int64)", leftNestedTupleInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, model.GetConversion(leftNestedTuple).Kind); // check right cast ... var rightCast = (CastExpressionSyntax)equals.Right; var rightCastInfo = model.GetTypeInfo(rightCast); Assert.Equal("(System.String, (System.Int64, System.Byte))", rightCastInfo.Type.ToTestDisplayString()); Assert.Equal("(System.String, (System.Int64, System.Int64))", rightCastInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTuple, model.GetConversion(rightCast).Kind); // ... its tuple var rightTuple = rightCast.Expression; var rightTupleInfo = model.GetTypeInfo(rightTuple); Assert.Null(rightTupleInfo.Type); Assert.Equal("(System.String, (System.Int64, System.Byte))", rightTupleInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ExplicitTupleLiteral, model.GetConversion(rightTuple).Kind); } [Fact] public void TestGenericElement() { var source = @" public class C { public void M<T>(T t) { _ = (t, t) == (t, t); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,13): error CS0019: Operator '==' cannot be applied to operands of type 'T' and 'T' // _ = (t, t) == (t, t); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(t, t) == (t, t)").WithArguments("==", "T", "T").WithLocation(6, 13), // (6,13): error CS0019: Operator '==' cannot be applied to operands of type 'T' and 'T' // _ = (t, t) == (t, t); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(t, t) == (t, t)").WithArguments("==", "T", "T").WithLocation(6, 13) ); } [Fact] public void TestNameofEquality() { var source = @" public class C { public void M() { _ = nameof((1, 2) == (3, 4)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,20): error CS8081: Expression does not have a name. // _ = nameof((1, 2) == (3, 4)); Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "(1, 2) == (3, 4)").WithLocation(6, 20) ); } [Fact] public void TestAsRefOrOutArgument() { var source = @" public class C { public void M(ref bool x, out bool y) { x = true; y = true; M(ref (1, 2) == (3, 4), out (1, 2) == (3, 4)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,15): error CS1510: A ref or out value must be an assignable variable // M(ref (1, 2) == (3, 4), out (1, 2) == (3, 4)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "(1, 2) == (3, 4)").WithLocation(8, 15), // (8,37): error CS1510: A ref or out value must be an assignable variable // M(ref (1, 2) == (3, 4), out (1, 2) == (3, 4)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "(1, 2) == (3, 4)").WithLocation(8, 37) ); } [Fact] public void TestWithAnonymousTypes() { var source = @" public class C { public static void Main() { var a = new { A = 1 }; var b = new { B = 2 }; var c = new { A = 1 }; var d = new { B = 2 }; System.Console.Write((a, b) == (a, b)); System.Console.Write((a, b) == (c, d)); System.Console.Write((a, b) != (c, d)); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueFalseTrue"); } [Fact] public void TestWithAnonymousTypes2() { var source = @" public class C { public static void Main() { var a = new { A = 1 }; var b = new { B = 2 }; System.Console.Write((a, b) == (b, a)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,30): error CS0019: Operator '==' cannot be applied to operands of type '<anonymous type: int A>' and '<anonymous type: int B>' // System.Console.Write((a, b) == (b, a)); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(a, b) == (b, a)").WithArguments("==", "<anonymous type: int A>", "<anonymous type: int B>").WithLocation(9, 30), // (9,30): error CS0019: Operator '==' cannot be applied to operands of type '<anonymous type: int B>' and '<anonymous type: int A>' // System.Console.Write((a, b) == (b, a)); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(a, b) == (b, a)").WithArguments("==", "<anonymous type: int B>", "<anonymous type: int A>").WithLocation(9, 30) ); } [Fact] public void TestRefReturningElements() { var source = @" public class C { public static void Main() { System.Console.Write((P, S()) == (1, ""hello"")); } public static int p = 1; public static ref int P => ref p; public static string s = ""hello""; public static ref string S() => ref s; } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); } [Fact] public void TestChecked() { var source = @" public class C { public static void Main() { try { checked { int ten = 10; System.Console.Write((2147483647 + ten, 1) == (0, 1)); } } catch (System.OverflowException) { System.Console.Write(""overflow""); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "overflow"); } [Fact] public void TestUnchecked() { var source = @" public class C { public static void Main() { unchecked { int ten = 10; System.Console.Write((2147483647 + ten, 1) == (-2147483639, 1)); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); } [Fact] public void TestInQuery() { var source = @" using System.Linq; public class C { public static void Main() { var query = from a in new int[] { 1, 2, 2} where (a, 2) == (2, a) select a; foreach (var i in query) { System.Console.Write(i); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "22"); } [Fact] public void TestWithPointer() { var source = @" public class C { public unsafe static void M() { int x = 234; int y = 236; int* p1 = &x; int* p2 = &y; _ = (p1, p2) == (p1, p2); } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (10,14): error CS0306: The type 'int*' may not be used as a type argument // _ = (p1, p2) == (p1, p2); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p1").WithArguments("int*").WithLocation(10, 14), // (10,18): error CS0306: The type 'int*' may not be used as a type argument // _ = (p1, p2) == (p1, p2); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p2").WithArguments("int*").WithLocation(10, 18), // (10,26): error CS0306: The type 'int*' may not be used as a type argument // _ = (p1, p2) == (p1, p2); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p1").WithArguments("int*").WithLocation(10, 26), // (10,30): error CS0306: The type 'int*' may not be used as a type argument // _ = (p1, p2) == (p1, p2); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p2").WithArguments("int*").WithLocation(10, 30), // (10,14): error CS0306: The type 'void*' may not be used as a type argument // _ = (p1, p2) == (p1, p2); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p1").WithArguments("void*").WithLocation(10, 14), // (10,18): error CS0306: The type 'void*' may not be used as a type argument // _ = (p1, p2) == (p1, p2); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p2").WithArguments("void*").WithLocation(10, 18), // (10,26): error CS0306: The type 'void*' may not be used as a type argument // _ = (p1, p2) == (p1, p2); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p1").WithArguments("void*").WithLocation(10, 26), // (10,30): error CS0306: The type 'void*' may not be used as a type argument // _ = (p1, p2) == (p1, p2); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p2").WithArguments("void*").WithLocation(10, 30) ); } [Fact] public void TestOrder01() { var source = @" using System; public class C { public static void Main() { X x = new X(); Y y = new Y(); Console.WriteLine((1, ((int, int))x) == (y, (1, 1))); } } class X { public static implicit operator (short, short)(X x) { Console.WriteLine(""X-> (short, short)""); return (1, 1); } } class Y { public static implicit operator int(Y x) { Console.WriteLine(""Y -> int""); return 1; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"X-> (short, short) Y -> int True"); } [Fact] public void TestOrder02() { var source = @" using System; public class C { public static void Main() { var result = (new B(1), new Nullable<B>(new A(2))) == (new A(3), new B(4)); Console.WriteLine(); Console.WriteLine(result); } } struct A { public readonly int N; public A(int n) { this.N = n; Console.Write($""new A({ n }); ""); } } struct B { public readonly int N; public B(int n) { this.N = n; Console.Write($""new B({n}); ""); } public static implicit operator B(A a) { Console.Write($""A({a.N})->""); return new B(a.N); } public static bool operator ==(B b1, B b2) { Console.Write($""B({b1.N})==B({b2.N}); ""); return b1.N == b2.N; } public static bool operator !=(B b1, B b2) { Console.Write($""B({b1.N})!=B({b2.N}); ""); return b1.N != b2.N; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (22,8): warning CS0660: 'B' defines operator == or operator != but does not override Object.Equals(object o) // struct B Diagnostic(ErrorCode.WRN_EqualityOpWithoutEquals, "B").WithArguments("B").WithLocation(22, 8), // (22,8): warning CS0661: 'B' defines operator == or operator != but does not override Object.GetHashCode() // struct B Diagnostic(ErrorCode.WRN_EqualityOpWithoutGetHashCode, "B").WithArguments("B").WithLocation(22, 8) ); CompileAndVerify(comp, expectedOutput: @"new B(1); new A(2); A(2)->new B(2); new A(3); new B(4); A(3)->new B(3); B(1)==B(3); False "); } [Fact, WorkItem(35958, "https://github.com/dotnet/roslyn/issues/35958")] public void TestMethodGroupConversionInTupleEquality_01() { var source = @" using System; public class C { public static void Main() { Action a = M; Console.WriteLine((a, M) == (M, a)); } static void M() {} }"; var comp = CompileAndVerify(source, expectedOutput: "True"); comp.VerifyDiagnostics(); } [Fact, WorkItem(35958, "https://github.com/dotnet/roslyn/issues/35958")] public void TestMethodGroupConversionInTupleEquality_02() { var source = @" using System; public class C { public static void Main() { Action a = () => {}; Console.WriteLine((a, M) == (M, a)); } static void M() {} }"; var comp = CompileAndVerify(source, expectedOutput: "False"); comp.VerifyDiagnostics(); } [Fact, WorkItem(35958, "https://github.com/dotnet/roslyn/issues/35958")] public void TestMethodGroupConversionInTupleEquality_03() { var source = @" using System; public class C { public static void Main() { K k = null; Console.WriteLine((k, 1) == (M, 1)); } static void M() {} } class K { public static bool operator ==(K k, System.Action a) => true; public static bool operator !=(K k, System.Action a) => false; public override bool Equals(object other) => false; public override int GetHashCode() => 1; } "; var comp = CompileAndVerify(source, expectedOutput: "True"); comp.VerifyDiagnostics(); } [Fact, WorkItem(35958, "https://github.com/dotnet/roslyn/issues/35958")] public void TestInterpolatedStringConversionInTupleEquality_01() { var source = @" using System; public class C { public static void Main() { K k = null; Console.WriteLine((k, 1) == ($""frog"", 1)); } static void M() {} } class K { public static bool operator ==(K k, IFormattable a) => a.ToString() == ""frog""; public static bool operator !=(K k, IFormattable a) => false; public override bool Equals(object other) => false; public override int GetHashCode() => 1; } "; var comp = CompileAndVerify(source, expectedOutput: "True"); comp.VerifyDiagnostics(); } } }
1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Test/Semantic/Semantics/DelegateTypeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class DelegateTypeTests : CSharpTestBase { private const string s_utils = @"using System; using System.Linq; static class Utils { internal static string GetDelegateMethodName(this Delegate d) { var method = d.Method; return Concat(GetTypeName(method.DeclaringType), method.Name); } internal static string GetDelegateTypeName(this Delegate d) { return d.GetType().GetTypeName(); } internal static string GetTypeName(this Type type) { if (type.IsArray) { return GetTypeName(type.GetElementType()) + ""[]""; } string typeName = type.Name; int index = typeName.LastIndexOf('`'); if (index >= 0) { typeName = typeName.Substring(0, index); } typeName = Concat(type.Namespace, typeName); if (!type.IsGenericType) { return typeName; } return $""{typeName}<{string.Join("", "", type.GetGenericArguments().Select(GetTypeName))}>""; } private static string Concat(string container, string name) { return string.IsNullOrEmpty(container) ? name : container + ""."" + name; } }"; [Fact] public void LanguageVersion() { var source = @"class Program { static void Main() { System.Delegate d; d = Main; d = () => { }; d = delegate () { }; System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,13): error CS0428: Cannot convert method group 'Main' to non-delegate type 'Delegate'. Did you intend to invoke the method? // d = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.Delegate").WithLocation(6, 13), // (7,13): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // d = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 13), // (8,13): error CS1660: Cannot convert anonymous method to type 'Delegate' because it is not a delegate type // d = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.Delegate").WithLocation(8, 13), // (9,48): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(9, 48)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(); } [Fact] public void MethodGroupConversions() { var source = @"class Program { static void Main() { object o = Main; System.ICloneable c = Main; System.Delegate d = Main; System.MulticastDelegate m = Main; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,20): error CS0428: Cannot convert method group 'Main' to non-delegate type 'object'. Did you intend to invoke the method? // object o = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "object").WithLocation(5, 20), // (6,31): error CS0428: Cannot convert method group 'Main' to non-delegate type 'ICloneable'. Did you intend to invoke the method? // System.ICloneable c = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.ICloneable").WithLocation(6, 31), // (8,38): error CS0428: Cannot convert method group 'Main' to non-delegate type 'MulticastDelegate'. Did you intend to invoke the method? // System.MulticastDelegate m = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.MulticastDelegate").WithLocation(8, 38)); } [Fact] public void LambdaConversions() { var source = @"class Program { static void Main() { object o = () => { }; System.ICloneable c = () => { }; System.Delegate d = () => { }; System.MulticastDelegate m = () => { }; d = x => x; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,20): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // object o = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "object").WithLocation(5, 20), // (6,31): error CS1660: Cannot convert lambda expression to type 'ICloneable' because it is not a delegate type // System.ICloneable c = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.ICloneable").WithLocation(6, 31), // (8,38): error CS1660: Cannot convert lambda expression to type 'MulticastDelegate' because it is not a delegate type // System.MulticastDelegate m = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.MulticastDelegate").WithLocation(8, 38), // (9,13): error CS8917: The delegate type could not be inferred. // d = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(9, 13)); } private static IEnumerable<object?[]> GetMethodGroupData(Func<string, string, DiagnosticDescription[]> getExpectedDiagnostics) { yield return getData("static int F() => 0;", "Program.F", "F", "System.Func<System.Int32>"); yield return getData("static int F() => 0;", "F", "F", "System.Func<System.Int32>"); yield return getData("int F() => 0;", "(new Program()).F", "F", "System.Func<System.Int32>"); yield return getData("static T F<T>() => default;", "Program.F<int>", "F", "System.Func<System.Int32>"); yield return getData("static void F<T>() where T : class { }", "F<object>", "F", "System.Action"); yield return getData("static void F<T>() where T : struct { }", "F<int>", "F", "System.Action"); yield return getData("T F<T>() => default;", "(new Program()).F<int>", "F", "System.Func<System.Int32>"); yield return getData("T F<T>() => default;", "(new Program()).F", "F", null); yield return getData("void F<T>(T t) { }", "(new Program()).F<string>", "F", "System.Action<System.String>"); yield return getData("void F<T>(T t) { }", "(new Program()).F", "F", null); yield return getData("static ref int F() => throw null;", "F", "F", "<>F{00000001}<System.Int32>"); yield return getData("static ref readonly int F() => throw null;", "F", "F", "<>F{00000003}<System.Int32>"); yield return getData("static void F() { }", "F", "F", "System.Action"); yield return getData("static void F(int x, int y) { }", "F", "F", "System.Action<System.Int32, System.Int32>"); yield return getData("static void F(out int x, int y) { x = 0; }", "F", "F", "<>A{00000002}<System.Int32, System.Int32>"); yield return getData("static void F(int x, ref int y) { }", "F", "F", "<>A{00000004}<System.Int32, System.Int32>"); yield return getData("static void F(int x, in int y) { }", "F", "F", "<>A{0000000c}<System.Int32, System.Int32>"); yield return getData("static void F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { }", "F", "F", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("static void F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { }", "F", "F", "<>A<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("static object F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => null;", "F", "F", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Object>"); yield return getData("static object F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => null;", "F", "F", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); object?[] getData(string methodDeclaration, string methodGroupExpression, string methodGroupOnly, string? expectedType) => new object?[] { methodDeclaration, methodGroupExpression, expectedType is null ? getExpectedDiagnostics(methodGroupExpression, methodGroupOnly) : null, expectedType }; } public static IEnumerable<object?[]> GetMethodGroupImplicitConversionData() { return GetMethodGroupData((methodGroupExpression, methodGroupOnly) => { int offset = methodGroupExpression.Length - methodGroupOnly.Length; return new[] { // (6,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(6, 29 + offset) }; }); } [Theory] [MemberData(nameof(GetMethodGroupImplicitConversionData))] public void MethodGroup_ImplicitConversion(string methodDeclaration, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"class Program {{ {methodDeclaration} static void Main() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(d.GetDelegateTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } public static IEnumerable<object?[]> GetMethodGroupExplicitConversionData() { return GetMethodGroupData((methodGroupExpression, methodGroupOnly) => { int offset = methodGroupExpression.Length - methodGroupOnly.Length; return new[] { // (6,20): error CS0030: Cannot convert type 'method' to 'Delegate' // object o = (System.Delegate)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, $"(System.Delegate){methodGroupExpression}").WithArguments("method", "System.Delegate").WithLocation(6, 20) }; }); } [Theory] [MemberData(nameof(GetMethodGroupExplicitConversionData))] public void MethodGroup_ExplicitConversion(string methodDeclaration, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"class Program {{ {methodDeclaration} static void Main() {{ object o = (System.Delegate){methodGroupExpression}; System.Console.Write(o.GetType().GetTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); // https://github.com/dotnet/roslyn/issues/52874: GetTypeInfo() for method group should return inferred delegate type. Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); } public static IEnumerable<object?[]> GetLambdaData() { yield return getData("x => x", null); yield return getData("x => { return x; }", null); yield return getData("x => ref args[0]", null); yield return getData("(x, y) => { }", null); yield return getData("() => 1", "System.Func<System.Int32>"); yield return getData("() => ref args[0]", "<>F{00000001}<System.String>"); yield return getData("() => { }", "System.Action"); yield return getData("(int x, int y) => { }", "System.Action<System.Int32, System.Int32>"); yield return getData("(out int x, int y) => { x = 0; }", "<>A{00000002}<System.Int32, System.Int32>"); yield return getData("(int x, ref int y) => { x = 0; }", "<>A{00000004}<System.Int32, System.Int32>"); yield return getData("(int x, in int y) => { x = 0; }", "<>A{0000000c}<System.Int32, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => { }", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => { }", "<>A<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => _1", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => _1", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Int32>"); yield return getData("static () => 1", "System.Func<System.Int32>"); yield return getData("async () => { await System.Threading.Tasks.Task.Delay(0); }", "System.Func<System.Threading.Tasks.Task>"); yield return getData("static async () => { await System.Threading.Tasks.Task.Delay(0); return 0; }", "System.Func<System.Threading.Tasks.Task<System.Int32>>"); yield return getData("() => Main", null); yield return getData("(int x) => x switch { _ => null }", null); yield return getData("_ => { }", null); yield return getData("_ => _", null); yield return getData("() => throw null", null); yield return getData("x => throw null", null); yield return getData("(int x) => throw null", null); yield return getData("() => { throw null; }", "System.Action"); yield return getData("(int x) => { throw null; }", "System.Action<System.Int32>"); yield return getData("(string s) => { if (s.Length > 0) return s; return null; }", "System.Func<System.String, System.String>"); yield return getData("(string s) => { if (s.Length > 0) return default; return s; }", "System.Func<System.String, System.String>"); yield return getData("(int i) => { if (i > 0) return i; return default; }", "System.Func<System.Int32, System.Int32>"); yield return getData("(int x, short y) => { if (x > 0) return x; return y; }", "System.Func<System.Int32, System.Int16, System.Int32>"); yield return getData("(int x, short y) => { if (x > 0) return y; return x; }", "System.Func<System.Int32, System.Int16, System.Int32>"); yield return getData("object () => default", "System.Func<System.Object>"); yield return getData("void () => { }", "System.Action"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } public static IEnumerable<object?[]> GetAnonymousMethodData() { yield return getData("delegate { }", null); yield return getData("delegate () { return 1; }", "System.Func<System.Int32>"); yield return getData("delegate () { return ref args[0]; }", "<>F{00000001}<System.String>"); yield return getData("delegate () { }", "System.Action"); yield return getData("delegate (int x, int y) { }", "System.Action<System.Int32, System.Int32>"); yield return getData("delegate (out int x, int y) { x = 0; }", "<>A{00000002}<System.Int32, System.Int32>"); yield return getData("delegate (int x, ref int y) { x = 0; }", "<>A{00000004}<System.Int32, System.Int32>"); yield return getData("delegate (int x, in int y) { x = 0; }", "<>A{0000000c}<System.Int32, System.Int32>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { }", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { }", "<>A<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { return _1; }", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { return _1; }", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Int32>"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } [Theory] [MemberData(nameof(GetLambdaData))] [MemberData(nameof(GetAnonymousMethodData))] public void AnonymousFunction_ImplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ System.Delegate d = {anonymousFunction}; System.Console.Write(d.GetDelegateTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedType is null) { comp.VerifyDiagnostics( // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 29)); } else { CompileAndVerify(comp, expectedOutput: expectedType); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<AnonymousFunctionExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(expr); if (expectedType == null) { Assert.Null(typeInfo.Type); } else { Assert.Equal(expectedType, typeInfo.Type.ToTestDisplayString()); } Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } [Theory] [MemberData(nameof(GetLambdaData))] [MemberData(nameof(GetAnonymousMethodData))] public void AnonymousFunction_ExplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ object o = (System.Delegate)({anonymousFunction}); System.Console.Write(o.GetType().GetTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedType is null) { comp.VerifyDiagnostics( // (5,20): error CS8917: The delegate type could not be inferred. // object o = (System.Delegate)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, $"(System.Delegate)({anonymousFunction})").WithLocation(5, 20)); } else { CompileAndVerify(comp, expectedOutput: expectedType); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(expectedType, typeInfo.ConvertedType?.ToTestDisplayString()); } public static IEnumerable<object?[]> GetExpressionData() { yield return getData("x => x", null); yield return getData("() => 1", "System.Func<System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => _1", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => _1", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Int32>"); yield return getData("static () => 1", "System.Func<System.Int32>"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } [Theory] [MemberData(nameof(GetExpressionData))] public void Expression_ImplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ System.Linq.Expressions.Expression e = {anonymousFunction}; }} }}"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); if (expectedType is null) { comp.VerifyDiagnostics( // (5,48): error CS8917: The delegate type could not be inferred. // System.Linq.Expressions.Expression e = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 48)); } else { comp.VerifyDiagnostics(); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<AnonymousFunctionExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(expr); if (expectedType == null) { Assert.Null(typeInfo.Type); } else { Assert.Equal($"System.Linq.Expressions.Expression<{expectedType}>", typeInfo.Type.ToTestDisplayString()); } Assert.Equal("System.Linq.Expressions.Expression", typeInfo.ConvertedType!.ToTestDisplayString()); } [Theory] [MemberData(nameof(GetExpressionData))] public void Expression_ExplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ object o = (System.Linq.Expressions.Expression)({anonymousFunction}); }} }}"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); if (expectedType is null) { comp.VerifyDiagnostics( // (5,20): error CS8917: The delegate type could not be inferred. // object o = (System.Linq.Expressions.Expression)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, $"(System.Linq.Expressions.Expression)({anonymousFunction})").WithLocation(5, 20)); } else { comp.VerifyDiagnostics(); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); if (expectedType is null) { Assert.Null(typeInfo.ConvertedType); } else { Assert.Equal($"System.Linq.Expressions.Expression<{expectedType}>", typeInfo.ConvertedType.ToTestDisplayString()); } } /// <summary> /// Should bind and report diagnostics from anonymous method body /// regardless of whether the delegate type can be inferred. /// </summary> [Fact] public void AnonymousMethodBodyErrors() { var source = @"using System; class Program { static void Main() { Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Delegate d1 = (object x1) => { _ = x1.Length; }; Delegate d2 = (ref object x2) => { _ = x2.Length; }; Delegate d3 = delegate (object x3) { _ = x3.Length; }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,23): error CS8917: The delegate type could not be inferred. // Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }").WithLocation(6, 23), // (6,68): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(6, 68), // (7,47): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d1 = (object x1) => { _ = x1.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(7, 47), // (8,51): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d2 = (ref object x2) => { _ = x2.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(8, 51), // (9,53): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d3 = delegate (object x3) { _ = x3.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(9, 53)); } public static IEnumerable<object?[]> GetBaseAndDerivedTypesData() { yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // instance and static // https://github.com/dotnet/roslyn/issues/52701: Assert failure: Unexpected value 'LessDerived' of type 'Microsoft.CodeAnalysis.CSharp.MemberResolutionKind' #if !DEBUG yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "this.F", "F", new[] { // (5,29): error CS0176: Member 'B.F(object)' cannot be accessed with an instance reference; qualify it with a type name instead // System.Delegate d = this.F; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.F").WithArguments("B.F(object)").WithLocation(5, 29) }); // instance and static #endif yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "base.F", "F", null, "System.Action<System.Object>"); // instance and static yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // static and instance yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "this.F", "F", null, "System.Action<System.Object>"); // static and instance yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "base.F", "F"); // static and instance yield return getData("internal void F(object x) { }", "internal static void F() { }", "F", "F"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "B.F", "F", null, "System.Action"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "this.F", "F", null, "System.Action<System.Object>"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "base.F", "F", null, "System.Action<System.Object>"); // instance and static, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "F", "F"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "B.F", "F", null, "System.Action"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "this.F", "F", null, "System.Action<System.Object>"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "base.F", "F"); // static and instance, different number of parameters yield return getData("internal static void F(object x) { }", "private static void F() { }", "F", "F"); // internal and private yield return getData("private static void F(object x) { }", "internal static void F() { }", "F", "F", null, "System.Action"); // internal and private yield return getData("internal abstract void F(object x);", "internal override void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // override yield return getData("internal virtual void F(object x) { }", "internal override void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // override yield return getData("internal void F(object x) { }", "internal void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // hiding yield return getData("internal void F(object x) { }", "internal new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // hiding yield return getData("internal void F(object x) { }", "internal new void F(object y) { }", "F", "F", null, "System.Action<System.Object>"); // different parameter name yield return getData("internal void F(object x) { }", "internal void F(string x) { }", "F", "F"); // different parameter type yield return getData("internal void F(object x) { }", "internal void F(object x, object y) { }", "F", "F"); // different number of parameters yield return getData("internal void F(object x) { }", "internal void F(ref object x) { }", "F", "F"); // different parameter ref kind yield return getData("internal void F(ref object x) { }", "internal void F(object x) { }", "F", "F"); // different parameter ref kind yield return getData("internal abstract object F();", "internal override object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // override yield return getData("internal virtual object F() => throw null;", "internal override object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // override yield return getData("internal object F() => throw null;", "internal object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // hiding yield return getData("internal object F() => throw null;", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // hiding yield return getData("internal string F() => throw null;", "internal new object F() => throw null;", "F", "F"); // different return type yield return getData("internal object F() => throw null;", "internal new ref object F() => throw null;", "F", "F"); // different return ref kind yield return getData("internal ref object F() => throw null;", "internal new object F() => throw null;", "F", "F"); // different return ref kind yield return getData("internal void F(object x) { }", "internal new void F(dynamic x) { }", "F", "F", null, "System.Action<System.Object>"); // object/dynamic yield return getData("internal dynamic F() => throw null;", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // object/dynamic yield return getData("internal void F((object, int) x) { }", "internal new void F((object a, int b) x) { }", "F", "F", null, "System.Action<System.ValueTuple<System.Object, System.Int32>>"); // tuple names yield return getData("internal (object a, int b) F() => throw null;", "internal new (object, int) F() => throw null;", "F", "F", null, "System.Func<System.ValueTuple<System.Object, System.Int32>>"); // tuple names yield return getData("internal void F(System.IntPtr x) { }", "internal new void F(nint x) { }", "F", "F", null, "System.Action<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal nint F() => throw null;", "internal new System.IntPtr F() => throw null;", "F", "F", null, "System.Func<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal void F(object x) { }", @"#nullable enable internal new void F(object? x) { } #nullable disable", "F", "F", null, "System.Action<System.Object>"); // different nullability yield return getData( @"#nullable enable internal object? F() => throw null!; #nullable disable", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // different nullability yield return getData("internal void F() { }", "internal void F<T>() { }", "F", "F"); // different arity yield return getData("internal void F() { }", "internal void F<T>() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F() { }", "F", "F"); // different arity yield return getData("internal void F<T>() { }", "internal void F() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F<T, U>() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F<T, U>() { }", "F<int, object>", "F<int, object>", null, "System.Action"); // different arity yield return getData("internal void F<T>(T t) { }", "internal new void F<U>(U u) { }", "F<int>", "F<int>", null, "System.Action<System.Int32>"); // different type parameter names yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) { }", "F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) { }", "internal new void F<T>(T t) where T : class { }", "F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) { }", "internal new void F<T>(T t) where T : class { }", "base.F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) where T : struct { }", "F<int>", "F<int>", null, "System.Action<System.Int32>"); // different type parameter constraints // https://github.com/dotnet/roslyn/issues/52701: Assert failure: Unexpected value 'LessDerived' of type 'Microsoft.CodeAnalysis.CSharp.MemberResolutionKind' #if !DEBUG yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) where T : struct { }", "F<object>", "F<object>", new[] { // (5,29): error CS0453: The type 'object' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B.F<T>(T)' // System.Delegate d = F<object>; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<object>").WithArguments("B.F<T>(T)", "T", "object").WithLocation(5, 29) }); // different type parameter constraints #endif static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(5, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedType }; } } [Theory] [MemberData(nameof(GetBaseAndDerivedTypesData))] public void MethodGroup_BaseAndDerivedTypes(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"partial class B {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(d.GetDelegateTypeName()); }} static void Main() {{ new B().M(); }} }} abstract class A {{ {methodA} }} partial class B : A {{ {methodB} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } public static IEnumerable<object?[]> GetExtensionMethodsSameScopeData() { yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "string.Empty.F", "F", null, "B.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different number of parameters yield return getData("internal static void F(this object x, object y) { }", "internal static void F(this object x, ref object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static void F(this object x, ref object y) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static object F(this object x) => throw null;", "internal static ref object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static ref object F(this object x) => throw null;", "internal static object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F", "F"); // different arity yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F<int>", "F<int>", null, "B.F", "System.Action<System.Int32>"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F", "F"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F<int>", "F<int>", null, "A.F", "System.Action"); // different arity yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) { }", "this.F<object>", "F<object>", new[] { // (5,29): error CS0121: The call is ambiguous between the following methods or properties: 'A.F<T>(T)' and 'B.F<T>(T)' // System.Delegate d = this.F<object>; Diagnostic(ErrorCode.ERR_AmbigCall, "this.F<object>").WithArguments("A.F<T>(T)", "B.F<T>(T)").WithLocation(5, 29) }); // different type parameter constraints yield return getData("internal static void F<T>(this T t) { }", "internal static void F<T>(this T t) where T : class { }", "this.F<object>", "F<object>", new[] { // (5,29): error CS0121: The call is ambiguous between the following methods or properties: 'A.F<T>(T)' and 'B.F<T>(T)' // System.Delegate d = this.F<object>; Diagnostic(ErrorCode.ERR_AmbigCall, "this.F<object>").WithArguments("A.F<T>(T)", "B.F<T>(T)").WithLocation(5, 29) }); // different type parameter constraints yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) where T : struct { }", "this.F<int>", "F<int>"); // different type parameter constraints static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedMethod = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(5, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedMethod, expectedType }; } } [Theory] [MemberData(nameof(GetExtensionMethodsSameScopeData))] public void MethodGroup_ExtensionMethodsSameScope(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedMethod, string? expectedType) { var source = $@"class Program {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(""{{0}}: {{1}}"", d.GetDelegateMethodName(), d.GetDelegateTypeName()); }} static void Main() {{ new Program().M(); }} }} static class A {{ {methodA} }} static class B {{ {methodB} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: $"{expectedMethod}: {expectedType}"); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); // https://github.com/dotnet/roslyn/issues/52870: GetSymbolInfo() should return resolved method from method group. Assert.Null(symbolInfo.Symbol); } public static IEnumerable<object?[]> GetExtensionMethodsDifferentScopeData() { yield return getData("internal static void F(this object x) { }", "internal static void F(this object x) { }", "this.F", "F", null, "A.F", "System.Action"); // hiding yield return getData("internal static void F(this object x) { }", "internal static void F(this object y) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter name yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "string.Empty.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different number of parameters yield return getData("internal static void F(this object x, object y) { }", "internal static void F(this object x, ref object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static void F(this object x, ref object y) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static object F(this object x) => throw null;", "internal static ref object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static ref object F(this object x) => throw null;", "internal static object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static void F(this object x, System.IntPtr y) { }", "internal static void F(this object x, nint y) { }", "this.F", "F", null, "A.F", "System.Action<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal static nint F(this object x) => throw null;", "internal static System.IntPtr F(this object x) => throw null;", "this.F", "F", null, "A.F", "System.Func<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F", "F"); // different arity yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F<int>", "F<int>", null, "N.B.F", "System.Action<System.Int32>"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F", "F"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F<int>", "F<int>", null, "A.F", "System.Action"); // different arity yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) { }", "this.F<object>", "F<object>", null, "A.F", "System.Action"); // different type parameter constraints yield return getData("internal static void F<T>(this T t) { }", "internal static void F<T>(this T t) where T : class { }", "this.F<object>", "F<object>", null, "A.F", "System.Action"); // different type parameter constraints yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) where T : struct { }", "this.F<int>", "F<int>"); // different type parameter constraints static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedMethod = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (6,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(6, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedMethod, expectedType }; } } [Theory] [MemberData(nameof(GetExtensionMethodsDifferentScopeData))] public void MethodGroup_ExtensionMethodsDifferentScope(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedMethod, string? expectedType) { var source = $@"using N; class Program {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(""{{0}}: {{1}}"", d.GetDelegateMethodName(), d.GetDelegateTypeName()); }} static void Main() {{ new Program().M(); }} }} static class A {{ {methodA} }} namespace N {{ static class B {{ {methodB} }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: $"{expectedMethod}: {expectedType}"); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); // https://github.com/dotnet/roslyn/issues/52870: GetSymbolInfo() should return resolved method from method group. Assert.Null(symbolInfo.Symbol); } [Fact] public void InstanceMethods_01() { var source = @"using System; class Program { object F1() => null; void F2(object x, int y) { } void F() { Delegate d1 = F1; Delegate d2 = this.F2; Console.WriteLine(""{0}, {1}"", d1.GetDelegateTypeName(), d2.GetDelegateTypeName()); } static void Main() { new Program().F(); } }"; CompileAndVerify(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, expectedOutput: "System.Func<System.Object>, System.Action<System.Object, System.Int32>"); } [Fact] public void InstanceMethods_02() { var source = @"using System; class A { protected virtual void F() { Console.WriteLine(nameof(A)); } } class B : A { protected override void F() { Console.WriteLine(nameof(B)); } static void Invoke(Delegate d) { d.DynamicInvoke(); } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } static void Main() { new B().M(); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"B B A"); } [Fact] public void InstanceMethods_03() { var source = @"using System; class A { protected void F() { Console.WriteLine(nameof(A)); } } class B : A { protected new void F() { Console.WriteLine(nameof(B)); } static void Invoke(Delegate d) { d.DynamicInvoke(); } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } static void Main() { new B().M(); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"B B A"); } [Fact] public void InstanceMethods_04() { var source = @"class Program { T F<T>() => default; static void Main() { var p = new Program(); System.Delegate d = p.F; object o = (System.Delegate)p.F; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (7,31): error CS8917: The delegate type could not be inferred. // System.Delegate d = p.F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 31), // (8,20): error CS0030: Cannot convert type 'method' to 'Delegate' // object o = (System.Delegate)p.F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(System.Delegate)p.F").WithArguments("method", "System.Delegate").WithLocation(8, 20)); } [Fact] public void MethodGroup_Inaccessible() { var source = @"using System; class A { private static void F() { } internal static void F(object o) { } } class B { static void Main() { Delegate d = A.F; Console.WriteLine(d.GetDelegateTypeName()); } }"; CompileAndVerify(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, expectedOutput: "System.Action<System.Object>"); } [Fact] public void MethodGroup_IncorrectArity() { var source = @"class Program { static void F0(object o) { } static void F0<T>(object o) { } static void F1(object o) { } static void F1<T, U>(object o) { } static void F2<T>(object o) { } static void F2<T, U>(object o) { } static void Main() { System.Delegate d; d = F0<int, object>; d = F1<int>; d = F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (12,13): error CS0308: The non-generic method 'Program.F0(object)' cannot be used with type arguments // d = F0<int, object>; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "F0<int, object>").WithArguments("Program.F0(object)", "method").WithLocation(12, 13), // (13,13): error CS0308: The non-generic method 'Program.F1(object)' cannot be used with type arguments // d = F1<int>; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "F1<int>").WithArguments("Program.F1(object)", "method").WithLocation(13, 13), // (14,13): error CS8917: The delegate type could not be inferred. // d = F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(14, 13)); } [Fact] public void ExtensionMethods_01() { var source = @"static class E { internal static void F1(this object x, int y) { } internal static void F2(this object x) { } } class Program { void F2(int x) { } static void Main() { System.Delegate d; var p = new Program(); d = p.F1; d = p.F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (14,15): error CS8917: The delegate type could not be inferred. // d = p.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(14, 15)); } [Fact] public void ExtensionMethods_02() { var source = @"using System; static class E { internal static void F(this System.Type x, int y) { } internal static void F(this string x) { } } class Program { static void Main() { Delegate d1 = typeof(Program).F; Delegate d2 = """".F; Console.WriteLine(""{0}, {1}"", d1.GetDelegateTypeName(), d2.GetDelegateTypeName()); } }"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "System.Action<System.Int32>, System.Action"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Select(d => d.Initializer!.Value).ToArray(); Assert.Equal(2, exprs.Length); foreach (var expr in exprs) { var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } } [Fact] public void ExtensionMethods_03() { var source = @"using N; namespace N { static class E1 { internal static void F1(this object x, int y) { } internal static void F2(this object x, int y) { } internal static void F2(this object x) { } internal static void F3(this object x) { } } } static class E2 { internal static void F1(this object x) { } } class Program { static void Main() { System.Delegate d; var p = new Program(); d = p.F1; d = p.F2; d = p.F3; d = E1.F1; d = E2.F1; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (22,15): error CS8917: The delegate type could not be inferred. // d = p.F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(22, 15), // (23,15): error CS8917: The delegate type could not be inferred. // d = p.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(23, 15)); } [Fact] public void ExtensionMethods_04() { var source = @"static class E { internal static void F1(this object x, int y) { } } static class Program { static void F2(this object x) { } static void Main() { System.Delegate d; d = E.F1; d = F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [Fact] public void ExtensionMethods_05() { var source = @"using System; static class E { internal static void F(this A a) { } } class A { } class B : A { static void Invoke(Delegate d) { } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (14,16): error CS0103: The name 'F' does not exist in the current context // Invoke(F); Diagnostic(ErrorCode.ERR_NameNotInContext, "F").WithArguments("F").WithLocation(14, 16), // (16,21): error CS0117: 'A' does not contain a definition for 'F' // Invoke(base.F); Diagnostic(ErrorCode.ERR_NoSuchMember, "F").WithArguments("A", "F").WithLocation(16, 21)); } [Fact] public void ExtensionMethods_06() { var source = @"static class E { internal static void F1<T>(this object x, T y) { } internal static void F2<T, U>(this T t) { } } class Program { static void F<T>(T t) where T : class { System.Delegate d; d = t.F1; d = t.F2; d = t.F1<int>; d = t.F1<T>; d = t.F2<T, object>; d = t.F2<object, T>; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (11,15): error CS8917: The delegate type could not be inferred. // d = t.F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(11, 15), // (12,15): error CS8917: The delegate type could not be inferred. // d = t.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(12, 15)); } /// <summary> /// Method group with dynamic receiver does not use method group conversion. /// </summary> [Fact] public void DynamicReceiver() { var source = @"using System; class Program { void F() { } static void Main() { dynamic d = new Program(); object obj; try { obj = d.F; } catch (Exception e) { obj = e; } Console.WriteLine(obj.GetType().FullName); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, references: new[] { CSharpRef }, expectedOutput: "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException"); } // System.Func<> and System.Action<> cannot be used as the delegate type // when the parameters or return type are not valid type arguments. [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [Fact] public void InvalidTypeArguments() { var source = @"unsafe class Program { static int* F() => throw null; static void Main() { System.Delegate d; d = F; d = (int x, int* y) => { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (7,13): error CS8917: The delegate type could not be inferred. // d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 13), // (8,13): error CS8917: The delegate type could not be inferred. // d = (int x, int* y) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(int x, int* y) => { }").WithLocation(8, 13)); } [Fact] public void GenericDelegateType() { var source = @"using System; class Program { static void Main() { Delegate d = F<int>(); Console.WriteLine(d.GetDelegateTypeName()); } unsafe static Delegate F<T>() { return (T t, int* p) => { }; } }"; // When we synthesize delegate types with parameter types (such as int*) that cannot // be used as type arguments, run the program to report the actual delegate type. var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (11,16): error CS8917: The delegate type could not be inferred. // return (T t, int* p) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(T t, int* p) => { }").WithLocation(11, 16)); } /// <summary> /// Custom modifiers should not affect delegate signature. /// </summary> [Fact] public void CustomModifiers_01() { var sourceA = @".class public A { .method public static void F1(object modopt(int32) x) { ldnull throw } .method public static object modopt(int32) F2() { ldnull throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using System; class B { static void Report(Delegate d) { Console.WriteLine(d.GetDelegateTypeName()); } static void Main() { Report(A.F1); Report(A.F2); } }"; var comp = CreateCompilation(new[] { sourceB, s_utils }, new[] { refA }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"System.Action<System.Object> System.Func<System.Object>"); } /// <summary> /// Custom modifiers should not affect delegate signature. /// </summary> [Fact] public void CustomModifiers_02() { var sourceA = @".class public A { .method public static void F1(object modreq(int32) x) { ldnull throw } .method public static object modreq(int32) F2() { ldnull throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using System; class B { static void Report(Delegate d) { Console.WriteLine(d.GetDelegateTypeName()); } static void Main() { Report(A.F1); Report(A.F2); } }"; var comp = CreateCompilation(new[] { sourceB, s_utils }, new[] { refA }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (10,16): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // Report(A.F1); Diagnostic(ErrorCode.ERR_BadArgType, "A.F1").WithArguments("1", "method group", "System.Delegate").WithLocation(10, 16), // (11,16): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // Report(A.F2); Diagnostic(ErrorCode.ERR_BadArgType, "A.F2").WithArguments("1", "method group", "System.Delegate").WithLocation(11, 16)); } [Fact] public void UnmanagedCallersOnlyAttribute_01() { var source = @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; class Program { static void Main() { Delegate d = F; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] static void F() { } }"; var comp = CreateCompilation(new[] { source, UnmanagedCallersOnlyAttributeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,22): error CS8902: 'Program.F()' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method. // Delegate d = F; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate, "F").WithArguments("Program.F()").WithLocation(8, 22)); } [Fact] public void UnmanagedCallersOnlyAttribute_02() { var source = @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; class Program { static void Main() { Delegate d = new S().F; } } struct S { } static class E1 { [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] public static void F(this S s) { } } static class E2 { [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] public static void F(this S s) { } }"; var comp = CreateCompilation(new[] { source, UnmanagedCallersOnlyAttributeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,22): error CS0121: The call is ambiguous between the following methods or properties: 'E1.F(S)' and 'E2.F(S)' // Delegate d = new S().F; Diagnostic(ErrorCode.ERR_AmbigCall, "new S().F").WithArguments("E1.F(S)", "E2.F(S)").WithLocation(8, 22)); } [Fact] public void SystemActionAndFunc_Missing() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Delegate d; d = Main; d = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,13): error CS0518: Predefined type 'System.Action' is not defined or imported // d = Main; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Main").WithArguments("System.Action").WithLocation(6, 13), // (6,13): error CS0518: Predefined type 'System.Action' is not defined or imported // d = Main; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Main").WithArguments("System.Action").WithLocation(6, 13), // (6,13): error CS8917: The delegate type could not be inferred. // d = Main; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "Main").WithLocation(6, 13), // (7,13): error CS0518: Predefined type 'System.Func`1' is not defined or imported // d = () => 1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "() => 1").WithArguments("System.Func`1").WithLocation(7, 13)); } private static MetadataReference GetCorlibWithInvalidActionAndFuncOfT() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Attribute extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Runtime.CompilerServices.RequiredAttributeAttribute extends System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class System.Type t) cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Action`1<T> extends System.MulticastDelegate { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance void Invoke(!T t) { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } }"; return CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); } [Fact] public void SystemActionAndFunc_UseSiteErrors() { var refA = GetCorlibWithInvalidActionAndFuncOfT(); var sourceB = @"class Program { static void F(object o) { } static void Main() { System.Delegate d; d = F; d = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (9,13): error CS0648: 'Action<T>' is a type not supported by the language // d = F; Diagnostic(ErrorCode.ERR_BogusType, "F").WithArguments("System.Action<T>").WithLocation(9, 13), // (9,13): error CS0648: 'Action<T>' is a type not supported by the language // d = F; Diagnostic(ErrorCode.ERR_BogusType, "F").WithArguments("System.Action<T>").WithLocation(9, 13), // (10,13): error CS0648: 'Func<T>' is a type not supported by the language // d = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Func<T>").WithLocation(10, 13)); } [Fact] public void SystemLinqExpressionsExpression_Missing() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } } .class public abstract System.Linq.Expressions.Expression extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,48): error CS0518: Predefined type 'System.Linq.Expressions.Expression`1' is not defined or imported // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "() => 1").WithArguments("System.Linq.Expressions.Expression`1").WithLocation(5, 48)); } [Fact] public void SystemLinqExpressionsExpression_UseSiteErrors() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Attribute extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Runtime.CompilerServices.RequiredAttributeAttribute extends System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class System.Type t) cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } } .class public abstract System.Linq.Expressions.Expression extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Linq.Expressions.LambdaExpression extends System.Linq.Expressions.Expression { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Linq.Expressions.Expression`1<T> extends System.Linq.Expressions.LambdaExpression { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,48): error CS0648: 'Expression<T>' is a type not supported by the language // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Linq.Expressions.Expression<T>").WithLocation(5, 48)); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_01() { var source = @"using System; class Program { static void M<T>(T t) { Console.WriteLine(""M<T>(T t)""); } static void M(Action<string> a) { Console.WriteLine(""M(Action<string> a)""); } static void F(object o) { } static void Main() { M(F); // C#9: M(Action<string>) } }"; var expectedOutput = @"M(Action<string> a)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: expectedOutput); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_02() { var source = @"using System; class Program { static void Main() { var c = new C(); c.M(Main); // C#9: E.M(object x, Action y) c.M(() => { }); // C#9: E.M(object x, Action y) } } class C { public void M(object y) { Console.WriteLine(""C.M(object y)""); } } static class E { public static void M(this object x, Action y) { Console.WriteLine(""E.M(object x, Action y)""); } }"; var expectedOutput = @"E.M(object x, Action y) E.M(object x, Action y) "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: expectedOutput); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_03() { var source = @"using System; class Program { static void Main() { var c = new C(); c.M(Main); // C#9: E.M(object x, Action y) c.M(() => { }); // C#9: E.M(object x, Action y) } } class C { public void M(Delegate d) { Console.WriteLine(""C.M""); } } static class E { public static void M(this object o, Action a) { Console.WriteLine(""E.M""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M E.M "); // Breaking change from C#9 which binds to E.M. CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"C.M C.M "); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { var c = new C(); c.M(() => 1); } } class C { public void M(Expression e) { Console.WriteLine(""C.M""); } } static class E { public static void M(this object o, Func<int> a) { Console.WriteLine(""E.M""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M"); // Breaking change from C#9 which binds to E.M. CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"C.M"); } [Fact] public void OverloadResolution_05() { var source = @"using System; class Program { static void Report(string name) { Console.WriteLine(name); } static void FA(Delegate d) { Report(""FA(Delegate)""); } static void FA(Action d) { Report(""FA(Action)""); } static void FB(Delegate d) { Report(""FB(Delegate)""); } static void FB(Func<int> d) { Report(""FB(Func<int>)""); } static void F1() { } static int F2() => 0; static void Main() { FA(F1); FA(F2); FB(F1); FB(F2); FA(() => { }); FA(() => 0); FB(() => { }); FB(() => 0); FA(delegate () { }); FA(delegate () { return 0; }); FB(delegate () { }); FB(delegate () { return 0; }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (14,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // FA(F2); Diagnostic(ErrorCode.ERR_BadArgType, "F2").WithArguments("1", "method group", "System.Delegate").WithLocation(14, 12), // (15,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // FB(F1); Diagnostic(ErrorCode.ERR_BadArgType, "F1").WithArguments("1", "method group", "System.Delegate").WithLocation(15, 12), // (18,18): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // FA(() => 0); Diagnostic(ErrorCode.ERR_IllegalStatement, "0").WithLocation(18, 18), // (19,15): error CS1643: Not all code paths return a value in lambda expression of type 'Func<int>' // FB(() => { }); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "=>").WithArguments("lambda expression", "System.Func<int>").WithLocation(19, 15), // (22,26): error CS8030: Anonymous function converted to a void returning delegate cannot return a value // FA(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(22, 26), // (23,12): error CS1643: Not all code paths return a value in anonymous method of type 'Func<int>' // FB(delegate () { }); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "delegate").WithArguments("anonymous method", "System.Func<int>").WithLocation(23, 12)); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) "); } [Fact] public void OverloadResolution_06() { var source = @"using System; using System.Linq.Expressions; class Program { static void Report(string name, Expression e) { Console.WriteLine(""{0}: {1}"", name, e); } static void F(Expression e) { Report(""F(Expression)"", e); } static void F(Expression<Func<int>> e) { Report(""F(Expression<Func<int>>)"", e); } static void Main() { F(() => 0); F(() => string.Empty); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,17): error CS0029: Cannot implicitly convert type 'string' to 'int' // F(() => string.Empty); Diagnostic(ErrorCode.ERR_NoImplicitConv, "string.Empty").WithArguments("string", "int").WithLocation(11, 17), // (11,17): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // F(() => string.Empty); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "string.Empty").WithArguments("lambda expression").WithLocation(11, 17)); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"F(Expression<Func<int>>): () => 0 F(Expression): () => String.Empty "); } [Fact] public void OverloadResolution_07() { var source = @"using System; using System.Linq.Expressions; class Program { static void F(Expression e) { } static void F(Expression<Func<int>> e) { } static void Main() { F(delegate () { return 0; }); F(delegate () { return string.Empty; }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (9,11): error CS1946: An anonymous method expression cannot be converted to an expression tree // F(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return 0; }").WithLocation(9, 11), // (10,11): error CS1946: An anonymous method expression cannot be converted to an expression tree // F(delegate () { return string.Empty; }); Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return string.Empty; }").WithLocation(10, 11)); } [Fact] public void ImplicitlyTypedVariables_01() { var source = @"using System; class Program { static void Main() { var d1 = Main; Report(d1); var d2 = () => { }; Report(d2); var d3 = delegate () { }; Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetDelegateTypeName()); }"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d1 = Main; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "Main").WithArguments("inferred delegate type", "10.0").WithLocation(6, 18), // (8,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d2 = () => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => { }").WithArguments("inferred delegate type", "10.0").WithLocation(8, 18), // (10,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "delegate () { }").WithArguments("inferred delegate type", "10.0").WithLocation(10, 18)); comp = CreateCompilation(new[] { source, s_utils }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Action System.Action System.Action"); verifier.VerifyIL("Program.Main", @"{ // Code size 100 (0x64) .maxstack 2 .locals init (System.Action V_0, //d1 System.Action V_1, //d2 System.Action V_2) //d3 IL_0000: nop IL_0001: ldnull IL_0002: ldftn ""void Program.Main()"" IL_0008: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_000d: stloc.0 IL_000e: ldloc.0 IL_000f: call ""void Program.Report(System.Delegate)"" IL_0014: nop IL_0015: ldsfld ""System.Action Program.<>c.<>9__0_0"" IL_001a: dup IL_001b: brtrue.s IL_0034 IL_001d: pop IL_001e: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0023: ldftn ""void Program.<>c.<Main>b__0_0()"" IL_0029: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_002e: dup IL_002f: stsfld ""System.Action Program.<>c.<>9__0_0"" IL_0034: stloc.1 IL_0035: ldloc.1 IL_0036: call ""void Program.Report(System.Delegate)"" IL_003b: nop IL_003c: ldsfld ""System.Action Program.<>c.<>9__0_1"" IL_0041: dup IL_0042: brtrue.s IL_005b IL_0044: pop IL_0045: ldsfld ""Program.<>c Program.<>c.<>9"" IL_004a: ldftn ""void Program.<>c.<Main>b__0_1()"" IL_0050: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0055: dup IL_0056: stsfld ""System.Action Program.<>c.<>9__0_1"" IL_005b: stloc.2 IL_005c: ldloc.2 IL_005d: call ""void Program.Report(System.Delegate)"" IL_0062: nop IL_0063: ret }"); } [Fact] public void ImplicitlyTypedVariables_02() { var source = @"var d1 = object.ReferenceEquals; var d2 = () => { }; var d3 = delegate () { }; "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9.WithKind(SourceCodeKind.Script)); comp.VerifyDiagnostics( // (1,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d1 = object.ReferenceEquals; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object.ReferenceEquals").WithArguments("inferred delegate type", "10.0").WithLocation(1, 10), // (2,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d2 = () => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => { }").WithArguments("inferred delegate type", "10.0").WithLocation(2, 10), // (3,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "delegate () { }").WithArguments("inferred delegate type", "10.0").WithLocation(3, 10)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10.WithKind(SourceCodeKind.Script)); comp.VerifyDiagnostics(); } [Fact] public void ImplicitlyTypedVariables_03() { var source = @"class Program { static void Main() { ref var d1 = Main; ref var d2 = () => { }; ref var d3 = delegate () { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d1 = Main; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d1 = Main").WithLocation(5, 17), // (5,22): error CS1657: Cannot use 'Main' as a ref or out value because it is a 'method group' // ref var d1 = Main; Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "Main").WithArguments("Main", "method group").WithLocation(5, 22), // (6,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d2 = () => { }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d2 = () => { }").WithLocation(6, 17), // (6,22): error CS1510: A ref or out value must be an assignable variable // ref var d2 = () => { }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "() => { }").WithLocation(6, 22), // (7,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d3 = delegate () { }").WithLocation(7, 17), // (7,22): error CS1510: A ref or out value must be an assignable variable // ref var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "delegate () { }").WithLocation(7, 22)); } [Fact] public void ImplicitlyTypedVariables_04() { var source = @"class Program { static void Main() { using var d1 = Main; using var d2 = () => { }; using var d3 = delegate () { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d1 = Main; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d1 = Main;").WithArguments("System.Action").WithLocation(5, 9), // (6,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d2 = () => { }; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d2 = () => { };").WithArguments("System.Action").WithLocation(6, 9), // (7,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d3 = delegate () { };").WithArguments("System.Action").WithLocation(7, 9)); } [Fact] public void ImplicitlyTypedVariables_05() { var source = @"class Program { static void Main() { foreach (var d1 in Main) { } foreach (var d2 in () => { }) { } foreach (var d3 in delegate () { }) { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,28): error CS0446: Foreach cannot operate on a 'method group'. Did you intend to invoke the 'method group'? // foreach (var d1 in Main) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "Main").WithArguments("method group").WithLocation(5, 28), // (6,28): error CS0446: Foreach cannot operate on a 'lambda expression'. Did you intend to invoke the 'lambda expression'? // foreach (var d2 in () => { }) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "() => { }").WithArguments("lambda expression").WithLocation(6, 28), // (7,28): error CS0446: Foreach cannot operate on a 'anonymous method'. Did you intend to invoke the 'anonymous method'? // foreach (var d3 in delegate () { }) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "delegate () { }").WithArguments("anonymous method").WithLocation(7, 28)); } [Fact] public void ImplicitlyTypedVariables_06() { var source = @"using System; class Program { static void Main() { Func<int> f; var d1 = Main; f = d1; var d2 = object (int x) => x; f = d2; var d3 = delegate () { return string.Empty; }; f = d3; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,13): error CS0029: Cannot implicitly convert type 'System.Action' to 'System.Func<int>' // f = d1; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d1").WithArguments("System.Action", "System.Func<int>").WithLocation(8, 13), // (10,13): error CS0029: Cannot implicitly convert type 'System.Func<int, object>' to 'System.Func<int>' // f = d2; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d2").WithArguments("System.Func<int, object>", "System.Func<int>").WithLocation(10, 13), // (12,13): error CS0029: Cannot implicitly convert type 'System.Func<string>' to 'System.Func<int>' // f = d3; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d3").WithArguments("System.Func<string>", "System.Func<int>").WithLocation(12, 13)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var variables = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(v => v.Initializer != null); var expectedInfo = new (string?, string?, string?)[] { ("System.Action d1", null, "System.Action"), ("System.Func<System.Int32, System.Object> d2", null, "System.Func<System.Int32, System.Object>"), ("System.Func<System.String> d3", null, "System.Func<System.String>"), }; AssertEx.Equal(expectedInfo, variables.Select(v => getVariableInfo(model, v))); static (string?, string?, string?) getVariableInfo(SemanticModel model, VariableDeclaratorSyntax variable) { var symbol = model.GetDeclaredSymbol(variable); var typeInfo = model.GetTypeInfo(variable.Initializer!.Value); return (symbol?.ToTestDisplayString(), typeInfo.Type?.ToTestDisplayString(), typeInfo.ConvertedType?.ToTestDisplayString()); } } [Fact] public void ImplicitlyTypedVariables_07() { var source = @"class Program { static void Main() { var t = (Main, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,13): error CS0815: Cannot assign (method group, lambda expression) to an implicitly-typed variable // var t = (Main, () => { }); Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "t = (Main, () => { })").WithArguments("(method group, lambda expression)").WithLocation(5, 13)); } [Fact] public void ImplicitlyTypedVariables_08() { var source = @"class Program { static void Main() { (var x1, var y1) = Main; var (x2, y2) = () => { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(5, 14), // (5,22): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y1'. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y1").WithArguments("y1").WithLocation(5, 22), // (5,28): error CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "Main").WithLocation(5, 28), // (6,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x2'. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x2").WithArguments("x2").WithLocation(6, 14), // (6,18): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y2'. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y2").WithArguments("y2").WithLocation(6, 18), // (6,24): error CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "() => { }").WithLocation(6, 24)); } [Fact] public void ImplicitlyTypedVariables_09() { var source = @"class Program { static void Main() { var (x, y) = (Main, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'. // var (x, y) = (Main, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(5, 14), // (5,17): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. // var (x, y) = (Main, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(5, 17)); } [Fact] public void ImplicitlyTypedVariables_10() { var source = @"using System; class Program { static void Main() { (var x1, Action y1) = (Main, null); (Action x2, var y2) = (null, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'. // (var x1, Action y1) = (Main, null); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(6, 14), // (7,25): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y2'. // (Action x2, var y2) = (null, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y2").WithArguments("y2").WithLocation(7, 25)); } [Fact] public void ImplicitlyTypedVariables_11() { var source = @"class Program { static void F(object o) { } static void F(int i) { } static void Main() { var d1 = F; var d2 = x => x; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,18): error CS8917: The delegate type could not be inferred. // var d1 = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 18), // (8,18): error CS8917: The delegate type could not be inferred. // var d2 = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(8, 18)); } [Fact] public void ImplicitlyTypedVariables_12() { var source = @"class Program { static void F(ref int i) { } static void Main() { var d1 = F; var d2 = (ref int x) => x; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ImplicitlyTypedVariables_13() { var source = @"using System; class Program { static int F() => 0; static void Main() { var d1 = (F); Report(d1); var d2 = (object (int x) => x); Report(d2); var d3 = (delegate () { return string.Empty; }); Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetDelegateTypeName()); }"; CompileAndVerify(new[] { source, s_utils }, options: TestOptions.DebugExe, expectedOutput: @"System.Func<System.Int32> System.Func<System.Int32, System.Object> System.Func<System.String>"); } [Fact] public void ImplicitlyTypedVariables_14() { var source = @"delegate void D(string s); class Program { static void Main() { (D x, var y) = (() => string.Empty, () => string.Empty); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,19): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. // (D x, var y) = (() => string.Empty, () => string.Empty); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(6, 19)); } [Fact] public void ImplicitlyTypedVariables_UseSiteErrors() { var source = @"class Program { static void F(object o) { } static void Main() { var d1 = F; var d2 = () => 1; } }"; var comp = CreateEmptyCompilation(source, new[] { GetCorlibWithInvalidActionAndFuncOfT() }); comp.VerifyDiagnostics( // (6,18): error CS0648: 'Action<T>' is a type not supported by the language // var d1 = F; Diagnostic(ErrorCode.ERR_BogusType, "F").WithArguments("System.Action<T>").WithLocation(6, 18), // (7,18): error CS0648: 'Func<T>' is a type not supported by the language // var d2 = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Func<T>").WithLocation(7, 18)); } /// <summary> /// Ensure the conversion group containing the implicit /// conversion is handled correctly in NullableWalker. /// </summary> [Fact] public void NullableAnalysis_01() { var source = @"#nullable enable class Program { static void Main() { System.Delegate d; d = Main; d = () => { }; d = delegate () { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } /// <summary> /// Ensure the conversion group containing the explicit /// conversion is handled correctly in NullableWalker. /// </summary> [Fact] public void NullableAnalysis_02() { var source = @"#nullable enable class Program { static void Main() { object o; o = (System.Delegate)Main; o = (System.Delegate)(() => { }); o = (System.Delegate)(delegate () { }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [Fact] public void SynthesizedDelegateTypes_01() { var source = @"using System; class Program { static void M1<T>(T t) { var d = (ref T t) => t; Report(d); Console.WriteLine(d(ref t)); } static void M2<U>(U u) where U : struct { var d = (ref U u) => u; Report(d); Console.WriteLine(d(ref u)); } static void M3(double value) { var d = (ref double d) => d; Report(d); Console.WriteLine(d(ref value)); } static void Main() { M1(41); M2(42f); M2(43d); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"<>F{00000001}`2[System.Int32,System.Int32] 41 <>F{00000001}`2[System.Single,System.Single] 42 <>F{00000001}`2[System.Double,System.Double] 43 "); verifier.VerifyIL("Program.M1<T>", @"{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<T, T> Program.<>c__0<T>.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c__0<T> Program.<>c__0<T>.<>9"" IL_000e: ldftn ""T Program.<>c__0<T>.<M1>b__0_0(ref T)"" IL_0014: newobj ""<>F{00000001}<T, T>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<T, T> Program.<>c__0<T>.<>9__0_0"" IL_001f: dup IL_0020: call ""void Program.Report(System.Delegate)"" IL_0025: ldarga.s V_0 IL_0027: callvirt ""T <>F{00000001}<T, T>.Invoke(ref T)"" IL_002c: box ""T"" IL_0031: call ""void System.Console.WriteLine(object)"" IL_0036: ret }"); verifier.VerifyIL("Program.M2<U>", @"{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<U, U> Program.<>c__1<U>.<>9__1_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c__1<U> Program.<>c__1<U>.<>9"" IL_000e: ldftn ""U Program.<>c__1<U>.<M2>b__1_0(ref U)"" IL_0014: newobj ""<>F{00000001}<U, U>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<U, U> Program.<>c__1<U>.<>9__1_0"" IL_001f: dup IL_0020: call ""void Program.Report(System.Delegate)"" IL_0025: ldarga.s V_0 IL_0027: callvirt ""U <>F{00000001}<U, U>.Invoke(ref U)"" IL_002c: box ""U"" IL_0031: call ""void System.Console.WriteLine(object)"" IL_0036: ret }"); verifier.VerifyIL("Program.M3", @"{ // Code size 50 (0x32) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<double, double> Program.<>c.<>9__2_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""double Program.<>c.<M3>b__2_0(ref double)"" IL_0014: newobj ""<>F{00000001}<double, double>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<double, double> Program.<>c.<>9__2_0"" IL_001f: dup IL_0020: call ""void Program.Report(System.Delegate)"" IL_0025: ldarga.s V_0 IL_0027: callvirt ""double <>F{00000001}<double, double>.Invoke(ref double)"" IL_002c: call ""void System.Console.WriteLine(double)"" IL_0031: ret }"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var nodes = tree.GetRoot().DescendantNodes(); var variables = nodes.OfType<VariableDeclaratorSyntax>().Where(v => v.Identifier.Text == "d").ToArray(); Assert.Equal(3, variables.Length); VerifyLocalDelegateType(model, variables[0], "<>F{00000001}<T, T> d", "T <>F{00000001}<T, T>.Invoke(ref T)"); VerifyLocalDelegateType(model, variables[1], "<>F{00000001}<U, U> d", "U <>F{00000001}<U, U>.Invoke(ref U)"); VerifyLocalDelegateType(model, variables[2], "<>F{00000001}<System.Double, System.Double> d", "System.Double <>F{00000001}<System.Double, System.Double>.Invoke(ref System.Double)"); var identifiers = nodes.OfType<InvocationExpressionSyntax>().Where(i => i.Expression is IdentifierNameSyntax id && id.Identifier.Text == "Report").Select(i => i.ArgumentList.Arguments[0].Expression).ToArray(); Assert.Equal(3, identifiers.Length); VerifyExpressionType(model, identifiers[0], "<>F{00000001}<T, T> d", "<>F{00000001}<T, T>"); VerifyExpressionType(model, identifiers[1], "<>F{00000001}<U, U> d", "<>F{00000001}<U, U>"); VerifyExpressionType(model, identifiers[2], "<>F{00000001}<System.Double, System.Double> d", "<>F{00000001}<System.Double, System.Double>"); } [Fact] public void SynthesizedDelegateTypes_02() { var source = @"using System; class Program { static void M1(A a, int value) { var d = a.F1; d() = value; } static void M2(B b, float value) { var d = b.F2; d() = value; } static void Main() { var a = new A(); M1(a, 41); var b = new B(); M2(b, 42f); Console.WriteLine((a._f, b._f)); } } class A { public int _f; public ref int F1() => ref _f; } class B { public float _f; } static class E { public static ref float F2(this B b) => ref b._f; }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"(41, 42)"); verifier.VerifyIL("Program.M1", @"{ // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldftn ""ref int A.F1()"" IL_0007: newobj ""<>F{00000001}<int>..ctor(object, System.IntPtr)"" IL_000c: callvirt ""ref int <>F{00000001}<int>.Invoke()"" IL_0011: ldarg.1 IL_0012: stind.i4 IL_0013: ret }"); verifier.VerifyIL("Program.M2", @"{ // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldftn ""ref float E.F2(B)"" IL_0007: newobj ""<>F{00000001}<float>..ctor(object, System.IntPtr)"" IL_000c: callvirt ""ref float <>F{00000001}<float>.Invoke()"" IL_0011: ldarg.1 IL_0012: stind.r4 IL_0013: ret }"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var variables = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(v => v.Identifier.Text == "d").ToArray(); Assert.Equal(2, variables.Length); VerifyLocalDelegateType(model, variables[0], "<>F{00000001}<System.Int32> d", "ref System.Int32 <>F{00000001}<System.Int32>.Invoke()"); VerifyLocalDelegateType(model, variables[1], "<>F{00000001}<System.Single> d", "ref System.Single <>F{00000001}<System.Single>.Invoke()"); } [Fact] public void SynthesizedDelegateTypes_03() { var source = @"using System; class Program { static void Main() { Report((ref int x, int y) => { }); Report((int x, ref int y) => { }); Report((ref float x, int y) => { }); Report((float x, ref int y) => { }); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"<>A{00000001}`2[System.Int32,System.Int32] <>A{00000004}`2[System.Int32,System.Int32] <>A{00000001}`2[System.Single,System.Int32] <>A{00000004}`2[System.Single,System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 145 (0x91) .maxstack 2 IL_0000: ldsfld ""<>A{00000001}<int, int> Program.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""void Program.<>c.<Main>b__0_0(ref int, int)"" IL_0014: newobj ""<>A{00000001}<int, int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>A{00000001}<int, int> Program.<>c.<>9__0_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>A{00000004}<int, int> Program.<>c.<>9__0_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""void Program.<>c.<Main>b__0_1(int, ref int)"" IL_0038: newobj ""<>A{00000004}<int, int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>A{00000004}<int, int> Program.<>c.<>9__0_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>A{00000001}<float, int> Program.<>c.<>9__0_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""void Program.<>c.<Main>b__0_2(ref float, int)"" IL_005c: newobj ""<>A{00000001}<float, int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>A{00000001}<float, int> Program.<>c.<>9__0_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ldsfld ""<>A{00000004}<float, int> Program.<>c.<>9__0_3"" IL_0071: dup IL_0072: brtrue.s IL_008b IL_0074: pop IL_0075: ldsfld ""Program.<>c Program.<>c.<>9"" IL_007a: ldftn ""void Program.<>c.<Main>b__0_3(float, ref int)"" IL_0080: newobj ""<>A{00000004}<float, int>..ctor(object, System.IntPtr)"" IL_0085: dup IL_0086: stsfld ""<>A{00000004}<float, int> Program.<>c.<>9__0_3"" IL_008b: call ""void Program.Report(System.Delegate)"" IL_0090: ret }"); } [Fact] public void SynthesizedDelegateTypes_04() { var source = @"using System; class Program { static int i = 0; static void Main() { Report(int () => i); Report((ref int () => ref i)); Report((ref readonly int () => ref i)); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32] <>F{00000001}`1[System.Int32] <>F{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 109 (0x6d) .maxstack 2 IL_0000: ldsfld ""System.Func<int> Program.<>c.<>9__1_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""int Program.<>c.<Main>b__1_0()"" IL_0014: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""System.Func<int> Program.<>c.<>9__1_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>F{00000001}<int> Program.<>c.<>9__1_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""ref int Program.<>c.<Main>b__1_1()"" IL_0038: newobj ""<>F{00000001}<int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>F{00000001}<int> Program.<>c.<>9__1_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>F{00000003}<int> Program.<>c.<>9__1_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""ref readonly int Program.<>c.<Main>b__1_2()"" IL_005c: newobj ""<>F{00000003}<int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>F{00000003}<int> Program.<>c.<>9__1_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ret }"); } [Fact] public void SynthesizedDelegateTypes_05() { var source = @"using System; class Program { static int i = 0; static int F1() => i; static ref int F2() => ref i; static ref readonly int F3() => ref i; static void Main() { Report(F1); Report(F2); Report(F3); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32] <>F{00000001}`1[System.Int32] <>F{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 52 (0x34) .maxstack 2 IL_0000: ldnull IL_0001: ldftn ""int Program.F1()"" IL_0007: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_000c: call ""void Program.Report(System.Delegate)"" IL_0011: ldnull IL_0012: ldftn ""ref int Program.F2()"" IL_0018: newobj ""<>F{00000001}<int>..ctor(object, System.IntPtr)"" IL_001d: call ""void Program.Report(System.Delegate)"" IL_0022: ldnull IL_0023: ldftn ""ref readonly int Program.F3()"" IL_0029: newobj ""<>F{00000003}<int>..ctor(object, System.IntPtr)"" IL_002e: call ""void Program.Report(System.Delegate)"" IL_0033: ret }"); } [Fact] public void SynthesizedDelegateTypes_06() { var source = @"using System; class Program { static int i = 0; static int F1() => i; static ref int F2() => ref i; static ref readonly int F3() => ref i; static void Main() { var d1 = F1; var d2 = F2; var d3 = F3; Report(d1); Report(d2); Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32] <>F{00000001}`1[System.Int32] <>F{00000003}`1[System.Int32] "); } [Fact] public void SynthesizedDelegateTypes_07() { var source = @"using System; class Program { static void Main() { Report(int (ref int i) => i); Report((ref int (ref int i) => ref i)); Report((ref readonly int (ref int i) => ref i)); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"<>F{00000001}`2[System.Int32,System.Int32] <>F{00000005}`2[System.Int32,System.Int32] <>F{0000000d}`2[System.Int32,System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 109 (0x6d) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<int, int> Program.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""int Program.<>c.<Main>b__0_0(ref int)"" IL_0014: newobj ""<>F{00000001}<int, int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<int, int> Program.<>c.<>9__0_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>F{00000005}<int, int> Program.<>c.<>9__0_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""ref int Program.<>c.<Main>b__0_1(ref int)"" IL_0038: newobj ""<>F{00000005}<int, int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>F{00000005}<int, int> Program.<>c.<>9__0_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>F{0000000d}<int, int> Program.<>c.<>9__0_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""ref readonly int Program.<>c.<Main>b__0_2(ref int)"" IL_005c: newobj ""<>F{0000000d}<int, int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>F{0000000d}<int, int> Program.<>c.<>9__0_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ret }"); } [Fact] public void SynthesizedDelegateTypes_08() { var source = @"#pragma warning disable 414 using System; class Program { static int i = 0; static void Main() { Report((int i) => { }); Report((out int i) => { i = 0; }); Report((ref int i) => { }); Report((in int i) => { }); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Action`1[System.Int32] <>A{00000002}`1[System.Int32] <>A{00000001}`1[System.Int32] <>A{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 145 (0x91) .maxstack 2 IL_0000: ldsfld ""System.Action<int> Program.<>c.<>9__1_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""void Program.<>c.<Main>b__1_0(int)"" IL_0014: newobj ""System.Action<int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""System.Action<int> Program.<>c.<>9__1_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>A{00000002}<int> Program.<>c.<>9__1_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""void Program.<>c.<Main>b__1_1(out int)"" IL_0038: newobj ""<>A{00000002}<int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>A{00000002}<int> Program.<>c.<>9__1_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>A{00000001}<int> Program.<>c.<>9__1_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""void Program.<>c.<Main>b__1_2(ref int)"" IL_005c: newobj ""<>A{00000001}<int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>A{00000001}<int> Program.<>c.<>9__1_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ldsfld ""<>A{00000003}<int> Program.<>c.<>9__1_3"" IL_0071: dup IL_0072: brtrue.s IL_008b IL_0074: pop IL_0075: ldsfld ""Program.<>c Program.<>c.<>9"" IL_007a: ldftn ""void Program.<>c.<Main>b__1_3(in int)"" IL_0080: newobj ""<>A{00000003}<int>..ctor(object, System.IntPtr)"" IL_0085: dup IL_0086: stsfld ""<>A{00000003}<int> Program.<>c.<>9__1_3"" IL_008b: call ""void Program.Report(System.Delegate)"" IL_0090: ret }"); } [Fact] public void SynthesizedDelegateTypes_09() { var source = @"#pragma warning disable 414 using System; class Program { static void M1(int i) { } static void M2(out int i) { i = 0; } static void M3(ref int i) { } static void M4(in int i) { } static void Main() { Report(M1); Report(M2); Report(M3); Report(M4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Action`1[System.Int32] <>A{00000002}`1[System.Int32] <>A{00000001}`1[System.Int32] <>A{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 69 (0x45) .maxstack 2 IL_0000: ldnull IL_0001: ldftn ""void Program.M1(int)"" IL_0007: newobj ""System.Action<int>..ctor(object, System.IntPtr)"" IL_000c: call ""void Program.Report(System.Delegate)"" IL_0011: ldnull IL_0012: ldftn ""void Program.M2(out int)"" IL_0018: newobj ""<>A{00000002}<int>..ctor(object, System.IntPtr)"" IL_001d: call ""void Program.Report(System.Delegate)"" IL_0022: ldnull IL_0023: ldftn ""void Program.M3(ref int)"" IL_0029: newobj ""<>A{00000001}<int>..ctor(object, System.IntPtr)"" IL_002e: call ""void Program.Report(System.Delegate)"" IL_0033: ldnull IL_0034: ldftn ""void Program.M4(in int)"" IL_003a: newobj ""<>A{00000003}<int>..ctor(object, System.IntPtr)"" IL_003f: call ""void Program.Report(System.Delegate)"" IL_0044: ret }"); } [Fact] public void SynthesizedDelegateTypes_10() { var source = @"#pragma warning disable 414 using System; class Program { static void M1(int i) { } static void M2(out int i) { i = 0; } static void M3(ref int i) { } static void M4(in int i) { } static void Main() { var d1 = M1; var d2 = M2; var d3 = M3; var d4 = M4; Report(d1); Report(d2); Report(d3); Report(d4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Action`1[System.Int32] <>A{00000002}`1[System.Int32] <>A{00000001}`1[System.Int32] <>A{00000003}`1[System.Int32] "); } [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [Fact] public void SynthesizedDelegateTypes_11() { var source = @"class Program { unsafe static void Main() { var d1 = int* () => (int*)42; var d2 = (int* p) => { }; var d3 = delegate*<void> () => default; var d4 = (delegate*<void> d) => { }; } }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (5,18): error CS8917: The delegate type could not be inferred. // var d1 = int* () => (int*)42; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "int* () => (int*)42").WithLocation(5, 18), // (6,18): error CS8917: The delegate type could not be inferred. // var d2 = (int* p) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(int* p) => { }").WithLocation(6, 18), // (7,18): error CS8917: The delegate type could not be inferred. // var d3 = delegate*<void> () => default; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "delegate*<void> () => default").WithLocation(7, 18), // (8,18): error CS8917: The delegate type could not be inferred. // var d4 = (delegate*<void> d) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(delegate*<void> d) => { }").WithLocation(8, 18)); } [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [ConditionalFact(typeof(DesktopOnly))] public void SynthesizedDelegateTypes_12() { var source = @"using System; class Program { static void Main() { var d1 = (TypedReference x) => { }; var d2 = (int x, RuntimeArgumentHandle y) => { }; var d3 = (ArgIterator x) => { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): error CS8917: The delegate type could not be inferred. // var d1 = (TypedReference x) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(TypedReference x) => { }").WithLocation(6, 18), // (7,18): error CS8917: The delegate type could not be inferred. // var d2 = (int x, RuntimeArgumentHandle y) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(int x, RuntimeArgumentHandle y) => { }").WithLocation(7, 18), // (8,18): error CS8917: The delegate type could not be inferred. // var d3 = (ArgIterator x) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(ArgIterator x) => { }").WithLocation(8, 18)); } [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [Fact] public void SynthesizedDelegateTypes_13() { var source = @"ref struct S<T> { } class Program { static void F1(int x, S<int> y) { } static S<T> F2<T>() => throw null; static void Main() { var d1 = F1; var d2 = F2<object>; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,18): error CS8917: The delegate type could not be inferred. // var d1 = F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(8, 18), // (9,18): error CS8917: The delegate type could not be inferred. // var d2 = F2<object>; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2<object>").WithLocation(9, 18)); } [Fact] public void SynthesizedDelegateTypes_14() { var source = @"class Program { static ref void F() { } static void Main() { var d1 = F; var d2 = (ref void () => { }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (3,16): error CS1547: Keyword 'void' cannot be used in this context // static ref void F() { } Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(3, 16), // (6,18): error CS8917: The delegate type could not be inferred. // var d1 = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(6, 18), // (7,19): error CS8917: The delegate type could not be inferred. // var d2 = (ref void () => { }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "ref void () => { }").WithLocation(7, 19), // (7,23): error CS1547: Keyword 'void' cannot be used in this context // var d2 = (ref void () => { }); Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(7, 23)); } [Fact] public void SynthesizedDelegateTypes_15() { var source = @"using System; unsafe class Program { static byte*[] F1() => null; static void F2(byte*[] a) { } static byte*[] F3(ref int i) => null; static void F4(ref byte*[] a) { } static void Main() { Report(int*[] () => null); Report((int*[] a) => { }); Report(int*[] (ref int i) => null); Report((ref int*[] a) => { }); Report(F1); Report(F2); Report(F3); Report(F4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32*[]] System.Action`1[System.Int32*[]] <>F{00000001}`2[System.Int32,System.Int32*[]] <>A{00000001}`1[System.Int32*[]] System.Func`1[System.Byte*[]] System.Action`1[System.Byte*[]] <>F{00000001}`2[System.Int32,System.Byte*[]] <>A{00000001}`1[System.Byte*[]] "); } [Fact] public void SynthesizedDelegateTypes_16() { var source = @"using System; unsafe class Program { static delegate*<ref int>[] F1() => null; static void F2(delegate*<ref int, void>[] a) { } static delegate*<ref int>[] F3(ref int i) => null; static void F4(ref delegate*<ref int, void>[] a) { } static void Main() { Report(delegate*<int, ref int>[] () => null); Report((delegate*<int, ref int, void>[] a) => { }); Report(delegate*<int, ref int>[] (ref int i) => null); Report((ref delegate*<int, ref int, void>[] a) => { }); Report(F1); Report(F2); Report(F3); Report(F4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Func`1[(fnptr)[]] System.Action`1[(fnptr)[]] <>F{00000001}`2[System.Int32,(fnptr)[]] <>A{00000001}`1[(fnptr)[]] System.Func`1[(fnptr)[]] System.Action`1[(fnptr)[]] <>F{00000001}`2[System.Int32,(fnptr)[]] <>A{00000001}`1[(fnptr)[]] "); } [Fact] public void SynthesizedDelegateTypes_17() { var source = @"#nullable enable using System; class Program { static void F1(object x, dynamic y) { } static void F2(IntPtr x, nint y) { } static void F3((int x, int y) t) { } static void F4(object? x, object?[] y) { } static void F5(ref object x, dynamic y) { } static void F6(IntPtr x, ref nint y) { } static void F7(ref (int x, int y) t) { } static void F8(object? x, ref object?[] y) { } static void Main() { Report(F1); Report(F2); Report(F3); Report(F4); Report(F5); Report(F6); Report(F7); Report(F8); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Action`2[System.Object,System.Object] System.Action`2[System.IntPtr,System.IntPtr] System.Action`1[System.ValueTuple`2[System.Int32,System.Int32]] System.Action`2[System.Object,System.Object[]] <>A{00000001}`2[System.Object,System.Object] <>A{00000004}`2[System.IntPtr,System.IntPtr] <>A{00000001}`1[System.ValueTuple`2[System.Int32,System.Int32]] <>A{00000004}`2[System.Object,System.Object[]] "); } private static void VerifyLocalDelegateType(SemanticModel model, VariableDeclaratorSyntax variable, string expectedLocal, string expectedInvokeMethod) { var local = (ILocalSymbol)model.GetDeclaredSymbol(variable)!; Assert.Equal(expectedLocal, local.ToTestDisplayString()); var delegateType = ((INamedTypeSymbol)local.Type); Assert.Equal(Accessibility.Internal, delegateType.DeclaredAccessibility); Assert.Equal(expectedInvokeMethod, delegateType.DelegateInvokeMethod.ToTestDisplayString()); } private static void VerifyExpressionType(SemanticModel model, ExpressionSyntax variable, string expectedSymbol, string expectedType) { var symbol = model.GetSymbolInfo(variable).Symbol; Assert.Equal(expectedSymbol, symbol.ToTestDisplayString()); var type = model.GetTypeInfo(variable).Type; Assert.Equal(expectedType, type.ToTestDisplayString()); } [Fact] public void TaskRunArgument() { var source = @"using System.Threading.Tasks; class Program { static async Task F() { await Task.Run(() => { }); } }"; var verifier = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview); var method = (MethodSymbol)verifier.TestData.GetMethodsByName()["Program.<>c.<F>b__0_0()"].Method; Assert.Equal("void Program.<>c.<F>b__0_0()", method.ToTestDisplayString()); verifier.VerifyIL("Program.<>c.<F>b__0_0()", @"{ // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class DelegateTypeTests : CSharpTestBase { private const string s_utils = @"using System; using System.Linq; static class Utils { internal static string GetDelegateMethodName(this Delegate d) { var method = d.Method; return Concat(GetTypeName(method.DeclaringType), method.Name); } internal static string GetDelegateTypeName(this Delegate d) { return d.GetType().GetTypeName(); } internal static string GetTypeName(this Type type) { if (type.IsArray) { return GetTypeName(type.GetElementType()) + ""[]""; } string typeName = type.Name; int index = typeName.LastIndexOf('`'); if (index >= 0) { typeName = typeName.Substring(0, index); } typeName = Concat(type.Namespace, typeName); if (!type.IsGenericType) { return typeName; } return $""{typeName}<{string.Join("", "", type.GetGenericArguments().Select(GetTypeName))}>""; } private static string Concat(string container, string name) { return string.IsNullOrEmpty(container) ? name : container + ""."" + name; } }"; [Fact] public void LanguageVersion() { var source = @"class Program { static void Main() { System.Delegate d; d = Main; d = () => { }; d = delegate () { }; System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,13): error CS0428: Cannot convert method group 'Main' to non-delegate type 'Delegate'. Did you intend to invoke the method? // d = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.Delegate").WithLocation(6, 13), // (7,13): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // d = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 13), // (8,13): error CS1660: Cannot convert anonymous method to type 'Delegate' because it is not a delegate type // d = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.Delegate").WithLocation(8, 13), // (9,48): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(9, 48)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(); } [Fact] public void MethodGroupConversions() { var source = @"class Program { static void Main() { object o = Main; System.ICloneable c = Main; System.Delegate d = Main; System.MulticastDelegate m = Main; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,20): error CS0428: Cannot convert method group 'Main' to non-delegate type 'object'. Did you intend to invoke the method? // object o = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "object").WithLocation(5, 20), // (6,31): error CS0428: Cannot convert method group 'Main' to non-delegate type 'ICloneable'. Did you intend to invoke the method? // System.ICloneable c = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.ICloneable").WithLocation(6, 31), // (8,38): error CS0428: Cannot convert method group 'Main' to non-delegate type 'MulticastDelegate'. Did you intend to invoke the method? // System.MulticastDelegate m = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.MulticastDelegate").WithLocation(8, 38)); } [Fact] public void LambdaConversions() { var source = @"class Program { static void Main() { object o = () => { }; System.ICloneable c = () => { }; System.Delegate d = () => { }; System.MulticastDelegate m = () => { }; d = x => x; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,20): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // object o = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "object").WithLocation(5, 20), // (6,31): error CS1660: Cannot convert lambda expression to type 'ICloneable' because it is not a delegate type // System.ICloneable c = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.ICloneable").WithLocation(6, 31), // (8,38): error CS1660: Cannot convert lambda expression to type 'MulticastDelegate' because it is not a delegate type // System.MulticastDelegate m = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.MulticastDelegate").WithLocation(8, 38), // (9,13): error CS8917: The delegate type could not be inferred. // d = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(9, 13)); } private static IEnumerable<object?[]> GetMethodGroupData(Func<string, string, DiagnosticDescription[]> getExpectedDiagnostics) { yield return getData("static int F() => 0;", "Program.F", "F", "System.Func<System.Int32>"); yield return getData("static int F() => 0;", "F", "F", "System.Func<System.Int32>"); yield return getData("int F() => 0;", "(new Program()).F", "F", "System.Func<System.Int32>"); yield return getData("static T F<T>() => default;", "Program.F<int>", "F", "System.Func<System.Int32>"); yield return getData("static void F<T>() where T : class { }", "F<object>", "F", "System.Action"); yield return getData("static void F<T>() where T : struct { }", "F<int>", "F", "System.Action"); yield return getData("T F<T>() => default;", "(new Program()).F<int>", "F", "System.Func<System.Int32>"); yield return getData("T F<T>() => default;", "(new Program()).F", "F", null); yield return getData("void F<T>(T t) { }", "(new Program()).F<string>", "F", "System.Action<System.String>"); yield return getData("void F<T>(T t) { }", "(new Program()).F", "F", null); yield return getData("static ref int F() => throw null;", "F", "F", "<>F{00000001}<System.Int32>"); yield return getData("static ref readonly int F() => throw null;", "F", "F", "<>F{00000003}<System.Int32>"); yield return getData("static void F() { }", "F", "F", "System.Action"); yield return getData("static void F(int x, int y) { }", "F", "F", "System.Action<System.Int32, System.Int32>"); yield return getData("static void F(out int x, int y) { x = 0; }", "F", "F", "<>A{00000002}<System.Int32, System.Int32>"); yield return getData("static void F(int x, ref int y) { }", "F", "F", "<>A{00000004}<System.Int32, System.Int32>"); yield return getData("static void F(int x, in int y) { }", "F", "F", "<>A{0000000c}<System.Int32, System.Int32>"); yield return getData("static void F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { }", "F", "F", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("static void F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { }", "F", "F", "<>A<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("static object F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => null;", "F", "F", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Object>"); yield return getData("static object F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => null;", "F", "F", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); object?[] getData(string methodDeclaration, string methodGroupExpression, string methodGroupOnly, string? expectedType) => new object?[] { methodDeclaration, methodGroupExpression, expectedType is null ? getExpectedDiagnostics(methodGroupExpression, methodGroupOnly) : null, expectedType }; } public static IEnumerable<object?[]> GetMethodGroupImplicitConversionData() { return GetMethodGroupData((methodGroupExpression, methodGroupOnly) => { int offset = methodGroupExpression.Length - methodGroupOnly.Length; return new[] { // (6,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(6, 29 + offset) }; }); } [Theory] [MemberData(nameof(GetMethodGroupImplicitConversionData))] public void MethodGroup_ImplicitConversion(string methodDeclaration, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"class Program {{ {methodDeclaration} static void Main() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(d.GetDelegateTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } public static IEnumerable<object?[]> GetMethodGroupExplicitConversionData() { return GetMethodGroupData((methodGroupExpression, methodGroupOnly) => { int offset = methodGroupExpression.Length - methodGroupOnly.Length; return new[] { // (6,20): error CS0030: Cannot convert type 'method' to 'Delegate' // object o = (System.Delegate)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, $"(System.Delegate){methodGroupExpression}").WithArguments("method", "System.Delegate").WithLocation(6, 20) }; }); } [Theory] [MemberData(nameof(GetMethodGroupExplicitConversionData))] public void MethodGroup_ExplicitConversion(string methodDeclaration, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"class Program {{ {methodDeclaration} static void Main() {{ object o = (System.Delegate){methodGroupExpression}; System.Console.Write(o.GetType().GetTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); // https://github.com/dotnet/roslyn/issues/52874: GetTypeInfo() for method group should return inferred delegate type. Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); } public static IEnumerable<object?[]> GetLambdaData() { yield return getData("x => x", null); yield return getData("x => { return x; }", null); yield return getData("x => ref args[0]", null); yield return getData("(x, y) => { }", null); yield return getData("() => 1", "System.Func<System.Int32>"); yield return getData("() => ref args[0]", "<>F{00000001}<System.String>"); yield return getData("() => { }", "System.Action"); yield return getData("(int x, int y) => { }", "System.Action<System.Int32, System.Int32>"); yield return getData("(out int x, int y) => { x = 0; }", "<>A{00000002}<System.Int32, System.Int32>"); yield return getData("(int x, ref int y) => { x = 0; }", "<>A{00000004}<System.Int32, System.Int32>"); yield return getData("(int x, in int y) => { x = 0; }", "<>A{0000000c}<System.Int32, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => { }", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => { }", "<>A<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => _1", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => _1", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Int32>"); yield return getData("static () => 1", "System.Func<System.Int32>"); yield return getData("async () => { await System.Threading.Tasks.Task.Delay(0); }", "System.Func<System.Threading.Tasks.Task>"); yield return getData("static async () => { await System.Threading.Tasks.Task.Delay(0); return 0; }", "System.Func<System.Threading.Tasks.Task<System.Int32>>"); yield return getData("() => Main", null); yield return getData("(int x) => x switch { _ => null }", null); yield return getData("_ => { }", null); yield return getData("_ => _", null); yield return getData("() => throw null", null); yield return getData("x => throw null", null); yield return getData("(int x) => throw null", null); yield return getData("() => { throw null; }", "System.Action"); yield return getData("(int x) => { throw null; }", "System.Action<System.Int32>"); yield return getData("(string s) => { if (s.Length > 0) return s; return null; }", "System.Func<System.String, System.String>"); yield return getData("(string s) => { if (s.Length > 0) return default; return s; }", "System.Func<System.String, System.String>"); yield return getData("(int i) => { if (i > 0) return i; return default; }", "System.Func<System.Int32, System.Int32>"); yield return getData("(int x, short y) => { if (x > 0) return x; return y; }", "System.Func<System.Int32, System.Int16, System.Int32>"); yield return getData("(int x, short y) => { if (x > 0) return y; return x; }", "System.Func<System.Int32, System.Int16, System.Int32>"); yield return getData("object () => default", "System.Func<System.Object>"); yield return getData("void () => { }", "System.Action"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } public static IEnumerable<object?[]> GetAnonymousMethodData() { yield return getData("delegate { }", null); yield return getData("delegate () { return 1; }", "System.Func<System.Int32>"); yield return getData("delegate () { return ref args[0]; }", "<>F{00000001}<System.String>"); yield return getData("delegate () { }", "System.Action"); yield return getData("delegate (int x, int y) { }", "System.Action<System.Int32, System.Int32>"); yield return getData("delegate (out int x, int y) { x = 0; }", "<>A{00000002}<System.Int32, System.Int32>"); yield return getData("delegate (int x, ref int y) { x = 0; }", "<>A{00000004}<System.Int32, System.Int32>"); yield return getData("delegate (int x, in int y) { x = 0; }", "<>A{0000000c}<System.Int32, System.Int32>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { }", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { }", "<>A<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { return _1; }", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { return _1; }", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Int32>"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } [Theory] [MemberData(nameof(GetLambdaData))] [MemberData(nameof(GetAnonymousMethodData))] public void AnonymousFunction_ImplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ System.Delegate d = {anonymousFunction}; System.Console.Write(d.GetDelegateTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedType is null) { comp.VerifyDiagnostics( // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 29)); } else { CompileAndVerify(comp, expectedOutput: expectedType); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<AnonymousFunctionExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(expr); if (expectedType == null) { Assert.Null(typeInfo.Type); } else { Assert.Equal(expectedType, typeInfo.Type.ToTestDisplayString()); } Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } [Theory] [MemberData(nameof(GetLambdaData))] [MemberData(nameof(GetAnonymousMethodData))] public void AnonymousFunction_ExplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ object o = (System.Delegate)({anonymousFunction}); System.Console.Write(o.GetType().GetTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedType is null) { comp.VerifyDiagnostics( // (5,38): error CS8917: The delegate type could not be inferred. // object o = (System.Delegate)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 38)); } else { CompileAndVerify(comp, expectedOutput: expectedType); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(expectedType, typeInfo.ConvertedType?.ToTestDisplayString()); } public static IEnumerable<object?[]> GetExpressionData() { yield return getData("x => x", null); yield return getData("() => 1", "System.Func<System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => _1", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => _1", "<>F<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Int32>"); yield return getData("static () => 1", "System.Func<System.Int32>"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } [Theory] [MemberData(nameof(GetExpressionData))] public void Expression_ImplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ System.Linq.Expressions.Expression e = {anonymousFunction}; }} }}"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); if (expectedType is null) { comp.VerifyDiagnostics( // (5,48): error CS8917: The delegate type could not be inferred. // System.Linq.Expressions.Expression e = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 48)); } else { comp.VerifyDiagnostics(); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<AnonymousFunctionExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(expr); if (expectedType == null) { Assert.Null(typeInfo.Type); } else { Assert.Equal($"System.Linq.Expressions.Expression<{expectedType}>", typeInfo.Type.ToTestDisplayString()); } Assert.Equal("System.Linq.Expressions.Expression", typeInfo.ConvertedType!.ToTestDisplayString()); } [Theory] [MemberData(nameof(GetExpressionData))] public void Expression_ExplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ object o = (System.Linq.Expressions.Expression)({anonymousFunction}); }} }}"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); if (expectedType is null) { comp.VerifyDiagnostics( // (5,57): error CS8917: The delegate type could not be inferred. // object o = (System.Linq.Expressions.Expression)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 57)); } else { comp.VerifyDiagnostics(); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); if (expectedType is null) { Assert.Null(typeInfo.ConvertedType); } else { Assert.Equal($"System.Linq.Expressions.Expression<{expectedType}>", typeInfo.ConvertedType.ToTestDisplayString()); } } /// <summary> /// Should bind and report diagnostics from anonymous method body /// regardless of whether the delegate type can be inferred. /// </summary> [Fact] public void AnonymousMethodBodyErrors() { var source = @"using System; class Program { static void Main() { Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Delegate d1 = (object x1) => { _ = x1.Length; }; Delegate d2 = (ref object x2) => { _ = x2.Length; }; Delegate d3 = delegate (object x3) { _ = x3.Length; }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,23): error CS8917: The delegate type could not be inferred. // Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }").WithLocation(6, 23), // (6,68): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(6, 68), // (7,47): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d1 = (object x1) => { _ = x1.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(7, 47), // (8,51): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d2 = (ref object x2) => { _ = x2.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(8, 51), // (9,53): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d3 = delegate (object x3) { _ = x3.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(9, 53)); } public static IEnumerable<object?[]> GetBaseAndDerivedTypesData() { yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // instance and static // https://github.com/dotnet/roslyn/issues/52701: Assert failure: Unexpected value 'LessDerived' of type 'Microsoft.CodeAnalysis.CSharp.MemberResolutionKind' #if !DEBUG yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "this.F", "F", new[] { // (5,29): error CS0176: Member 'B.F(object)' cannot be accessed with an instance reference; qualify it with a type name instead // System.Delegate d = this.F; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.F").WithArguments("B.F(object)").WithLocation(5, 29) }); // instance and static #endif yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "base.F", "F", null, "System.Action<System.Object>"); // instance and static yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // static and instance yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "this.F", "F", null, "System.Action<System.Object>"); // static and instance yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "base.F", "F"); // static and instance yield return getData("internal void F(object x) { }", "internal static void F() { }", "F", "F"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "B.F", "F", null, "System.Action"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "this.F", "F", null, "System.Action<System.Object>"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "base.F", "F", null, "System.Action<System.Object>"); // instance and static, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "F", "F"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "B.F", "F", null, "System.Action"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "this.F", "F", null, "System.Action<System.Object>"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "base.F", "F"); // static and instance, different number of parameters yield return getData("internal static void F(object x) { }", "private static void F() { }", "F", "F"); // internal and private yield return getData("private static void F(object x) { }", "internal static void F() { }", "F", "F", null, "System.Action"); // internal and private yield return getData("internal abstract void F(object x);", "internal override void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // override yield return getData("internal virtual void F(object x) { }", "internal override void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // override yield return getData("internal void F(object x) { }", "internal void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // hiding yield return getData("internal void F(object x) { }", "internal new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // hiding yield return getData("internal void F(object x) { }", "internal new void F(object y) { }", "F", "F", null, "System.Action<System.Object>"); // different parameter name yield return getData("internal void F(object x) { }", "internal void F(string x) { }", "F", "F"); // different parameter type yield return getData("internal void F(object x) { }", "internal void F(object x, object y) { }", "F", "F"); // different number of parameters yield return getData("internal void F(object x) { }", "internal void F(ref object x) { }", "F", "F"); // different parameter ref kind yield return getData("internal void F(ref object x) { }", "internal void F(object x) { }", "F", "F"); // different parameter ref kind yield return getData("internal abstract object F();", "internal override object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // override yield return getData("internal virtual object F() => throw null;", "internal override object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // override yield return getData("internal object F() => throw null;", "internal object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // hiding yield return getData("internal object F() => throw null;", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // hiding yield return getData("internal string F() => throw null;", "internal new object F() => throw null;", "F", "F"); // different return type yield return getData("internal object F() => throw null;", "internal new ref object F() => throw null;", "F", "F"); // different return ref kind yield return getData("internal ref object F() => throw null;", "internal new object F() => throw null;", "F", "F"); // different return ref kind yield return getData("internal void F(object x) { }", "internal new void F(dynamic x) { }", "F", "F", null, "System.Action<System.Object>"); // object/dynamic yield return getData("internal dynamic F() => throw null;", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // object/dynamic yield return getData("internal void F((object, int) x) { }", "internal new void F((object a, int b) x) { }", "F", "F", null, "System.Action<System.ValueTuple<System.Object, System.Int32>>"); // tuple names yield return getData("internal (object a, int b) F() => throw null;", "internal new (object, int) F() => throw null;", "F", "F", null, "System.Func<System.ValueTuple<System.Object, System.Int32>>"); // tuple names yield return getData("internal void F(System.IntPtr x) { }", "internal new void F(nint x) { }", "F", "F", null, "System.Action<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal nint F() => throw null;", "internal new System.IntPtr F() => throw null;", "F", "F", null, "System.Func<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal void F(object x) { }", @"#nullable enable internal new void F(object? x) { } #nullable disable", "F", "F", null, "System.Action<System.Object>"); // different nullability yield return getData( @"#nullable enable internal object? F() => throw null!; #nullable disable", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // different nullability yield return getData("internal void F() { }", "internal void F<T>() { }", "F", "F"); // different arity yield return getData("internal void F() { }", "internal void F<T>() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F() { }", "F", "F"); // different arity yield return getData("internal void F<T>() { }", "internal void F() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F<T, U>() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F<T, U>() { }", "F<int, object>", "F<int, object>", null, "System.Action"); // different arity yield return getData("internal void F<T>(T t) { }", "internal new void F<U>(U u) { }", "F<int>", "F<int>", null, "System.Action<System.Int32>"); // different type parameter names yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) { }", "F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) { }", "internal new void F<T>(T t) where T : class { }", "F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) { }", "internal new void F<T>(T t) where T : class { }", "base.F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) where T : struct { }", "F<int>", "F<int>", null, "System.Action<System.Int32>"); // different type parameter constraints // https://github.com/dotnet/roslyn/issues/52701: Assert failure: Unexpected value 'LessDerived' of type 'Microsoft.CodeAnalysis.CSharp.MemberResolutionKind' #if !DEBUG yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) where T : struct { }", "F<object>", "F<object>", new[] { // (5,29): error CS0453: The type 'object' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B.F<T>(T)' // System.Delegate d = F<object>; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<object>").WithArguments("B.F<T>(T)", "T", "object").WithLocation(5, 29) }); // different type parameter constraints #endif static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(5, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedType }; } } [Theory] [MemberData(nameof(GetBaseAndDerivedTypesData))] public void MethodGroup_BaseAndDerivedTypes(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"partial class B {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(d.GetDelegateTypeName()); }} static void Main() {{ new B().M(); }} }} abstract class A {{ {methodA} }} partial class B : A {{ {methodB} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } public static IEnumerable<object?[]> GetExtensionMethodsSameScopeData() { yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "string.Empty.F", "F", null, "B.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different number of parameters yield return getData("internal static void F(this object x, object y) { }", "internal static void F(this object x, ref object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static void F(this object x, ref object y) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static object F(this object x) => throw null;", "internal static ref object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static ref object F(this object x) => throw null;", "internal static object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F", "F"); // different arity yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F<int>", "F<int>", null, "B.F", "System.Action<System.Int32>"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F", "F"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F<int>", "F<int>", null, "A.F", "System.Action"); // different arity yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) { }", "this.F<object>", "F<object>", new[] { // (5,29): error CS0121: The call is ambiguous between the following methods or properties: 'A.F<T>(T)' and 'B.F<T>(T)' // System.Delegate d = this.F<object>; Diagnostic(ErrorCode.ERR_AmbigCall, "this.F<object>").WithArguments("A.F<T>(T)", "B.F<T>(T)").WithLocation(5, 29) }); // different type parameter constraints yield return getData("internal static void F<T>(this T t) { }", "internal static void F<T>(this T t) where T : class { }", "this.F<object>", "F<object>", new[] { // (5,29): error CS0121: The call is ambiguous between the following methods or properties: 'A.F<T>(T)' and 'B.F<T>(T)' // System.Delegate d = this.F<object>; Diagnostic(ErrorCode.ERR_AmbigCall, "this.F<object>").WithArguments("A.F<T>(T)", "B.F<T>(T)").WithLocation(5, 29) }); // different type parameter constraints yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) where T : struct { }", "this.F<int>", "F<int>"); // different type parameter constraints static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedMethod = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(5, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedMethod, expectedType }; } } [Theory] [MemberData(nameof(GetExtensionMethodsSameScopeData))] public void MethodGroup_ExtensionMethodsSameScope(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedMethod, string? expectedType) { var source = $@"class Program {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(""{{0}}: {{1}}"", d.GetDelegateMethodName(), d.GetDelegateTypeName()); }} static void Main() {{ new Program().M(); }} }} static class A {{ {methodA} }} static class B {{ {methodB} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: $"{expectedMethod}: {expectedType}"); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); // https://github.com/dotnet/roslyn/issues/52870: GetSymbolInfo() should return resolved method from method group. Assert.Null(symbolInfo.Symbol); } public static IEnumerable<object?[]> GetExtensionMethodsDifferentScopeData() { yield return getData("internal static void F(this object x) { }", "internal static void F(this object x) { }", "this.F", "F", null, "A.F", "System.Action"); // hiding yield return getData("internal static void F(this object x) { }", "internal static void F(this object y) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter name yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "string.Empty.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different number of parameters yield return getData("internal static void F(this object x, object y) { }", "internal static void F(this object x, ref object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static void F(this object x, ref object y) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static object F(this object x) => throw null;", "internal static ref object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static ref object F(this object x) => throw null;", "internal static object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static void F(this object x, System.IntPtr y) { }", "internal static void F(this object x, nint y) { }", "this.F", "F", null, "A.F", "System.Action<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal static nint F(this object x) => throw null;", "internal static System.IntPtr F(this object x) => throw null;", "this.F", "F", null, "A.F", "System.Func<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F", "F"); // different arity yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F<int>", "F<int>", null, "N.B.F", "System.Action<System.Int32>"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F", "F"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F<int>", "F<int>", null, "A.F", "System.Action"); // different arity yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) { }", "this.F<object>", "F<object>", null, "A.F", "System.Action"); // different type parameter constraints yield return getData("internal static void F<T>(this T t) { }", "internal static void F<T>(this T t) where T : class { }", "this.F<object>", "F<object>", null, "A.F", "System.Action"); // different type parameter constraints yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) where T : struct { }", "this.F<int>", "F<int>"); // different type parameter constraints static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedMethod = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (6,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(6, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedMethod, expectedType }; } } [Theory] [MemberData(nameof(GetExtensionMethodsDifferentScopeData))] public void MethodGroup_ExtensionMethodsDifferentScope(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedMethod, string? expectedType) { var source = $@"using N; class Program {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(""{{0}}: {{1}}"", d.GetDelegateMethodName(), d.GetDelegateTypeName()); }} static void Main() {{ new Program().M(); }} }} static class A {{ {methodA} }} namespace N {{ static class B {{ {methodB} }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: $"{expectedMethod}: {expectedType}"); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); // https://github.com/dotnet/roslyn/issues/52870: GetSymbolInfo() should return resolved method from method group. Assert.Null(symbolInfo.Symbol); } [Fact] public void InstanceMethods_01() { var source = @"using System; class Program { object F1() => null; void F2(object x, int y) { } void F() { Delegate d1 = F1; Delegate d2 = this.F2; Console.WriteLine(""{0}, {1}"", d1.GetDelegateTypeName(), d2.GetDelegateTypeName()); } static void Main() { new Program().F(); } }"; CompileAndVerify(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, expectedOutput: "System.Func<System.Object>, System.Action<System.Object, System.Int32>"); } [Fact] public void InstanceMethods_02() { var source = @"using System; class A { protected virtual void F() { Console.WriteLine(nameof(A)); } } class B : A { protected override void F() { Console.WriteLine(nameof(B)); } static void Invoke(Delegate d) { d.DynamicInvoke(); } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } static void Main() { new B().M(); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"B B A"); } [Fact] public void InstanceMethods_03() { var source = @"using System; class A { protected void F() { Console.WriteLine(nameof(A)); } } class B : A { protected new void F() { Console.WriteLine(nameof(B)); } static void Invoke(Delegate d) { d.DynamicInvoke(); } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } static void Main() { new B().M(); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"B B A"); } [Fact] public void InstanceMethods_04() { var source = @"class Program { T F<T>() => default; static void Main() { var p = new Program(); System.Delegate d = p.F; object o = (System.Delegate)p.F; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (7,31): error CS8917: The delegate type could not be inferred. // System.Delegate d = p.F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 31), // (8,20): error CS0030: Cannot convert type 'method' to 'Delegate' // object o = (System.Delegate)p.F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(System.Delegate)p.F").WithArguments("method", "System.Delegate").WithLocation(8, 20)); } [Fact] public void MethodGroup_Inaccessible() { var source = @"using System; class A { private static void F() { } internal static void F(object o) { } } class B { static void Main() { Delegate d = A.F; Console.WriteLine(d.GetDelegateTypeName()); } }"; CompileAndVerify(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, expectedOutput: "System.Action<System.Object>"); } [Fact] public void MethodGroup_IncorrectArity() { var source = @"class Program { static void F0(object o) { } static void F0<T>(object o) { } static void F1(object o) { } static void F1<T, U>(object o) { } static void F2<T>(object o) { } static void F2<T, U>(object o) { } static void Main() { System.Delegate d; d = F0<int, object>; d = F1<int>; d = F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (12,13): error CS0308: The non-generic method 'Program.F0(object)' cannot be used with type arguments // d = F0<int, object>; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "F0<int, object>").WithArguments("Program.F0(object)", "method").WithLocation(12, 13), // (13,13): error CS0308: The non-generic method 'Program.F1(object)' cannot be used with type arguments // d = F1<int>; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "F1<int>").WithArguments("Program.F1(object)", "method").WithLocation(13, 13), // (14,13): error CS8917: The delegate type could not be inferred. // d = F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(14, 13)); } [Fact] public void ExtensionMethods_01() { var source = @"static class E { internal static void F1(this object x, int y) { } internal static void F2(this object x) { } } class Program { void F2(int x) { } static void Main() { System.Delegate d; var p = new Program(); d = p.F1; d = p.F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (14,15): error CS8917: The delegate type could not be inferred. // d = p.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(14, 15)); } [Fact] public void ExtensionMethods_02() { var source = @"using System; static class E { internal static void F(this System.Type x, int y) { } internal static void F(this string x) { } } class Program { static void Main() { Delegate d1 = typeof(Program).F; Delegate d2 = """".F; Console.WriteLine(""{0}, {1}"", d1.GetDelegateTypeName(), d2.GetDelegateTypeName()); } }"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "System.Action<System.Int32>, System.Action"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Select(d => d.Initializer!.Value).ToArray(); Assert.Equal(2, exprs.Length); foreach (var expr in exprs) { var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } } [Fact] public void ExtensionMethods_03() { var source = @"using N; namespace N { static class E1 { internal static void F1(this object x, int y) { } internal static void F2(this object x, int y) { } internal static void F2(this object x) { } internal static void F3(this object x) { } } } static class E2 { internal static void F1(this object x) { } } class Program { static void Main() { System.Delegate d; var p = new Program(); d = p.F1; d = p.F2; d = p.F3; d = E1.F1; d = E2.F1; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (22,15): error CS8917: The delegate type could not be inferred. // d = p.F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(22, 15), // (23,15): error CS8917: The delegate type could not be inferred. // d = p.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(23, 15)); } [Fact] public void ExtensionMethods_04() { var source = @"static class E { internal static void F1(this object x, int y) { } } static class Program { static void F2(this object x) { } static void Main() { System.Delegate d; d = E.F1; d = F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [Fact] public void ExtensionMethods_05() { var source = @"using System; static class E { internal static void F(this A a) { } } class A { } class B : A { static void Invoke(Delegate d) { } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (14,16): error CS0103: The name 'F' does not exist in the current context // Invoke(F); Diagnostic(ErrorCode.ERR_NameNotInContext, "F").WithArguments("F").WithLocation(14, 16), // (16,21): error CS0117: 'A' does not contain a definition for 'F' // Invoke(base.F); Diagnostic(ErrorCode.ERR_NoSuchMember, "F").WithArguments("A", "F").WithLocation(16, 21)); } [Fact] public void ExtensionMethods_06() { var source = @"static class E { internal static void F1<T>(this object x, T y) { } internal static void F2<T, U>(this T t) { } } class Program { static void F<T>(T t) where T : class { System.Delegate d; d = t.F1; d = t.F2; d = t.F1<int>; d = t.F1<T>; d = t.F2<T, object>; d = t.F2<object, T>; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (11,15): error CS8917: The delegate type could not be inferred. // d = t.F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(11, 15), // (12,15): error CS8917: The delegate type could not be inferred. // d = t.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(12, 15)); } /// <summary> /// Method group with dynamic receiver does not use method group conversion. /// </summary> [Fact] public void DynamicReceiver() { var source = @"using System; class Program { void F() { } static void Main() { dynamic d = new Program(); object obj; try { obj = d.F; } catch (Exception e) { obj = e; } Console.WriteLine(obj.GetType().FullName); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, references: new[] { CSharpRef }, expectedOutput: "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException"); } // System.Func<> and System.Action<> cannot be used as the delegate type // when the parameters or return type are not valid type arguments. [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [Fact] public void InvalidTypeArguments() { var source = @"unsafe class Program { static int* F() => throw null; static void Main() { System.Delegate d; d = F; d = (int x, int* y) => { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (7,13): error CS8917: The delegate type could not be inferred. // d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 13), // (8,13): error CS8917: The delegate type could not be inferred. // d = (int x, int* y) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(int x, int* y) => { }").WithLocation(8, 13)); } [Fact] public void GenericDelegateType() { var source = @"using System; class Program { static void Main() { Delegate d = F<int>(); Console.WriteLine(d.GetDelegateTypeName()); } unsafe static Delegate F<T>() { return (T t, int* p) => { }; } }"; // When we synthesize delegate types with parameter types (such as int*) that cannot // be used as type arguments, run the program to report the actual delegate type. var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (11,16): error CS8917: The delegate type could not be inferred. // return (T t, int* p) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(T t, int* p) => { }").WithLocation(11, 16)); } /// <summary> /// Custom modifiers should not affect delegate signature. /// </summary> [Fact] public void CustomModifiers_01() { var sourceA = @".class public A { .method public static void F1(object modopt(int32) x) { ldnull throw } .method public static object modopt(int32) F2() { ldnull throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using System; class B { static void Report(Delegate d) { Console.WriteLine(d.GetDelegateTypeName()); } static void Main() { Report(A.F1); Report(A.F2); } }"; var comp = CreateCompilation(new[] { sourceB, s_utils }, new[] { refA }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"System.Action<System.Object> System.Func<System.Object>"); } /// <summary> /// Custom modifiers should not affect delegate signature. /// </summary> [Fact] public void CustomModifiers_02() { var sourceA = @".class public A { .method public static void F1(object modreq(int32) x) { ldnull throw } .method public static object modreq(int32) F2() { ldnull throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using System; class B { static void Report(Delegate d) { Console.WriteLine(d.GetDelegateTypeName()); } static void Main() { Report(A.F1); Report(A.F2); } }"; var comp = CreateCompilation(new[] { sourceB, s_utils }, new[] { refA }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (10,16): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // Report(A.F1); Diagnostic(ErrorCode.ERR_BadArgType, "A.F1").WithArguments("1", "method group", "System.Delegate").WithLocation(10, 16), // (11,16): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // Report(A.F2); Diagnostic(ErrorCode.ERR_BadArgType, "A.F2").WithArguments("1", "method group", "System.Delegate").WithLocation(11, 16)); } [Fact] public void UnmanagedCallersOnlyAttribute_01() { var source = @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; class Program { static void Main() { Delegate d = F; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] static void F() { } }"; var comp = CreateCompilation(new[] { source, UnmanagedCallersOnlyAttributeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,22): error CS8902: 'Program.F()' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method. // Delegate d = F; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate, "F").WithArguments("Program.F()").WithLocation(8, 22)); } [Fact] public void UnmanagedCallersOnlyAttribute_02() { var source = @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; class Program { static void Main() { Delegate d = new S().F; } } struct S { } static class E1 { [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] public static void F(this S s) { } } static class E2 { [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] public static void F(this S s) { } }"; var comp = CreateCompilation(new[] { source, UnmanagedCallersOnlyAttributeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,22): error CS0121: The call is ambiguous between the following methods or properties: 'E1.F(S)' and 'E2.F(S)' // Delegate d = new S().F; Diagnostic(ErrorCode.ERR_AmbigCall, "new S().F").WithArguments("E1.F(S)", "E2.F(S)").WithLocation(8, 22)); } [Fact] public void SystemActionAndFunc_Missing() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Delegate d; d = Main; d = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,13): error CS0518: Predefined type 'System.Action' is not defined or imported // d = Main; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Main").WithArguments("System.Action").WithLocation(6, 13), // (6,13): error CS0518: Predefined type 'System.Action' is not defined or imported // d = Main; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Main").WithArguments("System.Action").WithLocation(6, 13), // (6,13): error CS8917: The delegate type could not be inferred. // d = Main; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "Main").WithLocation(6, 13), // (7,13): error CS0518: Predefined type 'System.Func`1' is not defined or imported // d = () => 1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "() => 1").WithArguments("System.Func`1").WithLocation(7, 13)); } private static MetadataReference GetCorlibWithInvalidActionAndFuncOfT() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Attribute extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Runtime.CompilerServices.RequiredAttributeAttribute extends System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class System.Type t) cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Action`1<T> extends System.MulticastDelegate { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance void Invoke(!T t) { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } }"; return CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); } [Fact] public void SystemActionAndFunc_UseSiteErrors() { var refA = GetCorlibWithInvalidActionAndFuncOfT(); var sourceB = @"class Program { static void F(object o) { } static void Main() { System.Delegate d; d = F; d = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (9,13): error CS0648: 'Action<T>' is a type not supported by the language // d = F; Diagnostic(ErrorCode.ERR_BogusType, "F").WithArguments("System.Action<T>").WithLocation(9, 13), // (9,13): error CS0648: 'Action<T>' is a type not supported by the language // d = F; Diagnostic(ErrorCode.ERR_BogusType, "F").WithArguments("System.Action<T>").WithLocation(9, 13), // (10,13): error CS0648: 'Func<T>' is a type not supported by the language // d = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Func<T>").WithLocation(10, 13)); } [Fact] public void SystemLinqExpressionsExpression_Missing() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } } .class public abstract System.Linq.Expressions.Expression extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,48): error CS0518: Predefined type 'System.Linq.Expressions.Expression`1' is not defined or imported // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "() => 1").WithArguments("System.Linq.Expressions.Expression`1").WithLocation(5, 48)); } [Fact] public void SystemLinqExpressionsExpression_UseSiteErrors() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Attribute extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Runtime.CompilerServices.RequiredAttributeAttribute extends System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class System.Type t) cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } } .class public abstract System.Linq.Expressions.Expression extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Linq.Expressions.LambdaExpression extends System.Linq.Expressions.Expression { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Linq.Expressions.Expression`1<T> extends System.Linq.Expressions.LambdaExpression { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,48): error CS0648: 'Expression<T>' is a type not supported by the language // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Linq.Expressions.Expression<T>").WithLocation(5, 48)); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_01() { var source = @"using System; class Program { static void M<T>(T t) { Console.WriteLine(""M<T>(T t)""); } static void M(Action<string> a) { Console.WriteLine(""M(Action<string> a)""); } static void F(object o) { } static void Main() { M(F); // C#9: M(Action<string>) } }"; var expectedOutput = @"M(Action<string> a)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: expectedOutput); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_02() { var source = @"using System; class Program { static void Main() { var c = new C(); c.M(Main); // C#9: E.M(object x, Action y) c.M(() => { }); // C#9: E.M(object x, Action y) } } class C { public void M(object y) { Console.WriteLine(""C.M(object y)""); } } static class E { public static void M(this object x, Action y) { Console.WriteLine(""E.M(object x, Action y)""); } }"; var expectedOutput = @"E.M(object x, Action y) E.M(object x, Action y) "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: expectedOutput); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_03() { var source = @"using System; class Program { static void Main() { var c = new C(); c.M(Main); // C#9: E.M(object x, Action y) c.M(() => { }); // C#9: E.M(object x, Action y) } } class C { public void M(Delegate d) { Console.WriteLine(""C.M""); } } static class E { public static void M(this object o, Action a) { Console.WriteLine(""E.M""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M E.M "); // Breaking change from C#9 which binds to E.M. CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"C.M C.M "); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { var c = new C(); c.M(() => 1); } } class C { public void M(Expression e) { Console.WriteLine(""C.M""); } } static class E { public static void M(this object o, Func<int> a) { Console.WriteLine(""E.M""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M"); // Breaking change from C#9 which binds to E.M. CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"C.M"); } [Fact] public void OverloadResolution_05() { var source = @"using System; class Program { static void Report(string name) { Console.WriteLine(name); } static void FA(Delegate d) { Report(""FA(Delegate)""); } static void FA(Action d) { Report(""FA(Action)""); } static void FB(Delegate d) { Report(""FB(Delegate)""); } static void FB(Func<int> d) { Report(""FB(Func<int>)""); } static void F1() { } static int F2() => 0; static void Main() { FA(F1); FA(F2); FB(F1); FB(F2); FA(() => { }); FA(() => 0); FB(() => { }); FB(() => 0); FA(delegate () { }); FA(delegate () { return 0; }); FB(delegate () { }); FB(delegate () { return 0; }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (14,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // FA(F2); Diagnostic(ErrorCode.ERR_BadArgType, "F2").WithArguments("1", "method group", "System.Delegate").WithLocation(14, 12), // (15,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // FB(F1); Diagnostic(ErrorCode.ERR_BadArgType, "F1").WithArguments("1", "method group", "System.Delegate").WithLocation(15, 12), // (18,18): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // FA(() => 0); Diagnostic(ErrorCode.ERR_IllegalStatement, "0").WithLocation(18, 18), // (19,15): error CS1643: Not all code paths return a value in lambda expression of type 'Func<int>' // FB(() => { }); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "=>").WithArguments("lambda expression", "System.Func<int>").WithLocation(19, 15), // (22,26): error CS8030: Anonymous function converted to a void returning delegate cannot return a value // FA(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(22, 26), // (23,12): error CS1643: Not all code paths return a value in anonymous method of type 'Func<int>' // FB(delegate () { }); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "delegate").WithArguments("anonymous method", "System.Func<int>").WithLocation(23, 12)); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) "); } [Fact] public void OverloadResolution_06() { var source = @"using System; using System.Linq.Expressions; class Program { static void Report(string name, Expression e) { Console.WriteLine(""{0}: {1}"", name, e); } static void F(Expression e) { Report(""F(Expression)"", e); } static void F(Expression<Func<int>> e) { Report(""F(Expression<Func<int>>)"", e); } static void Main() { F(() => 0); F(() => string.Empty); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,17): error CS0029: Cannot implicitly convert type 'string' to 'int' // F(() => string.Empty); Diagnostic(ErrorCode.ERR_NoImplicitConv, "string.Empty").WithArguments("string", "int").WithLocation(11, 17), // (11,17): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // F(() => string.Empty); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "string.Empty").WithArguments("lambda expression").WithLocation(11, 17)); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"F(Expression<Func<int>>): () => 0 F(Expression): () => String.Empty "); } [Fact] public void OverloadResolution_07() { var source = @"using System; using System.Linq.Expressions; class Program { static void F(Expression e) { } static void F(Expression<Func<int>> e) { } static void Main() { F(delegate () { return 0; }); F(delegate () { return string.Empty; }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,11): error CS1660: Cannot convert anonymous method to type 'Expression' because it is not a delegate type // F(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return 0; }").WithArguments("anonymous method", "System.Linq.Expressions.Expression").WithLocation(9, 11), // (10,11): error CS1660: Cannot convert anonymous method to type 'Expression' because it is not a delegate type // F(delegate () { return string.Empty; }); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { return string.Empty; }").WithArguments("anonymous method", "System.Linq.Expressions.Expression").WithLocation(10, 11)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (9,11): error CS1946: An anonymous method expression cannot be converted to an expression tree // F(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return 0; }").WithLocation(9, 11), // (10,11): error CS1946: An anonymous method expression cannot be converted to an expression tree // F(delegate () { return string.Empty; }); Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return string.Empty; }").WithLocation(10, 11)); } [WorkItem(55319, "https://github.com/dotnet/roslyn/issues/55319")] [Fact] public void OverloadResolution_08() { var source = @"using System; using static System.Console; class C { static void Main() { var c = new C(); c.F(x => x); c.F((int x) => x); } void F(Delegate d) => Write(""instance, ""); } static class Extensions { public static void F(this C c, Func<int, int> f) => Write(""extension, ""); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "extension, extension, "); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: "extension, instance, "); CompileAndVerify(source, expectedOutput: "extension, instance, "); } [WorkItem(55319, "https://github.com/dotnet/roslyn/issues/55319")] [Fact] public void OverloadResolution_09() { var source = @"using System; using System.Linq.Expressions; using static System.Console; class C { static void Main() { var c = new C(); c.F(x => x); c.F((int x) => x); } void F(Expression e) => Write(""instance, ""); } static class Extensions { public static void F(this C c, Expression<Func<int, int>> e) => Write(""extension, ""); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "extension, extension, "); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: "extension, instance, "); CompileAndVerify(source, expectedOutput: "extension, instance, "); } [WorkItem(55319, "https://github.com/dotnet/roslyn/issues/55319")] [Fact] public void OverloadResolution_10() { var source = @"using System; using static System.Console; class C { static object M1(object o) => o; static int M1(int i) => i; static int M2(int i) => i; static void Main() { var c = new C(); c.F(M1); c.F(M2); } void F(Delegate d) => Write(""instance, ""); } static class Extensions { public static void F(this C c, Func<int, int> f) => Write(""extension, ""); }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "extension, extension, "); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: "extension, instance, "); CompileAndVerify(source, expectedOutput: "extension, instance, "); } [Fact] public void OverloadResolution_11() { var source = @"using System; using System.Linq.Expressions; class C { static object M1(object o) => o; static int M1(int i) => i; static void Main() { F1(x => x); F1(M1); F2(x => x); } static void F1(Delegate d) { } static void F2(Expression e) { } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,12): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // F1(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Delegate").WithLocation(9, 12), // (10,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // F1(M1); Diagnostic(ErrorCode.ERR_BadArgType, "M1").WithArguments("1", "method group", "System.Delegate").WithLocation(10, 12), // (11,12): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // F2(x => x); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(11, 12)); var expectedDiagnostics10AndLater = new[] { // (9,12): error CS8917: The delegate type could not be inferred. // F1(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(9, 12), // (10,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // F1(M1); Diagnostic(ErrorCode.ERR_BadArgType, "M1").WithArguments("1", "method group", "System.Delegate").WithLocation(10, 12), // (11,12): error CS8917: The delegate type could not be inferred. // F2(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(11, 12) }; comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); comp = CreateCompilation(source); comp.VerifyDiagnostics(expectedDiagnostics10AndLater); } [Fact] public void ImplicitlyTypedVariables_01() { var source = @"using System; class Program { static void Main() { var d1 = Main; Report(d1); var d2 = () => { }; Report(d2); var d3 = delegate () { }; Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetDelegateTypeName()); }"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d1 = Main; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "Main").WithArguments("inferred delegate type", "10.0").WithLocation(6, 18), // (8,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d2 = () => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => { }").WithArguments("inferred delegate type", "10.0").WithLocation(8, 18), // (10,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "delegate () { }").WithArguments("inferred delegate type", "10.0").WithLocation(10, 18)); comp = CreateCompilation(new[] { source, s_utils }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Action System.Action System.Action"); verifier.VerifyIL("Program.Main", @"{ // Code size 100 (0x64) .maxstack 2 .locals init (System.Action V_0, //d1 System.Action V_1, //d2 System.Action V_2) //d3 IL_0000: nop IL_0001: ldnull IL_0002: ldftn ""void Program.Main()"" IL_0008: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_000d: stloc.0 IL_000e: ldloc.0 IL_000f: call ""void Program.Report(System.Delegate)"" IL_0014: nop IL_0015: ldsfld ""System.Action Program.<>c.<>9__0_0"" IL_001a: dup IL_001b: brtrue.s IL_0034 IL_001d: pop IL_001e: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0023: ldftn ""void Program.<>c.<Main>b__0_0()"" IL_0029: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_002e: dup IL_002f: stsfld ""System.Action Program.<>c.<>9__0_0"" IL_0034: stloc.1 IL_0035: ldloc.1 IL_0036: call ""void Program.Report(System.Delegate)"" IL_003b: nop IL_003c: ldsfld ""System.Action Program.<>c.<>9__0_1"" IL_0041: dup IL_0042: brtrue.s IL_005b IL_0044: pop IL_0045: ldsfld ""Program.<>c Program.<>c.<>9"" IL_004a: ldftn ""void Program.<>c.<Main>b__0_1()"" IL_0050: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0055: dup IL_0056: stsfld ""System.Action Program.<>c.<>9__0_1"" IL_005b: stloc.2 IL_005c: ldloc.2 IL_005d: call ""void Program.Report(System.Delegate)"" IL_0062: nop IL_0063: ret }"); } [Fact] public void ImplicitlyTypedVariables_02() { var source = @"var d1 = object.ReferenceEquals; var d2 = () => { }; var d3 = delegate () { }; "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9.WithKind(SourceCodeKind.Script)); comp.VerifyDiagnostics( // (1,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d1 = object.ReferenceEquals; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object.ReferenceEquals").WithArguments("inferred delegate type", "10.0").WithLocation(1, 10), // (2,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d2 = () => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => { }").WithArguments("inferred delegate type", "10.0").WithLocation(2, 10), // (3,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "delegate () { }").WithArguments("inferred delegate type", "10.0").WithLocation(3, 10)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10.WithKind(SourceCodeKind.Script)); comp.VerifyDiagnostics(); } [Fact] public void ImplicitlyTypedVariables_03() { var source = @"class Program { static void Main() { ref var d1 = Main; ref var d2 = () => { }; ref var d3 = delegate () { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d1 = Main; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d1 = Main").WithLocation(5, 17), // (5,22): error CS1657: Cannot use 'Main' as a ref or out value because it is a 'method group' // ref var d1 = Main; Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "Main").WithArguments("Main", "method group").WithLocation(5, 22), // (6,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d2 = () => { }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d2 = () => { }").WithLocation(6, 17), // (6,22): error CS1510: A ref or out value must be an assignable variable // ref var d2 = () => { }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "() => { }").WithLocation(6, 22), // (7,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d3 = delegate () { }").WithLocation(7, 17), // (7,22): error CS1510: A ref or out value must be an assignable variable // ref var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "delegate () { }").WithLocation(7, 22)); } [Fact] public void ImplicitlyTypedVariables_04() { var source = @"class Program { static void Main() { using var d1 = Main; using var d2 = () => { }; using var d3 = delegate () { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d1 = Main; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d1 = Main;").WithArguments("System.Action").WithLocation(5, 9), // (6,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d2 = () => { }; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d2 = () => { };").WithArguments("System.Action").WithLocation(6, 9), // (7,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d3 = delegate () { };").WithArguments("System.Action").WithLocation(7, 9)); } [Fact] public void ImplicitlyTypedVariables_05() { var source = @"class Program { static void Main() { foreach (var d1 in Main) { } foreach (var d2 in () => { }) { } foreach (var d3 in delegate () { }) { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,28): error CS0446: Foreach cannot operate on a 'method group'. Did you intend to invoke the 'method group'? // foreach (var d1 in Main) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "Main").WithArguments("method group").WithLocation(5, 28), // (6,28): error CS0446: Foreach cannot operate on a 'lambda expression'. Did you intend to invoke the 'lambda expression'? // foreach (var d2 in () => { }) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "() => { }").WithArguments("lambda expression").WithLocation(6, 28), // (7,28): error CS0446: Foreach cannot operate on a 'anonymous method'. Did you intend to invoke the 'anonymous method'? // foreach (var d3 in delegate () { }) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "delegate () { }").WithArguments("anonymous method").WithLocation(7, 28)); } [Fact] public void ImplicitlyTypedVariables_06() { var source = @"using System; class Program { static void Main() { Func<int> f; var d1 = Main; f = d1; var d2 = object (int x) => x; f = d2; var d3 = delegate () { return string.Empty; }; f = d3; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,13): error CS0029: Cannot implicitly convert type 'System.Action' to 'System.Func<int>' // f = d1; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d1").WithArguments("System.Action", "System.Func<int>").WithLocation(8, 13), // (10,13): error CS0029: Cannot implicitly convert type 'System.Func<int, object>' to 'System.Func<int>' // f = d2; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d2").WithArguments("System.Func<int, object>", "System.Func<int>").WithLocation(10, 13), // (12,13): error CS0029: Cannot implicitly convert type 'System.Func<string>' to 'System.Func<int>' // f = d3; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d3").WithArguments("System.Func<string>", "System.Func<int>").WithLocation(12, 13)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var variables = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(v => v.Initializer != null); var expectedInfo = new (string?, string?, string?)[] { ("System.Action d1", null, "System.Action"), ("System.Func<System.Int32, System.Object> d2", null, "System.Func<System.Int32, System.Object>"), ("System.Func<System.String> d3", null, "System.Func<System.String>"), }; AssertEx.Equal(expectedInfo, variables.Select(v => getVariableInfo(model, v))); static (string?, string?, string?) getVariableInfo(SemanticModel model, VariableDeclaratorSyntax variable) { var symbol = model.GetDeclaredSymbol(variable); var typeInfo = model.GetTypeInfo(variable.Initializer!.Value); return (symbol?.ToTestDisplayString(), typeInfo.Type?.ToTestDisplayString(), typeInfo.ConvertedType?.ToTestDisplayString()); } } [Fact] public void ImplicitlyTypedVariables_07() { var source = @"class Program { static void Main() { var t = (Main, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,13): error CS0815: Cannot assign (method group, lambda expression) to an implicitly-typed variable // var t = (Main, () => { }); Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "t = (Main, () => { })").WithArguments("(method group, lambda expression)").WithLocation(5, 13)); } [Fact] public void ImplicitlyTypedVariables_08() { var source = @"class Program { static void Main() { (var x1, var y1) = Main; var (x2, y2) = () => { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(5, 14), // (5,22): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y1'. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y1").WithArguments("y1").WithLocation(5, 22), // (5,28): error CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "Main").WithLocation(5, 28), // (6,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x2'. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x2").WithArguments("x2").WithLocation(6, 14), // (6,18): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y2'. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y2").WithArguments("y2").WithLocation(6, 18), // (6,24): error CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "() => { }").WithLocation(6, 24)); } [Fact] public void ImplicitlyTypedVariables_09() { var source = @"class Program { static void Main() { var (x, y) = (Main, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'. // var (x, y) = (Main, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(5, 14), // (5,17): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. // var (x, y) = (Main, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(5, 17)); } [Fact] public void ImplicitlyTypedVariables_10() { var source = @"using System; class Program { static void Main() { (var x1, Action y1) = (Main, null); (Action x2, var y2) = (null, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'. // (var x1, Action y1) = (Main, null); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(6, 14), // (7,25): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y2'. // (Action x2, var y2) = (null, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y2").WithArguments("y2").WithLocation(7, 25)); } [Fact] public void ImplicitlyTypedVariables_11() { var source = @"class Program { static void F(object o) { } static void F(int i) { } static void Main() { var d1 = F; var d2 = x => x; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,18): error CS8917: The delegate type could not be inferred. // var d1 = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 18), // (8,18): error CS8917: The delegate type could not be inferred. // var d2 = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(8, 18)); } [Fact] public void ImplicitlyTypedVariables_12() { var source = @"class Program { static void F(ref int i) { } static void Main() { var d1 = F; var d2 = (ref int x) => x; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ImplicitlyTypedVariables_13() { var source = @"using System; class Program { static int F() => 0; static void Main() { var d1 = (F); Report(d1); var d2 = (object (int x) => x); Report(d2); var d3 = (delegate () { return string.Empty; }); Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetDelegateTypeName()); }"; CompileAndVerify(new[] { source, s_utils }, options: TestOptions.DebugExe, expectedOutput: @"System.Func<System.Int32> System.Func<System.Int32, System.Object> System.Func<System.String>"); } [Fact] public void ImplicitlyTypedVariables_14() { var source = @"delegate void D(string s); class Program { static void Main() { (D x, var y) = (() => string.Empty, () => string.Empty); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,19): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. // (D x, var y) = (() => string.Empty, () => string.Empty); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(6, 19)); } [Fact] public void ImplicitlyTypedVariables_UseSiteErrors() { var source = @"class Program { static void F(object o) { } static void Main() { var d1 = F; var d2 = () => 1; } }"; var comp = CreateEmptyCompilation(source, new[] { GetCorlibWithInvalidActionAndFuncOfT() }); comp.VerifyDiagnostics( // (6,18): error CS0648: 'Action<T>' is a type not supported by the language // var d1 = F; Diagnostic(ErrorCode.ERR_BogusType, "F").WithArguments("System.Action<T>").WithLocation(6, 18), // (7,18): error CS0648: 'Func<T>' is a type not supported by the language // var d2 = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Func<T>").WithLocation(7, 18)); } /// <summary> /// Ensure the conversion group containing the implicit /// conversion is handled correctly in NullableWalker. /// </summary> [Fact] public void NullableAnalysis_01() { var source = @"#nullable enable class Program { static void Main() { System.Delegate d; d = Main; d = () => { }; d = delegate () { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } /// <summary> /// Ensure the conversion group containing the explicit /// conversion is handled correctly in NullableWalker. /// </summary> [Fact] public void NullableAnalysis_02() { var source = @"#nullable enable class Program { static void Main() { object o; o = (System.Delegate)Main; o = (System.Delegate)(() => { }); o = (System.Delegate)(delegate () { }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [Fact] public void SynthesizedDelegateTypes_01() { var source = @"using System; class Program { static void M1<T>(T t) { var d = (ref T t) => t; Report(d); Console.WriteLine(d(ref t)); } static void M2<U>(U u) where U : struct { var d = (ref U u) => u; Report(d); Console.WriteLine(d(ref u)); } static void M3(double value) { var d = (ref double d) => d; Report(d); Console.WriteLine(d(ref value)); } static void Main() { M1(41); M2(42f); M2(43d); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"<>F{00000001}`2[System.Int32,System.Int32] 41 <>F{00000001}`2[System.Single,System.Single] 42 <>F{00000001}`2[System.Double,System.Double] 43 "); verifier.VerifyIL("Program.M1<T>", @"{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<T, T> Program.<>c__0<T>.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c__0<T> Program.<>c__0<T>.<>9"" IL_000e: ldftn ""T Program.<>c__0<T>.<M1>b__0_0(ref T)"" IL_0014: newobj ""<>F{00000001}<T, T>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<T, T> Program.<>c__0<T>.<>9__0_0"" IL_001f: dup IL_0020: call ""void Program.Report(System.Delegate)"" IL_0025: ldarga.s V_0 IL_0027: callvirt ""T <>F{00000001}<T, T>.Invoke(ref T)"" IL_002c: box ""T"" IL_0031: call ""void System.Console.WriteLine(object)"" IL_0036: ret }"); verifier.VerifyIL("Program.M2<U>", @"{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<U, U> Program.<>c__1<U>.<>9__1_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c__1<U> Program.<>c__1<U>.<>9"" IL_000e: ldftn ""U Program.<>c__1<U>.<M2>b__1_0(ref U)"" IL_0014: newobj ""<>F{00000001}<U, U>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<U, U> Program.<>c__1<U>.<>9__1_0"" IL_001f: dup IL_0020: call ""void Program.Report(System.Delegate)"" IL_0025: ldarga.s V_0 IL_0027: callvirt ""U <>F{00000001}<U, U>.Invoke(ref U)"" IL_002c: box ""U"" IL_0031: call ""void System.Console.WriteLine(object)"" IL_0036: ret }"); verifier.VerifyIL("Program.M3", @"{ // Code size 50 (0x32) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<double, double> Program.<>c.<>9__2_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""double Program.<>c.<M3>b__2_0(ref double)"" IL_0014: newobj ""<>F{00000001}<double, double>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<double, double> Program.<>c.<>9__2_0"" IL_001f: dup IL_0020: call ""void Program.Report(System.Delegate)"" IL_0025: ldarga.s V_0 IL_0027: callvirt ""double <>F{00000001}<double, double>.Invoke(ref double)"" IL_002c: call ""void System.Console.WriteLine(double)"" IL_0031: ret }"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var nodes = tree.GetRoot().DescendantNodes(); var variables = nodes.OfType<VariableDeclaratorSyntax>().Where(v => v.Identifier.Text == "d").ToArray(); Assert.Equal(3, variables.Length); VerifyLocalDelegateType(model, variables[0], "<>F{00000001}<T, T> d", "T <>F{00000001}<T, T>.Invoke(ref T)"); VerifyLocalDelegateType(model, variables[1], "<>F{00000001}<U, U> d", "U <>F{00000001}<U, U>.Invoke(ref U)"); VerifyLocalDelegateType(model, variables[2], "<>F{00000001}<System.Double, System.Double> d", "System.Double <>F{00000001}<System.Double, System.Double>.Invoke(ref System.Double)"); var identifiers = nodes.OfType<InvocationExpressionSyntax>().Where(i => i.Expression is IdentifierNameSyntax id && id.Identifier.Text == "Report").Select(i => i.ArgumentList.Arguments[0].Expression).ToArray(); Assert.Equal(3, identifiers.Length); VerifyExpressionType(model, identifiers[0], "<>F{00000001}<T, T> d", "<>F{00000001}<T, T>"); VerifyExpressionType(model, identifiers[1], "<>F{00000001}<U, U> d", "<>F{00000001}<U, U>"); VerifyExpressionType(model, identifiers[2], "<>F{00000001}<System.Double, System.Double> d", "<>F{00000001}<System.Double, System.Double>"); } [Fact] public void SynthesizedDelegateTypes_02() { var source = @"using System; class Program { static void M1(A a, int value) { var d = a.F1; d() = value; } static void M2(B b, float value) { var d = b.F2; d() = value; } static void Main() { var a = new A(); M1(a, 41); var b = new B(); M2(b, 42f); Console.WriteLine((a._f, b._f)); } } class A { public int _f; public ref int F1() => ref _f; } class B { public float _f; } static class E { public static ref float F2(this B b) => ref b._f; }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"(41, 42)"); verifier.VerifyIL("Program.M1", @"{ // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldftn ""ref int A.F1()"" IL_0007: newobj ""<>F{00000001}<int>..ctor(object, System.IntPtr)"" IL_000c: callvirt ""ref int <>F{00000001}<int>.Invoke()"" IL_0011: ldarg.1 IL_0012: stind.i4 IL_0013: ret }"); verifier.VerifyIL("Program.M2", @"{ // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldftn ""ref float E.F2(B)"" IL_0007: newobj ""<>F{00000001}<float>..ctor(object, System.IntPtr)"" IL_000c: callvirt ""ref float <>F{00000001}<float>.Invoke()"" IL_0011: ldarg.1 IL_0012: stind.r4 IL_0013: ret }"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var variables = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(v => v.Identifier.Text == "d").ToArray(); Assert.Equal(2, variables.Length); VerifyLocalDelegateType(model, variables[0], "<>F{00000001}<System.Int32> d", "ref System.Int32 <>F{00000001}<System.Int32>.Invoke()"); VerifyLocalDelegateType(model, variables[1], "<>F{00000001}<System.Single> d", "ref System.Single <>F{00000001}<System.Single>.Invoke()"); } [Fact] public void SynthesizedDelegateTypes_03() { var source = @"using System; class Program { static void Main() { Report((ref int x, int y) => { }); Report((int x, ref int y) => { }); Report((ref float x, int y) => { }); Report((float x, ref int y) => { }); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"<>A{00000001}`2[System.Int32,System.Int32] <>A{00000004}`2[System.Int32,System.Int32] <>A{00000001}`2[System.Single,System.Int32] <>A{00000004}`2[System.Single,System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 145 (0x91) .maxstack 2 IL_0000: ldsfld ""<>A{00000001}<int, int> Program.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""void Program.<>c.<Main>b__0_0(ref int, int)"" IL_0014: newobj ""<>A{00000001}<int, int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>A{00000001}<int, int> Program.<>c.<>9__0_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>A{00000004}<int, int> Program.<>c.<>9__0_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""void Program.<>c.<Main>b__0_1(int, ref int)"" IL_0038: newobj ""<>A{00000004}<int, int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>A{00000004}<int, int> Program.<>c.<>9__0_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>A{00000001}<float, int> Program.<>c.<>9__0_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""void Program.<>c.<Main>b__0_2(ref float, int)"" IL_005c: newobj ""<>A{00000001}<float, int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>A{00000001}<float, int> Program.<>c.<>9__0_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ldsfld ""<>A{00000004}<float, int> Program.<>c.<>9__0_3"" IL_0071: dup IL_0072: brtrue.s IL_008b IL_0074: pop IL_0075: ldsfld ""Program.<>c Program.<>c.<>9"" IL_007a: ldftn ""void Program.<>c.<Main>b__0_3(float, ref int)"" IL_0080: newobj ""<>A{00000004}<float, int>..ctor(object, System.IntPtr)"" IL_0085: dup IL_0086: stsfld ""<>A{00000004}<float, int> Program.<>c.<>9__0_3"" IL_008b: call ""void Program.Report(System.Delegate)"" IL_0090: ret }"); } [Fact] public void SynthesizedDelegateTypes_04() { var source = @"using System; class Program { static int i = 0; static void Main() { Report(int () => i); Report((ref int () => ref i)); Report((ref readonly int () => ref i)); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32] <>F{00000001}`1[System.Int32] <>F{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 109 (0x6d) .maxstack 2 IL_0000: ldsfld ""System.Func<int> Program.<>c.<>9__1_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""int Program.<>c.<Main>b__1_0()"" IL_0014: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""System.Func<int> Program.<>c.<>9__1_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>F{00000001}<int> Program.<>c.<>9__1_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""ref int Program.<>c.<Main>b__1_1()"" IL_0038: newobj ""<>F{00000001}<int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>F{00000001}<int> Program.<>c.<>9__1_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>F{00000003}<int> Program.<>c.<>9__1_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""ref readonly int Program.<>c.<Main>b__1_2()"" IL_005c: newobj ""<>F{00000003}<int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>F{00000003}<int> Program.<>c.<>9__1_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ret }"); } [Fact] public void SynthesizedDelegateTypes_05() { var source = @"using System; class Program { static int i = 0; static int F1() => i; static ref int F2() => ref i; static ref readonly int F3() => ref i; static void Main() { Report(F1); Report(F2); Report(F3); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32] <>F{00000001}`1[System.Int32] <>F{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 52 (0x34) .maxstack 2 IL_0000: ldnull IL_0001: ldftn ""int Program.F1()"" IL_0007: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_000c: call ""void Program.Report(System.Delegate)"" IL_0011: ldnull IL_0012: ldftn ""ref int Program.F2()"" IL_0018: newobj ""<>F{00000001}<int>..ctor(object, System.IntPtr)"" IL_001d: call ""void Program.Report(System.Delegate)"" IL_0022: ldnull IL_0023: ldftn ""ref readonly int Program.F3()"" IL_0029: newobj ""<>F{00000003}<int>..ctor(object, System.IntPtr)"" IL_002e: call ""void Program.Report(System.Delegate)"" IL_0033: ret }"); } [Fact] public void SynthesizedDelegateTypes_06() { var source = @"using System; class Program { static int i = 0; static int F1() => i; static ref int F2() => ref i; static ref readonly int F3() => ref i; static void Main() { var d1 = F1; var d2 = F2; var d3 = F3; Report(d1); Report(d2); Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32] <>F{00000001}`1[System.Int32] <>F{00000003}`1[System.Int32] "); } [Fact] public void SynthesizedDelegateTypes_07() { var source = @"using System; class Program { static void Main() { Report(int (ref int i) => i); Report((ref int (ref int i) => ref i)); Report((ref readonly int (ref int i) => ref i)); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"<>F{00000001}`2[System.Int32,System.Int32] <>F{00000005}`2[System.Int32,System.Int32] <>F{0000000d}`2[System.Int32,System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 109 (0x6d) .maxstack 2 IL_0000: ldsfld ""<>F{00000001}<int, int> Program.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""int Program.<>c.<Main>b__0_0(ref int)"" IL_0014: newobj ""<>F{00000001}<int, int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""<>F{00000001}<int, int> Program.<>c.<>9__0_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>F{00000005}<int, int> Program.<>c.<>9__0_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""ref int Program.<>c.<Main>b__0_1(ref int)"" IL_0038: newobj ""<>F{00000005}<int, int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>F{00000005}<int, int> Program.<>c.<>9__0_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>F{0000000d}<int, int> Program.<>c.<>9__0_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""ref readonly int Program.<>c.<Main>b__0_2(ref int)"" IL_005c: newobj ""<>F{0000000d}<int, int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>F{0000000d}<int, int> Program.<>c.<>9__0_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ret }"); } [Fact] public void SynthesizedDelegateTypes_08() { var source = @"#pragma warning disable 414 using System; class Program { static int i = 0; static void Main() { Report((int i) => { }); Report((out int i) => { i = 0; }); Report((ref int i) => { }); Report((in int i) => { }); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Action`1[System.Int32] <>A{00000002}`1[System.Int32] <>A{00000001}`1[System.Int32] <>A{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 145 (0x91) .maxstack 2 IL_0000: ldsfld ""System.Action<int> Program.<>c.<>9__1_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""Program.<>c Program.<>c.<>9"" IL_000e: ldftn ""void Program.<>c.<Main>b__1_0(int)"" IL_0014: newobj ""System.Action<int>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""System.Action<int> Program.<>c.<>9__1_0"" IL_001f: call ""void Program.Report(System.Delegate)"" IL_0024: ldsfld ""<>A{00000002}<int> Program.<>c.<>9__1_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0032: ldftn ""void Program.<>c.<Main>b__1_1(out int)"" IL_0038: newobj ""<>A{00000002}<int>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""<>A{00000002}<int> Program.<>c.<>9__1_1"" IL_0043: call ""void Program.Report(System.Delegate)"" IL_0048: ldsfld ""<>A{00000001}<int> Program.<>c.<>9__1_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0056: ldftn ""void Program.<>c.<Main>b__1_2(ref int)"" IL_005c: newobj ""<>A{00000001}<int>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""<>A{00000001}<int> Program.<>c.<>9__1_2"" IL_0067: call ""void Program.Report(System.Delegate)"" IL_006c: ldsfld ""<>A{00000003}<int> Program.<>c.<>9__1_3"" IL_0071: dup IL_0072: brtrue.s IL_008b IL_0074: pop IL_0075: ldsfld ""Program.<>c Program.<>c.<>9"" IL_007a: ldftn ""void Program.<>c.<Main>b__1_3(in int)"" IL_0080: newobj ""<>A{00000003}<int>..ctor(object, System.IntPtr)"" IL_0085: dup IL_0086: stsfld ""<>A{00000003}<int> Program.<>c.<>9__1_3"" IL_008b: call ""void Program.Report(System.Delegate)"" IL_0090: ret }"); } [Fact] public void SynthesizedDelegateTypes_09() { var source = @"#pragma warning disable 414 using System; class Program { static void M1(int i) { } static void M2(out int i) { i = 0; } static void M3(ref int i) { } static void M4(in int i) { } static void Main() { Report(M1); Report(M2); Report(M3); Report(M4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Action`1[System.Int32] <>A{00000002}`1[System.Int32] <>A{00000001}`1[System.Int32] <>A{00000003}`1[System.Int32] "); verifier.VerifyIL("Program.Main", @"{ // Code size 69 (0x45) .maxstack 2 IL_0000: ldnull IL_0001: ldftn ""void Program.M1(int)"" IL_0007: newobj ""System.Action<int>..ctor(object, System.IntPtr)"" IL_000c: call ""void Program.Report(System.Delegate)"" IL_0011: ldnull IL_0012: ldftn ""void Program.M2(out int)"" IL_0018: newobj ""<>A{00000002}<int>..ctor(object, System.IntPtr)"" IL_001d: call ""void Program.Report(System.Delegate)"" IL_0022: ldnull IL_0023: ldftn ""void Program.M3(ref int)"" IL_0029: newobj ""<>A{00000001}<int>..ctor(object, System.IntPtr)"" IL_002e: call ""void Program.Report(System.Delegate)"" IL_0033: ldnull IL_0034: ldftn ""void Program.M4(in int)"" IL_003a: newobj ""<>A{00000003}<int>..ctor(object, System.IntPtr)"" IL_003f: call ""void Program.Report(System.Delegate)"" IL_0044: ret }"); } [Fact] public void SynthesizedDelegateTypes_10() { var source = @"#pragma warning disable 414 using System; class Program { static void M1(int i) { } static void M2(out int i) { i = 0; } static void M3(ref int i) { } static void M4(in int i) { } static void Main() { var d1 = M1; var d2 = M2; var d3 = M3; var d4 = M4; Report(d1); Report(d2); Report(d3); Report(d4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Action`1[System.Int32] <>A{00000002}`1[System.Int32] <>A{00000001}`1[System.Int32] <>A{00000003}`1[System.Int32] "); } [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [Fact] public void SynthesizedDelegateTypes_11() { var source = @"class Program { unsafe static void Main() { var d1 = int* () => (int*)42; var d2 = (int* p) => { }; var d3 = delegate*<void> () => default; var d4 = (delegate*<void> d) => { }; } }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (5,18): error CS8917: The delegate type could not be inferred. // var d1 = int* () => (int*)42; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "int* () => (int*)42").WithLocation(5, 18), // (6,18): error CS8917: The delegate type could not be inferred. // var d2 = (int* p) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(int* p) => { }").WithLocation(6, 18), // (7,18): error CS8917: The delegate type could not be inferred. // var d3 = delegate*<void> () => default; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "delegate*<void> () => default").WithLocation(7, 18), // (8,18): error CS8917: The delegate type could not be inferred. // var d4 = (delegate*<void> d) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(delegate*<void> d) => { }").WithLocation(8, 18)); } [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [ConditionalFact(typeof(DesktopOnly))] public void SynthesizedDelegateTypes_12() { var source = @"using System; class Program { static void Main() { var d1 = (TypedReference x) => { }; var d2 = (int x, RuntimeArgumentHandle y) => { }; var d3 = (ArgIterator x) => { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): error CS8917: The delegate type could not be inferred. // var d1 = (TypedReference x) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(TypedReference x) => { }").WithLocation(6, 18), // (7,18): error CS8917: The delegate type could not be inferred. // var d2 = (int x, RuntimeArgumentHandle y) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(int x, RuntimeArgumentHandle y) => { }").WithLocation(7, 18), // (8,18): error CS8917: The delegate type could not be inferred. // var d3 = (ArgIterator x) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(ArgIterator x) => { }").WithLocation(8, 18)); } [WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")] [Fact] public void SynthesizedDelegateTypes_13() { var source = @"ref struct S<T> { } class Program { static void F1(int x, S<int> y) { } static S<T> F2<T>() => throw null; static void Main() { var d1 = F1; var d2 = F2<object>; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,18): error CS8917: The delegate type could not be inferred. // var d1 = F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(8, 18), // (9,18): error CS8917: The delegate type could not be inferred. // var d2 = F2<object>; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2<object>").WithLocation(9, 18)); } [Fact] public void SynthesizedDelegateTypes_14() { var source = @"class Program { static ref void F() { } static void Main() { var d1 = F; var d2 = (ref void () => { }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (3,16): error CS1547: Keyword 'void' cannot be used in this context // static ref void F() { } Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(3, 16), // (6,18): error CS8917: The delegate type could not be inferred. // var d1 = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(6, 18), // (7,19): error CS8917: The delegate type could not be inferred. // var d2 = (ref void () => { }); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "ref void () => { }").WithLocation(7, 19), // (7,23): error CS1547: Keyword 'void' cannot be used in this context // var d2 = (ref void () => { }); Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(7, 23)); } [Fact] public void SynthesizedDelegateTypes_15() { var source = @"using System; unsafe class Program { static byte*[] F1() => null; static void F2(byte*[] a) { } static byte*[] F3(ref int i) => null; static void F4(ref byte*[] a) { } static void Main() { Report(int*[] () => null); Report((int*[] a) => { }); Report(int*[] (ref int i) => null); Report((ref int*[] a) => { }); Report(F1); Report(F2); Report(F3); Report(F4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Func`1[System.Int32*[]] System.Action`1[System.Int32*[]] <>F{00000001}`2[System.Int32,System.Int32*[]] <>A{00000001}`1[System.Int32*[]] System.Func`1[System.Byte*[]] System.Action`1[System.Byte*[]] <>F{00000001}`2[System.Int32,System.Byte*[]] <>A{00000001}`1[System.Byte*[]] "); } [Fact] public void SynthesizedDelegateTypes_16() { var source = @"using System; unsafe class Program { static delegate*<ref int>[] F1() => null; static void F2(delegate*<ref int, void>[] a) { } static delegate*<ref int>[] F3(ref int i) => null; static void F4(ref delegate*<ref int, void>[] a) { } static void Main() { Report(delegate*<int, ref int>[] () => null); Report((delegate*<int, ref int, void>[] a) => { }); Report(delegate*<int, ref int>[] (ref int i) => null); Report((ref delegate*<int, ref int, void>[] a) => { }); Report(F1); Report(F2); Report(F3); Report(F4); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Func`1[(fnptr)[]] System.Action`1[(fnptr)[]] <>F{00000001}`2[System.Int32,(fnptr)[]] <>A{00000001}`1[(fnptr)[]] System.Func`1[(fnptr)[]] System.Action`1[(fnptr)[]] <>F{00000001}`2[System.Int32,(fnptr)[]] <>A{00000001}`1[(fnptr)[]] "); } [Fact] public void SynthesizedDelegateTypes_17() { var source = @"#nullable enable using System; class Program { static void F1(object x, dynamic y) { } static void F2(IntPtr x, nint y) { } static void F3((int x, int y) t) { } static void F4(object? x, object?[] y) { } static void F5(ref object x, dynamic y) { } static void F6(IntPtr x, ref nint y) { } static void F7(ref (int x, int y) t) { } static void F8(object? x, ref object?[] y) { } static void Main() { Report(F1); Report(F2); Report(F3); Report(F4); Report(F5); Report(F6); Report(F7); Report(F8); } static void Report(Delegate d) => Console.WriteLine(d.GetType()); }"; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"System.Action`2[System.Object,System.Object] System.Action`2[System.IntPtr,System.IntPtr] System.Action`1[System.ValueTuple`2[System.Int32,System.Int32]] System.Action`2[System.Object,System.Object[]] <>A{00000001}`2[System.Object,System.Object] <>A{00000004}`2[System.IntPtr,System.IntPtr] <>A{00000001}`1[System.ValueTuple`2[System.Int32,System.Int32]] <>A{00000004}`2[System.Object,System.Object[]] "); } private static void VerifyLocalDelegateType(SemanticModel model, VariableDeclaratorSyntax variable, string expectedLocal, string expectedInvokeMethod) { var local = (ILocalSymbol)model.GetDeclaredSymbol(variable)!; Assert.Equal(expectedLocal, local.ToTestDisplayString()); var delegateType = ((INamedTypeSymbol)local.Type); Assert.Equal(Accessibility.Internal, delegateType.DeclaredAccessibility); Assert.Equal(expectedInvokeMethod, delegateType.DelegateInvokeMethod.ToTestDisplayString()); } private static void VerifyExpressionType(SemanticModel model, ExpressionSyntax variable, string expectedSymbol, string expectedType) { var symbol = model.GetSymbolInfo(variable).Symbol; Assert.Equal(expectedSymbol, symbol.ToTestDisplayString()); var type = model.GetTypeInfo(variable).Type; Assert.Equal(expectedType, type.ToTestDisplayString()); } [Fact] public void TaskRunArgument() { var source = @"using System.Threading.Tasks; class Program { static async Task F() { await Task.Run(() => { }); } }"; var verifier = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview); var method = (MethodSymbol)verifier.TestData.GetMethodsByName()["Program.<>c.<F>b__0_0()"].Method; Assert.Equal("void Program.<>c.<F>b__0_0()", method.ToTestDisplayString()); verifier.VerifyIL("Program.<>c.<F>b__0_0()", @"{ // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } } }
1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/Core/Implementation/CommentSelection/AbstractToggleBlockCommentBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CommentSelection; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Text.Operations; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection { internal abstract class AbstractToggleBlockCommentBase : // Value tuple to represent that there is no distinct command to be passed in. AbstractCommentSelectionBase<ValueTuple>, ICommandHandler<ToggleBlockCommentCommandArgs> { private static readonly CommentSelectionResult s_emptyCommentSelectionResult = new(new List<TextChange>(), new List<CommentTrackingSpan>(), Operation.Uncomment); private readonly ITextStructureNavigatorSelectorService _navigatorSelectorService; internal AbstractToggleBlockCommentBase( ITextUndoHistoryRegistry undoHistoryRegistry, IEditorOperationsFactoryService editorOperationsFactoryService, ITextStructureNavigatorSelectorService navigatorSelectorService) : base(undoHistoryRegistry, editorOperationsFactoryService) { _navigatorSelectorService = navigatorSelectorService; } /// <summary> /// Retrieves data about the commented spans near the selection. /// </summary> /// <param name="document">the current document.</param> /// <param name="snapshot">the current text snapshot.</param> /// <param name="linesContainingSelections"> /// a span that contains text from the first character of the first line in the selection(s) /// until the last character of the last line in the selection(s) /// </param> /// <param name="commentInfo">the comment information for the document.</param> /// <param name="cancellationToken">a cancellation token.</param> /// <returns>any commented spans relevant to the selection in the document.</returns> protected abstract Task<ImmutableArray<TextSpan>> GetBlockCommentsInDocumentAsync(Document document, ITextSnapshot snapshot, TextSpan linesContainingSelections, CommentSelectionInfo commentInfo, CancellationToken cancellationToken); public CommandState GetCommandState(ToggleBlockCommentCommandArgs args) => GetCommandState(args.SubjectBuffer); public bool ExecuteCommand(ToggleBlockCommentCommandArgs args, CommandExecutionContext context) => ExecuteCommand(args.TextView, args.SubjectBuffer, ValueTuple.Create(), context); public override string DisplayName => EditorFeaturesResources.Toggle_Block_Comment; protected override string GetTitle(ValueTuple command) => EditorFeaturesResources.Toggle_Block_Comment; protected override string GetMessage(ValueTuple command) => EditorFeaturesResources.Toggling_block_comment; internal override async Task<CommentSelectionResult> CollectEditsAsync(Document document, ICommentSelectionService service, ITextBuffer subjectBuffer, NormalizedSnapshotSpanCollection selectedSpans, ValueTuple command, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.CommandHandler_ToggleBlockComment, KeyValueLogMessage.Create(LogType.UserAction, m => { m[LanguageNameString] = document.Project.Language; m[LengthString] = subjectBuffer.CurrentSnapshot.Length; }), cancellationToken)) { var navigator = _navigatorSelectorService.GetTextStructureNavigator(subjectBuffer); var commentInfo = await service.GetInfoAsync(document, selectedSpans.First().Span.ToTextSpan(), cancellationToken).ConfigureAwait(false); if (commentInfo.SupportsBlockComment) { return await ToggleBlockCommentsAsync(document, commentInfo, navigator, selectedSpans, cancellationToken).ConfigureAwait(false); } return s_emptyCommentSelectionResult; } } private async Task<CommentSelectionResult> ToggleBlockCommentsAsync(Document document, CommentSelectionInfo commentInfo, ITextStructureNavigator navigator, NormalizedSnapshotSpanCollection selectedSpans, CancellationToken cancellationToken) { var firstLineAroundSelection = selectedSpans.First().Start.GetContainingLine().Start; var lastLineAroundSelection = selectedSpans.Last().End.GetContainingLine().End; var linesContainingSelection = TextSpan.FromBounds(firstLineAroundSelection, lastLineAroundSelection); var blockCommentedSpans = await GetBlockCommentsInDocumentAsync( document, selectedSpans.First().Snapshot, linesContainingSelection, commentInfo, cancellationToken).ConfigureAwait(false); var blockCommentSelections = selectedSpans.SelectAsArray(span => new BlockCommentSelectionHelper(blockCommentedSpans, span)); var returnOperation = Operation.Uncomment; var textChanges = ArrayBuilder<TextChange>.GetInstance(); var trackingSpans = ArrayBuilder<CommentTrackingSpan>.GetInstance(); // Try to uncomment until an already uncommented span is found. foreach (var blockCommentSelection in blockCommentSelections) { // If any selection does not have comments to remove, then the operation should be comment. if (!TryUncommentBlockComment(blockCommentedSpans, blockCommentSelection, textChanges, trackingSpans, commentInfo)) { returnOperation = Operation.Comment; break; } } if (returnOperation == Operation.Comment) { textChanges.Clear(); trackingSpans.Clear(); foreach (var blockCommentSelection in blockCommentSelections) { BlockCommentSpan(blockCommentSelection, navigator, textChanges, trackingSpans, commentInfo); } } return new CommentSelectionResult(textChanges.ToArrayAndFree(), trackingSpans.ToArrayAndFree(), returnOperation); } private static bool TryUncommentBlockComment(ImmutableArray<TextSpan> blockCommentedSpans, BlockCommentSelectionHelper blockCommentSelection, ArrayBuilder<TextChange> textChanges, ArrayBuilder<CommentTrackingSpan> trackingSpans, CommentSelectionInfo commentInfo) { // If the selection is just a caret, try and uncomment blocks on the same line with only whitespace on the line. if (blockCommentSelection.SelectedSpan.IsEmpty && blockCommentSelection.TryGetBlockCommentOnSameLine(blockCommentedSpans, out var blockCommentOnSameLine)) { DeleteBlockComment(blockCommentSelection, blockCommentOnSameLine, textChanges, commentInfo); trackingSpans.Add(new CommentTrackingSpan(blockCommentOnSameLine)); return true; } // If the selection is entirely commented, remove any block comments that intersect. else if (blockCommentSelection.IsEntirelyCommented()) { var intersectingBlockComments = blockCommentSelection.IntersectingBlockComments; foreach (var spanToRemove in intersectingBlockComments) { DeleteBlockComment(blockCommentSelection, spanToRemove, textChanges, commentInfo); } var trackingSpan = TextSpan.FromBounds(intersectingBlockComments.First().Start, intersectingBlockComments.Last().End); trackingSpans.Add(new CommentTrackingSpan(trackingSpan)); return true; } else { return false; } } private static void BlockCommentSpan(BlockCommentSelectionHelper blockCommentSelection, ITextStructureNavigator navigator, ArrayBuilder<TextChange> textChanges, ArrayBuilder<CommentTrackingSpan> trackingSpans, CommentSelectionInfo commentInfo) { // Add sequential block comments if the selection contains any intersecting comments. if (blockCommentSelection.HasIntersectingBlockComments()) { AddBlockCommentWithIntersectingSpans(blockCommentSelection, textChanges, trackingSpans, commentInfo); } else { // Comment the selected span or caret location. var spanToAdd = blockCommentSelection.SelectedSpan; if (spanToAdd.IsEmpty) { var caretLocation = GetCaretLocationAfterToken(navigator, blockCommentSelection); spanToAdd = TextSpan.FromBounds(caretLocation, caretLocation); } trackingSpans.Add(new CommentTrackingSpan(spanToAdd)); AddBlockComment(commentInfo, spanToAdd, textChanges); } } /// <summary> /// Returns a caret location of itself or the location after the token the caret is inside of. /// </summary> private static int GetCaretLocationAfterToken(ITextStructureNavigator navigator, BlockCommentSelectionHelper blockCommentSelection) { var snapshotSpan = blockCommentSelection.SnapshotSpan; if (navigator == null) { return snapshotSpan.Start; } var extent = navigator.GetExtentOfWord(snapshotSpan.Start); int locationAfterToken = extent.Span.End; // Don't move to the end if it's already before the token. if (snapshotSpan.Start == extent.Span.Start) { locationAfterToken = extent.Span.Start; } // If the 'word' is just whitespace, use the selected location. if (blockCommentSelection.IsSpanWhitespace(TextSpan.FromBounds(extent.Span.Start, extent.Span.End))) { locationAfterToken = snapshotSpan.Start; } return locationAfterToken; } /// <summary> /// Adds a block comment when the selection already contains block comment(s). /// The result will be sequential block comments with the entire selection being commented out. /// </summary> private static void AddBlockCommentWithIntersectingSpans(BlockCommentSelectionHelper blockCommentSelection, ArrayBuilder<TextChange> textChanges, ArrayBuilder<CommentTrackingSpan> trackingSpans, CommentSelectionInfo commentInfo) { var selectedSpan = blockCommentSelection.SelectedSpan; var amountToAddToStart = 0; var amountToAddToEnd = 0; // Add comments to all uncommented spans in the selection. foreach (var uncommentedSpan in blockCommentSelection.UncommentedSpansInSelection) { AddBlockComment(commentInfo, uncommentedSpan, textChanges); } var startsWithCommentMarker = blockCommentSelection.StartsWithAnyBlockCommentMarker(commentInfo); var endsWithCommentMarker = blockCommentSelection.EndsWithAnyBlockCommentMarker(commentInfo); // If the start is commented (and not a comment marker), close the current comment and open a new one. if (blockCommentSelection.IsLocationCommented(selectedSpan.Start) && !startsWithCommentMarker) { InsertText(textChanges, selectedSpan.Start, commentInfo.BlockCommentEndString); InsertText(textChanges, selectedSpan.Start, commentInfo.BlockCommentStartString); // Shrink the tracking so the previous comment start marker is not included in selection. amountToAddToStart = commentInfo.BlockCommentEndString.Length; } // If the end is commented (and not a comment marker), close the current comment and open a new one. if (blockCommentSelection.IsLocationCommented(selectedSpan.End) && !endsWithCommentMarker) { InsertText(textChanges, selectedSpan.End, commentInfo.BlockCommentEndString); InsertText(textChanges, selectedSpan.End, commentInfo.BlockCommentStartString); // Shrink the tracking span so the next comment start marker is not included in selection. amountToAddToEnd = -commentInfo.BlockCommentStartString.Length; } trackingSpans.Add(new CommentTrackingSpan(selectedSpan, amountToAddToStart, amountToAddToEnd)); } private static void AddBlockComment(CommentSelectionInfo commentInfo, TextSpan span, ArrayBuilder<TextChange> textChanges) { InsertText(textChanges, span.Start, commentInfo.BlockCommentStartString); InsertText(textChanges, span.End, commentInfo.BlockCommentEndString); } private static void DeleteBlockComment(BlockCommentSelectionHelper blockCommentSelection, TextSpan spanToRemove, ArrayBuilder<TextChange> textChanges, CommentSelectionInfo commentInfo) { DeleteText(textChanges, new TextSpan(spanToRemove.Start, commentInfo.BlockCommentStartString.Length)); var endMarkerPosition = spanToRemove.End - commentInfo.BlockCommentEndString.Length; // Sometimes the block comment will be missing a close marker. if (Equals(blockCommentSelection.GetSubstringFromText(endMarkerPosition, commentInfo.BlockCommentEndString.Length), commentInfo.BlockCommentEndString)) { DeleteText(textChanges, new TextSpan(endMarkerPosition, commentInfo.BlockCommentEndString.Length)); } } private class BlockCommentSelectionHelper { /// <summary> /// Trimmed text of the selection. /// </summary> private readonly string _trimmedText; public SnapshotSpan SnapshotSpan { get; } public TextSpan SelectedSpan { get; } public ImmutableArray<TextSpan> IntersectingBlockComments { get; } public ImmutableArray<TextSpan> UncommentedSpansInSelection { get; } public BlockCommentSelectionHelper(ImmutableArray<TextSpan> allBlockComments, SnapshotSpan selectedSnapshotSpan) { _trimmedText = selectedSnapshotSpan.GetText().Trim(); SnapshotSpan = selectedSnapshotSpan; SelectedSpan = TextSpan.FromBounds(selectedSnapshotSpan.Start, selectedSnapshotSpan.End); IntersectingBlockComments = GetIntersectingBlockComments(allBlockComments, SelectedSpan); UncommentedSpansInSelection = GetUncommentedSpansInSelection(); } /// <summary> /// Determines if the given span is entirely whitespace. /// </summary> public bool IsSpanWhitespace(TextSpan span) { for (var i = span.Start; i < span.End; i++) { if (!char.IsWhiteSpace(SnapshotSpan.Snapshot[i])) { return false; } } return true; } /// <summary> /// Determines if the location falls inside a commented span. /// </summary> public bool IsLocationCommented(int location) => IntersectingBlockComments.Contains(span => span.Contains(location)); /// <summary> /// Checks if the selection already starts with a comment marker. /// This prevents us from adding an extra marker. /// </summary> public bool StartsWithAnyBlockCommentMarker(CommentSelectionInfo commentInfo) { return _trimmedText.StartsWith(commentInfo.BlockCommentStartString, StringComparison.Ordinal) || _trimmedText.StartsWith(commentInfo.BlockCommentEndString, StringComparison.Ordinal); } /// <summary> /// Checks if the selection already ends with a comment marker. /// This prevents us from adding an extra marker. /// </summary> public bool EndsWithAnyBlockCommentMarker(CommentSelectionInfo commentInfo) { return _trimmedText.EndsWith(commentInfo.BlockCommentStartString, StringComparison.Ordinal) || _trimmedText.EndsWith(commentInfo.BlockCommentEndString, StringComparison.Ordinal); } /// <summary> /// Checks if the selected span contains any uncommented non whitespace characters. /// </summary> public bool IsEntirelyCommented() => !UncommentedSpansInSelection.Any() && HasIntersectingBlockComments(); /// <summary> /// Returns if the selection intersects with any block comments. /// </summary> public bool HasIntersectingBlockComments() => IntersectingBlockComments.Any(); public string GetSubstringFromText(int position, int length) => SnapshotSpan.Snapshot.GetText().Substring(position, length); /// <summary> /// Tries to get a block comment on the same line. There are two cases: /// 1. The caret is preceding a block comment on the same line, with only whitespace before the comment. /// 2. The caret is following a block comment on the same line, with only whitespace after the comment. /// </summary> public bool TryGetBlockCommentOnSameLine(ImmutableArray<TextSpan> allBlockComments, out TextSpan commentedSpanOnSameLine) { var snapshot = SnapshotSpan.Snapshot; var selectedLine = snapshot.GetLineFromPosition(SelectedSpan.Start); var lineStartToCaretIsWhitespace = IsSpanWhitespace(TextSpan.FromBounds(selectedLine.Start, SelectedSpan.Start)); var caretToLineEndIsWhitespace = IsSpanWhitespace(TextSpan.FromBounds(SelectedSpan.Start, selectedLine.End)); foreach (var blockComment in allBlockComments) { if (lineStartToCaretIsWhitespace && SelectedSpan.Start < blockComment.Start && snapshot.AreOnSameLine(SelectedSpan.Start, blockComment.Start)) { if (IsSpanWhitespace(TextSpan.FromBounds(SelectedSpan.Start, blockComment.Start))) { commentedSpanOnSameLine = blockComment; return true; } } else if (caretToLineEndIsWhitespace && SelectedSpan.Start > blockComment.End && snapshot.AreOnSameLine(SelectedSpan.Start, blockComment.End)) { if (IsSpanWhitespace(TextSpan.FromBounds(blockComment.End, SelectedSpan.Start))) { commentedSpanOnSameLine = blockComment; return true; } } } commentedSpanOnSameLine = new TextSpan(); return false; } /// <summary> /// Gets a list of block comments that intersect the span. /// Spans are intersecting if 1 location is the same between them (empty spans look at the start). /// </summary> private static ImmutableArray<TextSpan> GetIntersectingBlockComments(ImmutableArray<TextSpan> allBlockComments, TextSpan span) => allBlockComments.WhereAsArray(blockCommentSpan => span.OverlapsWith(blockCommentSpan) || blockCommentSpan.Contains(span)); /// <summary> /// Retrieves all non commented, non whitespace spans. /// </summary> private ImmutableArray<TextSpan> GetUncommentedSpansInSelection() { var uncommentedSpans = new List<TextSpan>(); // Invert the commented spans to get the uncommented spans. var spanStart = SelectedSpan.Start; foreach (var commentedSpan in IntersectingBlockComments) { if (commentedSpan.Start > spanStart) { // Get span up until the comment and check to make sure it is not whitespace. var possibleUncommentedSpan = TextSpan.FromBounds(spanStart, commentedSpan.Start); if (!IsSpanWhitespace(possibleUncommentedSpan)) { uncommentedSpans.Add(possibleUncommentedSpan); } } // The next possible uncommented span starts at the end of this commented span. spanStart = commentedSpan.End; } // If part of the selection is left over, it's not commented. Add if not whitespace. if (spanStart < SelectedSpan.End) { var uncommentedSpan = TextSpan.FromBounds(spanStart, SelectedSpan.End); if (!IsSpanWhitespace(uncommentedSpan)) { uncommentedSpans.Add(uncommentedSpan); } } return uncommentedSpans.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; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommentSelection; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Text.Operations; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection { internal abstract class AbstractToggleBlockCommentBase : // Value tuple to represent that there is no distinct command to be passed in. AbstractCommentSelectionBase<ValueTuple>, ICommandHandler<ToggleBlockCommentCommandArgs> { private static readonly CommentSelectionResult s_emptyCommentSelectionResult = new(new List<TextChange>(), new List<CommentTrackingSpan>(), Operation.Uncomment); private readonly ITextStructureNavigatorSelectorService _navigatorSelectorService; internal AbstractToggleBlockCommentBase( ITextUndoHistoryRegistry undoHistoryRegistry, IEditorOperationsFactoryService editorOperationsFactoryService, ITextStructureNavigatorSelectorService navigatorSelectorService) : base(undoHistoryRegistry, editorOperationsFactoryService) { _navigatorSelectorService = navigatorSelectorService; } /// <summary> /// Retrieves data about the commented spans near the selection. /// </summary> /// <param name="document">the current document.</param> /// <param name="snapshot">the current text snapshot.</param> /// <param name="linesContainingSelections"> /// a span that contains text from the first character of the first line in the selection(s) /// until the last character of the last line in the selection(s) /// </param> /// <param name="commentInfo">the comment information for the document.</param> /// <param name="cancellationToken">a cancellation token.</param> /// <returns>any commented spans relevant to the selection in the document.</returns> protected abstract Task<ImmutableArray<TextSpan>> GetBlockCommentsInDocumentAsync(Document document, ITextSnapshot snapshot, TextSpan linesContainingSelections, CommentSelectionInfo commentInfo, CancellationToken cancellationToken); public CommandState GetCommandState(ToggleBlockCommentCommandArgs args) => GetCommandState(args.SubjectBuffer); public bool ExecuteCommand(ToggleBlockCommentCommandArgs args, CommandExecutionContext context) => ExecuteCommand(args.TextView, args.SubjectBuffer, ValueTuple.Create(), context); public override string DisplayName => EditorFeaturesResources.Toggle_Block_Comment; protected override string GetTitle(ValueTuple command) => EditorFeaturesResources.Toggle_Block_Comment; protected override string GetMessage(ValueTuple command) => EditorFeaturesResources.Toggling_block_comment; internal override async Task<CommentSelectionResult> CollectEditsAsync(Document document, ICommentSelectionService service, ITextBuffer subjectBuffer, NormalizedSnapshotSpanCollection selectedSpans, ValueTuple command, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.CommandHandler_ToggleBlockComment, KeyValueLogMessage.Create(LogType.UserAction, m => { m[LanguageNameString] = document.Project.Language; m[LengthString] = subjectBuffer.CurrentSnapshot.Length; }), cancellationToken)) { var navigator = _navigatorSelectorService.GetTextStructureNavigator(subjectBuffer); var commentInfo = await service.GetInfoAsync(document, selectedSpans.First().Span.ToTextSpan(), cancellationToken).ConfigureAwait(false); if (commentInfo.SupportsBlockComment) { return await ToggleBlockCommentsAsync(document, commentInfo, navigator, selectedSpans, cancellationToken).ConfigureAwait(false); } return s_emptyCommentSelectionResult; } } private async Task<CommentSelectionResult> ToggleBlockCommentsAsync(Document document, CommentSelectionInfo commentInfo, ITextStructureNavigator navigator, NormalizedSnapshotSpanCollection selectedSpans, CancellationToken cancellationToken) { var firstLineAroundSelection = selectedSpans.First().Start.GetContainingLine().Start; var lastLineAroundSelection = selectedSpans.Last().End.GetContainingLine().End; var linesContainingSelection = TextSpan.FromBounds(firstLineAroundSelection, lastLineAroundSelection); var blockCommentedSpans = await GetBlockCommentsInDocumentAsync( document, selectedSpans.First().Snapshot, linesContainingSelection, commentInfo, cancellationToken).ConfigureAwait(false); var blockCommentSelections = selectedSpans.SelectAsArray(span => new BlockCommentSelectionHelper(blockCommentedSpans, span)); var returnOperation = Operation.Uncomment; var textChanges = ArrayBuilder<TextChange>.GetInstance(); var trackingSpans = ArrayBuilder<CommentTrackingSpan>.GetInstance(); // Try to uncomment until an already uncommented span is found. foreach (var blockCommentSelection in blockCommentSelections) { // If any selection does not have comments to remove, then the operation should be comment. if (!TryUncommentBlockComment(blockCommentedSpans, blockCommentSelection, textChanges, trackingSpans, commentInfo)) { returnOperation = Operation.Comment; break; } } if (returnOperation == Operation.Comment) { textChanges.Clear(); trackingSpans.Clear(); foreach (var blockCommentSelection in blockCommentSelections) { BlockCommentSpan(blockCommentSelection, navigator, textChanges, trackingSpans, commentInfo); } } return new CommentSelectionResult(textChanges.ToArrayAndFree(), trackingSpans.ToArrayAndFree(), returnOperation); } private static bool TryUncommentBlockComment(ImmutableArray<TextSpan> blockCommentedSpans, BlockCommentSelectionHelper blockCommentSelection, ArrayBuilder<TextChange> textChanges, ArrayBuilder<CommentTrackingSpan> trackingSpans, CommentSelectionInfo commentInfo) { // If the selection is just a caret, try and uncomment blocks on the same line with only whitespace on the line. if (blockCommentSelection.SelectedSpan.IsEmpty && blockCommentSelection.TryGetBlockCommentOnSameLine(blockCommentedSpans, out var blockCommentOnSameLine)) { DeleteBlockComment(blockCommentSelection, blockCommentOnSameLine, textChanges, commentInfo); trackingSpans.Add(new CommentTrackingSpan(blockCommentOnSameLine)); return true; } // If the selection is entirely commented, remove any block comments that intersect. else if (blockCommentSelection.IsEntirelyCommented()) { var intersectingBlockComments = blockCommentSelection.IntersectingBlockComments; foreach (var spanToRemove in intersectingBlockComments) { DeleteBlockComment(blockCommentSelection, spanToRemove, textChanges, commentInfo); } var trackingSpan = TextSpan.FromBounds(intersectingBlockComments.First().Start, intersectingBlockComments.Last().End); trackingSpans.Add(new CommentTrackingSpan(trackingSpan)); return true; } else { return false; } } private static void BlockCommentSpan(BlockCommentSelectionHelper blockCommentSelection, ITextStructureNavigator navigator, ArrayBuilder<TextChange> textChanges, ArrayBuilder<CommentTrackingSpan> trackingSpans, CommentSelectionInfo commentInfo) { // Add sequential block comments if the selection contains any intersecting comments. if (blockCommentSelection.HasIntersectingBlockComments()) { AddBlockCommentWithIntersectingSpans(blockCommentSelection, textChanges, trackingSpans, commentInfo); } else { // Comment the selected span or caret location. var spanToAdd = blockCommentSelection.SelectedSpan; if (spanToAdd.IsEmpty) { var caretLocation = GetCaretLocationAfterToken(navigator, blockCommentSelection); spanToAdd = TextSpan.FromBounds(caretLocation, caretLocation); } trackingSpans.Add(new CommentTrackingSpan(spanToAdd)); AddBlockComment(commentInfo, spanToAdd, textChanges); } } /// <summary> /// Returns a caret location of itself or the location after the token the caret is inside of. /// </summary> private static int GetCaretLocationAfterToken(ITextStructureNavigator navigator, BlockCommentSelectionHelper blockCommentSelection) { var snapshotSpan = blockCommentSelection.SnapshotSpan; if (navigator == null) { return snapshotSpan.Start; } var extent = navigator.GetExtentOfWord(snapshotSpan.Start); int locationAfterToken = extent.Span.End; // Don't move to the end if it's already before the token. if (snapshotSpan.Start == extent.Span.Start) { locationAfterToken = extent.Span.Start; } // If the 'word' is just whitespace, use the selected location. if (blockCommentSelection.IsSpanWhitespace(TextSpan.FromBounds(extent.Span.Start, extent.Span.End))) { locationAfterToken = snapshotSpan.Start; } return locationAfterToken; } /// <summary> /// Adds a block comment when the selection already contains block comment(s). /// The result will be sequential block comments with the entire selection being commented out. /// </summary> private static void AddBlockCommentWithIntersectingSpans(BlockCommentSelectionHelper blockCommentSelection, ArrayBuilder<TextChange> textChanges, ArrayBuilder<CommentTrackingSpan> trackingSpans, CommentSelectionInfo commentInfo) { var selectedSpan = blockCommentSelection.SelectedSpan; var amountToAddToStart = 0; var amountToAddToEnd = 0; // Add comments to all uncommented spans in the selection. foreach (var uncommentedSpan in blockCommentSelection.UncommentedSpansInSelection) { AddBlockComment(commentInfo, uncommentedSpan, textChanges); } var startsWithCommentMarker = blockCommentSelection.StartsWithAnyBlockCommentMarker(commentInfo); var endsWithCommentMarker = blockCommentSelection.EndsWithAnyBlockCommentMarker(commentInfo); // If the start is commented (and not a comment marker), close the current comment and open a new one. if (blockCommentSelection.IsLocationCommented(selectedSpan.Start) && !startsWithCommentMarker) { InsertText(textChanges, selectedSpan.Start, commentInfo.BlockCommentEndString); InsertText(textChanges, selectedSpan.Start, commentInfo.BlockCommentStartString); // Shrink the tracking so the previous comment start marker is not included in selection. amountToAddToStart = commentInfo.BlockCommentEndString.Length; } // If the end is commented (and not a comment marker), close the current comment and open a new one. if (blockCommentSelection.IsLocationCommented(selectedSpan.End) && !endsWithCommentMarker) { InsertText(textChanges, selectedSpan.End, commentInfo.BlockCommentEndString); InsertText(textChanges, selectedSpan.End, commentInfo.BlockCommentStartString); // Shrink the tracking span so the next comment start marker is not included in selection. amountToAddToEnd = -commentInfo.BlockCommentStartString.Length; } trackingSpans.Add(new CommentTrackingSpan(selectedSpan, amountToAddToStart, amountToAddToEnd)); } private static void AddBlockComment(CommentSelectionInfo commentInfo, TextSpan span, ArrayBuilder<TextChange> textChanges) { InsertText(textChanges, span.Start, commentInfo.BlockCommentStartString); InsertText(textChanges, span.End, commentInfo.BlockCommentEndString); } private static void DeleteBlockComment(BlockCommentSelectionHelper blockCommentSelection, TextSpan spanToRemove, ArrayBuilder<TextChange> textChanges, CommentSelectionInfo commentInfo) { DeleteText(textChanges, new TextSpan(spanToRemove.Start, commentInfo.BlockCommentStartString.Length)); var endMarkerPosition = spanToRemove.End - commentInfo.BlockCommentEndString.Length; // Sometimes the block comment will be missing a close marker. if (Equals(blockCommentSelection.GetSubstringFromText(endMarkerPosition, commentInfo.BlockCommentEndString.Length), commentInfo.BlockCommentEndString)) { DeleteText(textChanges, new TextSpan(endMarkerPosition, commentInfo.BlockCommentEndString.Length)); } } private class BlockCommentSelectionHelper { /// <summary> /// Trimmed text of the selection. /// </summary> private readonly string _trimmedText; public SnapshotSpan SnapshotSpan { get; } public TextSpan SelectedSpan { get; } public ImmutableArray<TextSpan> IntersectingBlockComments { get; } public ImmutableArray<TextSpan> UncommentedSpansInSelection { get; } public BlockCommentSelectionHelper(ImmutableArray<TextSpan> allBlockComments, SnapshotSpan selectedSnapshotSpan) { _trimmedText = selectedSnapshotSpan.GetText().Trim(); SnapshotSpan = selectedSnapshotSpan; SelectedSpan = TextSpan.FromBounds(selectedSnapshotSpan.Start, selectedSnapshotSpan.End); IntersectingBlockComments = GetIntersectingBlockComments(allBlockComments, SelectedSpan); UncommentedSpansInSelection = GetUncommentedSpansInSelection(); } /// <summary> /// Determines if the given span is entirely whitespace. /// </summary> public bool IsSpanWhitespace(TextSpan span) { for (var i = span.Start; i < span.End; i++) { if (!char.IsWhiteSpace(SnapshotSpan.Snapshot[i])) { return false; } } return true; } /// <summary> /// Determines if the location falls inside a commented span. /// </summary> public bool IsLocationCommented(int location) => IntersectingBlockComments.Contains(span => span.Contains(location)); /// <summary> /// Checks if the selection already starts with a comment marker. /// This prevents us from adding an extra marker. /// </summary> public bool StartsWithAnyBlockCommentMarker(CommentSelectionInfo commentInfo) { return _trimmedText.StartsWith(commentInfo.BlockCommentStartString, StringComparison.Ordinal) || _trimmedText.StartsWith(commentInfo.BlockCommentEndString, StringComparison.Ordinal); } /// <summary> /// Checks if the selection already ends with a comment marker. /// This prevents us from adding an extra marker. /// </summary> public bool EndsWithAnyBlockCommentMarker(CommentSelectionInfo commentInfo) { return _trimmedText.EndsWith(commentInfo.BlockCommentStartString, StringComparison.Ordinal) || _trimmedText.EndsWith(commentInfo.BlockCommentEndString, StringComparison.Ordinal); } /// <summary> /// Checks if the selected span contains any uncommented non whitespace characters. /// </summary> public bool IsEntirelyCommented() => !UncommentedSpansInSelection.Any() && HasIntersectingBlockComments(); /// <summary> /// Returns if the selection intersects with any block comments. /// </summary> public bool HasIntersectingBlockComments() => IntersectingBlockComments.Any(); public string GetSubstringFromText(int position, int length) => SnapshotSpan.Snapshot.GetText().Substring(position, length); /// <summary> /// Tries to get a block comment on the same line. There are two cases: /// 1. The caret is preceding a block comment on the same line, with only whitespace before the comment. /// 2. The caret is following a block comment on the same line, with only whitespace after the comment. /// </summary> public bool TryGetBlockCommentOnSameLine(ImmutableArray<TextSpan> allBlockComments, out TextSpan commentedSpanOnSameLine) { var snapshot = SnapshotSpan.Snapshot; var selectedLine = snapshot.GetLineFromPosition(SelectedSpan.Start); var lineStartToCaretIsWhitespace = IsSpanWhitespace(TextSpan.FromBounds(selectedLine.Start, SelectedSpan.Start)); var caretToLineEndIsWhitespace = IsSpanWhitespace(TextSpan.FromBounds(SelectedSpan.Start, selectedLine.End)); foreach (var blockComment in allBlockComments) { if (lineStartToCaretIsWhitespace && SelectedSpan.Start < blockComment.Start && snapshot.AreOnSameLine(SelectedSpan.Start, blockComment.Start)) { if (IsSpanWhitespace(TextSpan.FromBounds(SelectedSpan.Start, blockComment.Start))) { commentedSpanOnSameLine = blockComment; return true; } } else if (caretToLineEndIsWhitespace && SelectedSpan.Start > blockComment.End && snapshot.AreOnSameLine(SelectedSpan.Start, blockComment.End)) { if (IsSpanWhitespace(TextSpan.FromBounds(blockComment.End, SelectedSpan.Start))) { commentedSpanOnSameLine = blockComment; return true; } } } commentedSpanOnSameLine = new TextSpan(); return false; } /// <summary> /// Gets a list of block comments that intersect the span. /// Spans are intersecting if 1 location is the same between them (empty spans look at the start). /// </summary> private static ImmutableArray<TextSpan> GetIntersectingBlockComments(ImmutableArray<TextSpan> allBlockComments, TextSpan span) => allBlockComments.WhereAsArray(blockCommentSpan => span.OverlapsWith(blockCommentSpan) || blockCommentSpan.Contains(span)); /// <summary> /// Retrieves all non commented, non whitespace spans. /// </summary> private ImmutableArray<TextSpan> GetUncommentedSpansInSelection() { var uncommentedSpans = new List<TextSpan>(); // Invert the commented spans to get the uncommented spans. var spanStart = SelectedSpan.Start; foreach (var commentedSpan in IntersectingBlockComments) { if (commentedSpan.Start > spanStart) { // Get span up until the comment and check to make sure it is not whitespace. var possibleUncommentedSpan = TextSpan.FromBounds(spanStart, commentedSpan.Start); if (!IsSpanWhitespace(possibleUncommentedSpan)) { uncommentedSpans.Add(possibleUncommentedSpan); } } // The next possible uncommented span starts at the end of this commented span. spanStart = commentedSpan.End; } // If part of the selection is left over, it's not commented. Add if not whitespace. if (spanStart < SelectedSpan.End) { var uncommentedSpan = TextSpan.FromBounds(spanStart, SelectedSpan.End); if (!IsSpanWhitespace(uncommentedSpan)) { uncommentedSpans.Add(uncommentedSpan); } } return uncommentedSpans.ToImmutableArray(); } } } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 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
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Test/Diagnostics/PerfMargin/DataModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Internal.Log; using Roslyn.Utilities; namespace Roslyn.Hosting.Diagnostics.PerfMargin { internal class DataModel { public ActivityLevel RootNode { get; } private readonly ActivityLevel[] _activities; public DataModel() { var functions = from f in typeof(FunctionId).GetFields() where !f.IsSpecialName select f; var count = functions.Count(); _activities = new ActivityLevel[count]; var features = new Dictionary<string, ActivityLevel>(); var root = new ActivityLevel("All"); foreach (var function in functions) { var value = (int)function.GetRawConstantValue(); var name = function.Name; var featureNames = name.Split('_'); var featureName = featureNames.Length > 1 ? featureNames[0] : "Uncategorized"; if (!features.TryGetValue(featureName, out var parent)) { parent = new ActivityLevel(featureName, root, createChildList: true); features[featureName] = parent; } _activities[value - 1] = new ActivityLevel(name, parent, createChildList: false); } root.SortChildren(); this.RootNode = root; } public void BlockStart(FunctionId functionId) { _activities[(int)functionId - 1].Start(); } public void BlockDisposed(FunctionId functionId) { _activities[(int)functionId - 1].Stop(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Internal.Log; using Roslyn.Utilities; namespace Roslyn.Hosting.Diagnostics.PerfMargin { internal class DataModel { public ActivityLevel RootNode { get; } private readonly ActivityLevel[] _activities; public DataModel() { var functions = from f in typeof(FunctionId).GetFields() where !f.IsSpecialName select f; var count = functions.Count(); _activities = new ActivityLevel[count]; var features = new Dictionary<string, ActivityLevel>(); var root = new ActivityLevel("All"); foreach (var function in functions) { var value = (int)function.GetRawConstantValue(); var name = function.Name; var featureNames = name.Split('_'); var featureName = featureNames.Length > 1 ? featureNames[0] : "Uncategorized"; if (!features.TryGetValue(featureName, out var parent)) { parent = new ActivityLevel(featureName, root, createChildList: true); features[featureName] = parent; } _activities[value - 1] = new ActivityLevel(name, parent, createChildList: false); } root.SortChildren(); this.RootNode = root; } public void BlockStart(FunctionId functionId) { _activities[(int)functionId - 1].Start(); } public void BlockDisposed(FunctionId functionId) { _activities[(int)functionId - 1].Stop(); } } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Test/Semantic/Semantics/NullCoalesceAssignmentTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.NullCoalescingAssignment)] public partial class NullCoalesceAssignmentTests : SemanticModelTestBase { [Fact] public void CoalescingAssignment_NoConversion() { var source = @" class C { void M(C c1, C c2) { c1 ??= c2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); var cType = comp.GetTypeByMetadataName("C"); var syntaxTree = comp.SyntaxTrees.Single(); var syntaxRoot = syntaxTree.GetRoot(); var semanticModel = comp.GetSemanticModel(syntaxTree); var coalesceAssignment = syntaxRoot.DescendantNodes().OfType<AssignmentExpressionSyntax>().Single(); assertTypeInfo(coalesceAssignment); assertTypeInfo(coalesceAssignment.Left); assertTypeInfo(coalesceAssignment.Right); void assertTypeInfo(SyntaxNode syntax) { var typeInfo = semanticModel.GetTypeInfo(syntax); Assert.NotEqual(default, typeInfo); Assert.NotNull(typeInfo.Type); Assert.Equal(cType.GetPublicSymbol(), typeInfo.Type); Assert.Equal(cType.GetPublicSymbol(), typeInfo.ConvertedType); } } [Fact] public void CoalescingAssignment_ValueConversion() { var source = @" class C { void M(C c1, D d1) { c1 ??= d1; } } class D : C {}"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); var cType = comp.GetTypeByMetadataName("C"); var dType = comp.GetTypeByMetadataName("D"); var syntaxTree = comp.SyntaxTrees.Single(); var syntaxRoot = syntaxTree.GetRoot(); var semanticModel = comp.GetSemanticModel(syntaxTree); var coalesceAssignment = syntaxRoot.DescendantNodes().OfType<AssignmentExpressionSyntax>().Single(); assertTypeInfo(coalesceAssignment); assertTypeInfo(coalesceAssignment.Left); var whenNullTypeInfo = semanticModel.GetTypeInfo(coalesceAssignment.Right); Assert.NotEqual(default, whenNullTypeInfo); Assert.Equal(dType.GetPublicSymbol(), whenNullTypeInfo.Type); Assert.Equal(cType, whenNullTypeInfo.ConvertedType.GetSymbol()); void assertTypeInfo(SyntaxNode syntax) { var typeInfo = semanticModel.GetTypeInfo(syntax); Assert.NotEqual(default, typeInfo); Assert.NotNull(typeInfo.Type); Assert.Equal(cType, typeInfo.Type.GetSymbol()); Assert.Equal(cType.GetPublicSymbol(), typeInfo.ConvertedType); } } [Fact] public void CoalescingAssignment_AsConvertedExpression() { var source = @" class C { void M(D d1, D d2) { M2(d1 ??= d1); } void M2(C c) {} } class D : C {}"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); var cType = comp.GetTypeByMetadataName("C"); var dType = comp.GetTypeByMetadataName("D"); var syntaxTree = comp.SyntaxTrees.Single(); var syntaxRoot = syntaxTree.GetRoot(); var semanticModel = comp.GetSemanticModel(syntaxTree); var coalesceAssignment = syntaxRoot.DescendantNodes().OfType<AssignmentExpressionSyntax>().Single(); var whenNullTypeInfo = semanticModel.GetTypeInfo(coalesceAssignment); Assert.NotEqual(default, whenNullTypeInfo); Assert.Equal(dType, whenNullTypeInfo.Type.GetSymbol()); Assert.Equal(cType.GetPublicSymbol(), whenNullTypeInfo.ConvertedType); assertTypeInfo(coalesceAssignment.Right); assertTypeInfo(coalesceAssignment.Left); void assertTypeInfo(SyntaxNode syntax) { var typeInfo = semanticModel.GetTypeInfo(syntax); Assert.NotEqual(default, typeInfo); Assert.NotNull(typeInfo.Type); Assert.Equal(dType.GetPublicSymbol(), typeInfo.Type); Assert.Equal(dType, typeInfo.ConvertedType.GetSymbol()); } } [Fact] public void CoalesceAssignment_ConvertedToNonNullable() { var source = @" class C { void M(int? a, int b) { a ??= b; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); var syntaxTree = comp.SyntaxTrees.Single(); var syntaxRoot = syntaxTree.GetRoot(); var semanticModel = comp.GetSemanticModel(syntaxTree); var coalesceAssignment = syntaxRoot.DescendantNodes().OfType<AssignmentExpressionSyntax>().Single(); var int32 = comp.GetSpecialType(SpecialType.System_Int32); var coalesceType = semanticModel.GetTypeInfo(coalesceAssignment).Type; Assert.Equal(int32.GetPublicSymbol(), coalesceType); } [Fact] public void CoalesceAssignment_DefaultConvertedToNonNullable() { var source = @" class C { void M(int? a) { a ??= default; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var syntaxTree = comp.SyntaxTrees.Single(); var syntaxRoot = syntaxTree.GetRoot(); var semanticModel = comp.GetSemanticModel(syntaxTree); var defaultLiteral = syntaxRoot.DescendantNodes().OfType<LiteralExpressionSyntax>().Where(expr => expr.IsKind(SyntaxKind.DefaultLiteralExpression)).Single(); Assert.Equal(SpecialType.System_Int32, semanticModel.GetTypeInfo(defaultLiteral).Type.SpecialType); Assert.Equal(SpecialType.System_Int32, semanticModel.GetTypeInfo(defaultLiteral).ConvertedType.SpecialType); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.NullCoalescingAssignment)] public partial class NullCoalesceAssignmentTests : SemanticModelTestBase { [Fact] public void CoalescingAssignment_NoConversion() { var source = @" class C { void M(C c1, C c2) { c1 ??= c2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); var cType = comp.GetTypeByMetadataName("C"); var syntaxTree = comp.SyntaxTrees.Single(); var syntaxRoot = syntaxTree.GetRoot(); var semanticModel = comp.GetSemanticModel(syntaxTree); var coalesceAssignment = syntaxRoot.DescendantNodes().OfType<AssignmentExpressionSyntax>().Single(); assertTypeInfo(coalesceAssignment); assertTypeInfo(coalesceAssignment.Left); assertTypeInfo(coalesceAssignment.Right); void assertTypeInfo(SyntaxNode syntax) { var typeInfo = semanticModel.GetTypeInfo(syntax); Assert.NotEqual(default, typeInfo); Assert.NotNull(typeInfo.Type); Assert.Equal(cType.GetPublicSymbol(), typeInfo.Type); Assert.Equal(cType.GetPublicSymbol(), typeInfo.ConvertedType); } } [Fact] public void CoalescingAssignment_ValueConversion() { var source = @" class C { void M(C c1, D d1) { c1 ??= d1; } } class D : C {}"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); var cType = comp.GetTypeByMetadataName("C"); var dType = comp.GetTypeByMetadataName("D"); var syntaxTree = comp.SyntaxTrees.Single(); var syntaxRoot = syntaxTree.GetRoot(); var semanticModel = comp.GetSemanticModel(syntaxTree); var coalesceAssignment = syntaxRoot.DescendantNodes().OfType<AssignmentExpressionSyntax>().Single(); assertTypeInfo(coalesceAssignment); assertTypeInfo(coalesceAssignment.Left); var whenNullTypeInfo = semanticModel.GetTypeInfo(coalesceAssignment.Right); Assert.NotEqual(default, whenNullTypeInfo); Assert.Equal(dType.GetPublicSymbol(), whenNullTypeInfo.Type); Assert.Equal(cType, whenNullTypeInfo.ConvertedType.GetSymbol()); void assertTypeInfo(SyntaxNode syntax) { var typeInfo = semanticModel.GetTypeInfo(syntax); Assert.NotEqual(default, typeInfo); Assert.NotNull(typeInfo.Type); Assert.Equal(cType, typeInfo.Type.GetSymbol()); Assert.Equal(cType.GetPublicSymbol(), typeInfo.ConvertedType); } } [Fact] public void CoalescingAssignment_AsConvertedExpression() { var source = @" class C { void M(D d1, D d2) { M2(d1 ??= d1); } void M2(C c) {} } class D : C {}"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); var cType = comp.GetTypeByMetadataName("C"); var dType = comp.GetTypeByMetadataName("D"); var syntaxTree = comp.SyntaxTrees.Single(); var syntaxRoot = syntaxTree.GetRoot(); var semanticModel = comp.GetSemanticModel(syntaxTree); var coalesceAssignment = syntaxRoot.DescendantNodes().OfType<AssignmentExpressionSyntax>().Single(); var whenNullTypeInfo = semanticModel.GetTypeInfo(coalesceAssignment); Assert.NotEqual(default, whenNullTypeInfo); Assert.Equal(dType, whenNullTypeInfo.Type.GetSymbol()); Assert.Equal(cType.GetPublicSymbol(), whenNullTypeInfo.ConvertedType); assertTypeInfo(coalesceAssignment.Right); assertTypeInfo(coalesceAssignment.Left); void assertTypeInfo(SyntaxNode syntax) { var typeInfo = semanticModel.GetTypeInfo(syntax); Assert.NotEqual(default, typeInfo); Assert.NotNull(typeInfo.Type); Assert.Equal(dType.GetPublicSymbol(), typeInfo.Type); Assert.Equal(dType, typeInfo.ConvertedType.GetSymbol()); } } [Fact] public void CoalesceAssignment_ConvertedToNonNullable() { var source = @" class C { void M(int? a, int b) { a ??= b; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); var syntaxTree = comp.SyntaxTrees.Single(); var syntaxRoot = syntaxTree.GetRoot(); var semanticModel = comp.GetSemanticModel(syntaxTree); var coalesceAssignment = syntaxRoot.DescendantNodes().OfType<AssignmentExpressionSyntax>().Single(); var int32 = comp.GetSpecialType(SpecialType.System_Int32); var coalesceType = semanticModel.GetTypeInfo(coalesceAssignment).Type; Assert.Equal(int32.GetPublicSymbol(), coalesceType); } [Fact] public void CoalesceAssignment_DefaultConvertedToNonNullable() { var source = @" class C { void M(int? a) { a ??= default; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var syntaxTree = comp.SyntaxTrees.Single(); var syntaxRoot = syntaxTree.GetRoot(); var semanticModel = comp.GetSemanticModel(syntaxTree); var defaultLiteral = syntaxRoot.DescendantNodes().OfType<LiteralExpressionSyntax>().Where(expr => expr.IsKind(SyntaxKind.DefaultLiteralExpression)).Single(); Assert.Equal(SpecialType.System_Int32, semanticModel.GetTypeInfo(defaultLiteral).Type.SpecialType); Assert.Equal(SpecialType.System_Int32, semanticModel.GetTypeInfo(defaultLiteral).ConvertedType.SpecialType); } } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Analyzers/CSharp/Analyzers/UseIsNullCheck/CSharpUseNullCheckOverTypeCheckDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.UseIsNullCheck { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class CSharpUseNullCheckOverTypeCheckDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public CSharpUseNullCheckOverTypeCheckDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseNullCheckOverTypeCheckDiagnosticId, EnforceOnBuildValues.UseNullCheckOverTypeCheck, CSharpCodeStyleOptions.PreferNullCheckOverTypeCheck, LanguageNames.CSharp, new LocalizableResourceString(nameof(CSharpAnalyzersResources.Prefer_null_check_over_type_check), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)), new LocalizableResourceString(nameof(CSharpAnalyzersResources.Null_check_can_be_clarified), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) { context.RegisterCompilationStartAction(context => { if (((CSharpCompilation)context.Compilation).LanguageVersion < LanguageVersion.CSharp9) { return; } context.RegisterOperationAction(c => AnalyzeIsTypeOperation(c), OperationKind.IsType); context.RegisterOperationAction(c => AnalyzeNegatedPatternOperation(c), OperationKind.NegatedPattern); }); } private static bool ShouldAnalyze(OperationAnalysisContext context, out ReportDiagnostic severity) { var option = context.Options.GetOption(CSharpCodeStyleOptions.PreferNullCheckOverTypeCheck, context.Operation.Syntax.SyntaxTree, context.CancellationToken); if (!option.Value) { severity = ReportDiagnostic.Default; return false; } severity = option.Notification.Severity; return true; } private void AnalyzeNegatedPatternOperation(OperationAnalysisContext context) { if (!ShouldAnalyze(context, out var severity) || context.Operation.Syntax is not UnaryPatternSyntax) { return; } var negatedPattern = (INegatedPatternOperation)context.Operation; // Matches 'x is not MyType' // InputType is the type of 'x' // MatchedType is 'MyType' // We check InheritsFromOrEquals so that we report a diagnostic on the following: // 1. x is not object (which is also equivalent to 'is null' check) // 2. derivedObj is parentObj (which is the same as the previous point). // 3. str is string (where str is a string, this is also equivalent to 'is null' check). // This doesn't match `x is not MyType y` because in such case, negatedPattern.Pattern will // be `DeclarationPattern`, not `TypePattern`. if (negatedPattern.Pattern is ITypePatternOperation typePatternOperation && typePatternOperation.InputType.InheritsFromOrEquals(typePatternOperation.MatchedType)) { context.ReportDiagnostic( DiagnosticHelper.Create( Descriptor, context.Operation.Syntax.GetLocation(), severity, additionalLocations: null, properties: null)); } } private void AnalyzeIsTypeOperation(OperationAnalysisContext context) { if (!ShouldAnalyze(context, out var severity) || context.Operation.Syntax is not BinaryExpressionSyntax) { return; } var isTypeOperation = (IIsTypeOperation)context.Operation; // Matches 'x is MyType' // isTypeOperation.TypeOperand is 'MyType' // isTypeOperation.ValueOperand.Type is the type of 'x'. // We check InheritsFromOrEquals for the same reason as stated in AnalyzeNegatedPatternOperation. // This doesn't match `x is MyType y` because in such case, we have an IsPattern instead of IsType operation. if (isTypeOperation.ValueOperand.Type is not null && isTypeOperation.ValueOperand.Type.InheritsFromOrEquals(isTypeOperation.TypeOperand)) { context.ReportDiagnostic( DiagnosticHelper.Create( Descriptor, context.Operation.Syntax.GetLocation(), severity, additionalLocations: null, properties: null)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.UseIsNullCheck { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class CSharpUseNullCheckOverTypeCheckDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public CSharpUseNullCheckOverTypeCheckDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseNullCheckOverTypeCheckDiagnosticId, EnforceOnBuildValues.UseNullCheckOverTypeCheck, CSharpCodeStyleOptions.PreferNullCheckOverTypeCheck, LanguageNames.CSharp, new LocalizableResourceString(nameof(CSharpAnalyzersResources.Prefer_null_check_over_type_check), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)), new LocalizableResourceString(nameof(CSharpAnalyzersResources.Null_check_can_be_clarified), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) { context.RegisterCompilationStartAction(context => { if (((CSharpCompilation)context.Compilation).LanguageVersion < LanguageVersion.CSharp9) { return; } context.RegisterOperationAction(c => AnalyzeIsTypeOperation(c), OperationKind.IsType); context.RegisterOperationAction(c => AnalyzeNegatedPatternOperation(c), OperationKind.NegatedPattern); }); } private static bool ShouldAnalyze(OperationAnalysisContext context, out ReportDiagnostic severity) { var option = context.Options.GetOption(CSharpCodeStyleOptions.PreferNullCheckOverTypeCheck, context.Operation.Syntax.SyntaxTree, context.CancellationToken); if (!option.Value) { severity = ReportDiagnostic.Default; return false; } severity = option.Notification.Severity; return true; } private void AnalyzeNegatedPatternOperation(OperationAnalysisContext context) { if (!ShouldAnalyze(context, out var severity) || context.Operation.Syntax is not UnaryPatternSyntax) { return; } var negatedPattern = (INegatedPatternOperation)context.Operation; // Matches 'x is not MyType' // InputType is the type of 'x' // MatchedType is 'MyType' // We check InheritsFromOrEquals so that we report a diagnostic on the following: // 1. x is not object (which is also equivalent to 'is null' check) // 2. derivedObj is parentObj (which is the same as the previous point). // 3. str is string (where str is a string, this is also equivalent to 'is null' check). // This doesn't match `x is not MyType y` because in such case, negatedPattern.Pattern will // be `DeclarationPattern`, not `TypePattern`. if (negatedPattern.Pattern is ITypePatternOperation typePatternOperation && typePatternOperation.InputType.InheritsFromOrEquals(typePatternOperation.MatchedType)) { context.ReportDiagnostic( DiagnosticHelper.Create( Descriptor, context.Operation.Syntax.GetLocation(), severity, additionalLocations: null, properties: null)); } } private void AnalyzeIsTypeOperation(OperationAnalysisContext context) { if (!ShouldAnalyze(context, out var severity) || context.Operation.Syntax is not BinaryExpressionSyntax) { return; } var isTypeOperation = (IIsTypeOperation)context.Operation; // Matches 'x is MyType' // isTypeOperation.TypeOperand is 'MyType' // isTypeOperation.ValueOperand.Type is the type of 'x'. // We check InheritsFromOrEquals for the same reason as stated in AnalyzeNegatedPatternOperation. // This doesn't match `x is MyType y` because in such case, we have an IsPattern instead of IsType operation. if (isTypeOperation.ValueOperand.Type is not null && isTypeOperation.ValueOperand.Type.InheritsFromOrEquals(isTypeOperation.TypeOperand)) { context.ReportDiagnostic( DiagnosticHelper.Create( Descriptor, context.Operation.Syntax.GetLocation(), severity, additionalLocations: null, properties: null)); } } } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/Core/Portable/Shared/Extensions/SyntaxGeneratorExtensions_CreateEqualsMethod.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class SyntaxGeneratorExtensions { public static IMethodSymbol CreateEqualsMethod( this SyntaxGenerator factory, SyntaxGeneratorInternal generatorInternal, Compilation compilation, ParseOptions parseOptions, INamedTypeSymbol containingType, ImmutableArray<ISymbol> symbols, string localNameOpt, SyntaxAnnotation statementAnnotation) { var statements = CreateEqualsMethodStatements( factory, generatorInternal, compilation, parseOptions, containingType, symbols, localNameOpt); statements = statements.SelectAsArray(s => s.WithAdditionalAnnotations(statementAnnotation)); return CreateEqualsMethod(compilation, statements); } public static IMethodSymbol CreateEqualsMethod(this Compilation compilation, ImmutableArray<SyntaxNode> statements) { return CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: default, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isOverride: true), returnType: compilation.GetSpecialType(SpecialType.System_Boolean), refKind: RefKind.None, explicitInterfaceImplementations: default, name: EqualsName, typeParameters: default, parameters: ImmutableArray.Create(CodeGenerationSymbolFactory.CreateParameterSymbol(compilation.GetSpecialType(SpecialType.System_Object).WithNullableAnnotation(NullableAnnotation.Annotated), ObjName)), statements: statements); } public static IMethodSymbol CreateIEquatableEqualsMethod( this SyntaxGenerator factory, SyntaxGeneratorInternal generatorInternal, SemanticModel semanticModel, INamedTypeSymbol containingType, ImmutableArray<ISymbol> symbols, INamedTypeSymbol constructedEquatableType, SyntaxAnnotation statementAnnotation) { var statements = CreateIEquatableEqualsMethodStatements( factory, generatorInternal, semanticModel.Compilation, containingType, symbols); statements = statements.SelectAsArray(s => s.WithAdditionalAnnotations(statementAnnotation)); var methodSymbol = constructedEquatableType .GetMembers(EqualsName) .OfType<IMethodSymbol>() .Single(m => containingType.Equals(m.Parameters.FirstOrDefault()?.Type)); var originalParameter = methodSymbol.Parameters.First(); // Replace `[AllowNull] Foo` with `Foo` or `Foo?` (no longer needed after https://github.com/dotnet/roslyn/issues/39256?) var parameters = ImmutableArray.Create(CodeGenerationSymbolFactory.CreateParameterSymbol( originalParameter, type: constructedEquatableType.GetTypeArguments()[0], attributes: ImmutableArray<AttributeData>.Empty)); if (factory.RequiresExplicitImplementationForInterfaceMembers) { return CodeGenerationSymbolFactory.CreateMethodSymbol( methodSymbol, modifiers: new DeclarationModifiers(), explicitInterfaceImplementations: ImmutableArray.Create(methodSymbol), parameters: parameters, statements: statements); } else { return CodeGenerationSymbolFactory.CreateMethodSymbol( methodSymbol, modifiers: new DeclarationModifiers(), parameters: parameters, statements: statements); } } private static ImmutableArray<SyntaxNode> CreateEqualsMethodStatements( SyntaxGenerator factory, SyntaxGeneratorInternal generatorInternal, Compilation compilation, ParseOptions parseOptions, INamedTypeSymbol containingType, ImmutableArray<ISymbol> members, string localNameOpt) { using var _1 = ArrayBuilder<SyntaxNode>.GetInstance(out var statements); // A ref like type can not be boxed. Because of this an overloaded Equals taking object in the general case // can never be true, because an equivalent object can never be boxed into the object itself. Therefore only // need to return false. if (containingType.IsRefLikeType) { statements.Add(factory.ReturnStatement(factory.FalseLiteralExpression())); return statements.ToImmutable(); } // Come up with a good name for the local variable we're going to compare against. // For example, if the class name is "CustomerOrder" then we'll generate: // // var order = obj as CustomerOrder; var localName = localNameOpt ?? GetLocalName(containingType); var localNameExpression = factory.IdentifierName(localName); var objNameExpression = factory.IdentifierName(ObjName); // These will be all the expressions that we'll '&&' together inside the final // return statement of 'Equals'. using var _2 = ArrayBuilder<SyntaxNode>.GetInstance(out var expressions); if (factory.SyntaxGeneratorInternal.SupportsPatterns(parseOptions)) { // If we support patterns then we can do "return obj is MyType myType && ..." expressions.Add( factory.SyntaxGeneratorInternal.IsPatternExpression(objNameExpression, factory.SyntaxGeneratorInternal.DeclarationPattern(containingType, localName))); } else if (containingType.IsValueType) { // If we're a value type, then we need an is-check first to make sure // the object is our type: // // if (!(obj is MyType)) // { // return false; // } var ifStatement = factory.IfStatement( factory.LogicalNotExpression( factory.IsTypeExpression( objNameExpression, containingType)), new[] { factory.ReturnStatement(factory.FalseLiteralExpression()) }); // Next, we cast the argument to our type: // // var myType = (MyType)obj; var localDeclaration = factory.SimpleLocalDeclarationStatement(factory.SyntaxGeneratorInternal, containingType, localName, factory.CastExpression(containingType, objNameExpression)); statements.Add(ifStatement); statements.Add(localDeclaration); } else { // It's not a value type, we can just use "as" to test the parameter is the right type: // // var myType = obj as MyType; var localDeclaration = factory.SimpleLocalDeclarationStatement(factory.SyntaxGeneratorInternal, containingType, localName, factory.TryCastExpression(objNameExpression, containingType)); statements.Add(localDeclaration); // Ensure that the parameter we got was not null (which also ensures the 'as' test // succeeded): // // myType != null expressions.Add(factory.ReferenceNotEqualsExpression(localNameExpression, factory.NullLiteralExpression())); } if (!containingType.IsValueType && HasExistingBaseEqualsMethod(containingType)) { // If we're overriding something that also provided an overridden 'Equals', // then ensure the base type thinks it is equals as well. // // base.Equals(obj) expressions.Add(factory.InvocationExpression( factory.MemberAccessExpression( factory.BaseExpression(), factory.IdentifierName(EqualsName)), objNameExpression)); } AddMemberChecks(factory, generatorInternal, compilation, members, localNameExpression, expressions); // Now combine all the comparison expressions together into one final statement like: // // return myType != null && // base.Equals(obj) && // this.S1 == myType.S1; statements.Add(factory.ReturnStatement( expressions.Aggregate(factory.LogicalAndExpression))); return statements.ToImmutable(); } private static void AddMemberChecks( SyntaxGenerator factory, SyntaxGeneratorInternal generatorInternal, Compilation compilation, ImmutableArray<ISymbol> members, SyntaxNode localNameExpression, ArrayBuilder<SyntaxNode> expressions) { var iequatableType = compilation.GetTypeByMetadataName(typeof(IEquatable<>).FullName); // Now, iterate over all the supplied members and ensure that our instance // and the parameter think they are equals. Specialize how we do this for // common types. Fall-back to EqualityComparer<SType>.Default.Equals for // everything else. foreach (var member in members) { var symbolNameExpression = factory.IdentifierName(member.Name); var thisSymbol = factory.MemberAccessExpression(factory.ThisExpression(), symbolNameExpression) .WithAdditionalAnnotations(Simplification.Simplifier.Annotation); var otherSymbol = factory.MemberAccessExpression(localNameExpression, symbolNameExpression); var memberType = member.GetSymbolType(); if (ShouldUseEqualityOperator(memberType)) { expressions.Add(factory.ValueEqualsExpression(thisSymbol, otherSymbol)); continue; } var valueIEquatable = memberType?.IsValueType == true && ImplementsIEquatable(memberType, iequatableType); if (valueIEquatable || memberType?.IsTupleType == true) { // If it's a value type and implements IEquatable<T>, Or if it's a tuple, then // just call directly into .Equals. This keeps the code simple and avoids an // unnecessary null check. // // this.a.Equals(other.a) expressions.Add(factory.InvocationExpression( factory.MemberAccessExpression(thisSymbol, nameof(object.Equals)), otherSymbol)); continue; } // Otherwise call EqualityComparer<SType>.Default.Equals(this.a, other.a). // This will do the appropriate null checks as well as calling directly // into IEquatable<T>.Equals implementations if available. expressions.Add(factory.InvocationExpression( factory.MemberAccessExpression( GetDefaultEqualityComparer(factory, generatorInternal, compilation, GetType(compilation, member)), factory.IdentifierName(EqualsName)), thisSymbol, otherSymbol)); } } private static ImmutableArray<SyntaxNode> CreateIEquatableEqualsMethodStatements( SyntaxGenerator factory, SyntaxGeneratorInternal generatorInternal, Compilation compilation, INamedTypeSymbol containingType, ImmutableArray<ISymbol> members) { var statements = ArrayBuilder<SyntaxNode>.GetInstance(); var otherNameExpression = factory.IdentifierName(OtherName); // These will be all the expressions that we'll '&&' together inside the final // return statement of 'Equals'. using var _ = ArrayBuilder<SyntaxNode>.GetInstance(out var expressions); if (!containingType.IsValueType) { // It's not a value type. Ensure that the parameter we got was not null. // // other != null expressions.Add(factory.ReferenceNotEqualsExpression(otherNameExpression, factory.NullLiteralExpression())); if (HasExistingBaseEqualsMethod(containingType)) { // If we're overriding something that also provided an overridden 'Equals', // then ensure the base type thinks it is equals as well. // // base.Equals(obj) expressions.Add(factory.InvocationExpression( factory.MemberAccessExpression( factory.BaseExpression(), factory.IdentifierName(EqualsName)), otherNameExpression)); } } AddMemberChecks(factory, generatorInternal, compilation, members, otherNameExpression, expressions); // Now combine all the comparison expressions together into one final statement like: // // return other != null && // base.Equals(other) && // this.S1 == other.S1; statements.Add(factory.ReturnStatement( expressions.Aggregate(factory.LogicalAndExpression))); return statements.ToImmutableAndFree(); } public static string GetLocalName(this ITypeSymbol containingType) { var name = containingType.Name; if (name.Length > 0) { using var parts = TemporaryArray<TextSpan>.Empty; StringBreaker.AddWordParts(name, ref parts.AsRef()); for (var i = parts.Count - 1; i >= 0; i--) { var p = parts[i]; if (p.Length > 0 && char.IsLetter(name[p.Start])) { return name.Substring(p.Start, p.Length).ToCamelCase(); } } } return "v"; } private static bool ImplementsIEquatable(ITypeSymbol memberType, INamedTypeSymbol iequatableType) { if (iequatableType != null) { // We compare ignoring nested nullability here, as it's possible the underlying object could have implemented IEquatable<Type> // or IEquatable<Type?>. From the perspective of this, either is allowable. var constructed = iequatableType.Construct(memberType); return memberType.AllInterfaces.Contains(constructed, equalityComparer: SymbolEqualityComparer.Default); } return false; } private static bool ShouldUseEqualityOperator(ITypeSymbol typeSymbol) { if (typeSymbol != null) { if (typeSymbol.IsNullable(out var underlyingType)) { typeSymbol = underlyingType; } if (typeSymbol.IsEnumType()) { return true; } switch (typeSymbol.SpecialType) { case SpecialType.System_Boolean: case SpecialType.System_Char: case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Decimal: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_String: case SpecialType.System_DateTime: return true; } } return false; } private static bool HasExistingBaseEqualsMethod(INamedTypeSymbol containingType) { // Check if any of our base types override Equals. If so, first check with them. var existingMethods = from baseType in containingType.GetBaseTypes() from method in baseType.GetMembers(EqualsName).OfType<IMethodSymbol>() where method.IsOverride && method.DeclaredAccessibility == Accessibility.Public && !method.IsStatic && method.Parameters.Length == 1 && method.ReturnType.SpecialType == SpecialType.System_Boolean && method.Parameters[0].Type.SpecialType == SpecialType.System_Object && !method.IsAbstract select method; return existingMethods.Any(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class SyntaxGeneratorExtensions { public static IMethodSymbol CreateEqualsMethod( this SyntaxGenerator factory, SyntaxGeneratorInternal generatorInternal, Compilation compilation, ParseOptions parseOptions, INamedTypeSymbol containingType, ImmutableArray<ISymbol> symbols, string localNameOpt, SyntaxAnnotation statementAnnotation) { var statements = CreateEqualsMethodStatements( factory, generatorInternal, compilation, parseOptions, containingType, symbols, localNameOpt); statements = statements.SelectAsArray(s => s.WithAdditionalAnnotations(statementAnnotation)); return CreateEqualsMethod(compilation, statements); } public static IMethodSymbol CreateEqualsMethod(this Compilation compilation, ImmutableArray<SyntaxNode> statements) { return CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: default, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isOverride: true), returnType: compilation.GetSpecialType(SpecialType.System_Boolean), refKind: RefKind.None, explicitInterfaceImplementations: default, name: EqualsName, typeParameters: default, parameters: ImmutableArray.Create(CodeGenerationSymbolFactory.CreateParameterSymbol(compilation.GetSpecialType(SpecialType.System_Object).WithNullableAnnotation(NullableAnnotation.Annotated), ObjName)), statements: statements); } public static IMethodSymbol CreateIEquatableEqualsMethod( this SyntaxGenerator factory, SyntaxGeneratorInternal generatorInternal, SemanticModel semanticModel, INamedTypeSymbol containingType, ImmutableArray<ISymbol> symbols, INamedTypeSymbol constructedEquatableType, SyntaxAnnotation statementAnnotation) { var statements = CreateIEquatableEqualsMethodStatements( factory, generatorInternal, semanticModel.Compilation, containingType, symbols); statements = statements.SelectAsArray(s => s.WithAdditionalAnnotations(statementAnnotation)); var methodSymbol = constructedEquatableType .GetMembers(EqualsName) .OfType<IMethodSymbol>() .Single(m => containingType.Equals(m.Parameters.FirstOrDefault()?.Type)); var originalParameter = methodSymbol.Parameters.First(); // Replace `[AllowNull] Foo` with `Foo` or `Foo?` (no longer needed after https://github.com/dotnet/roslyn/issues/39256?) var parameters = ImmutableArray.Create(CodeGenerationSymbolFactory.CreateParameterSymbol( originalParameter, type: constructedEquatableType.GetTypeArguments()[0], attributes: ImmutableArray<AttributeData>.Empty)); if (factory.RequiresExplicitImplementationForInterfaceMembers) { return CodeGenerationSymbolFactory.CreateMethodSymbol( methodSymbol, modifiers: new DeclarationModifiers(), explicitInterfaceImplementations: ImmutableArray.Create(methodSymbol), parameters: parameters, statements: statements); } else { return CodeGenerationSymbolFactory.CreateMethodSymbol( methodSymbol, modifiers: new DeclarationModifiers(), parameters: parameters, statements: statements); } } private static ImmutableArray<SyntaxNode> CreateEqualsMethodStatements( SyntaxGenerator factory, SyntaxGeneratorInternal generatorInternal, Compilation compilation, ParseOptions parseOptions, INamedTypeSymbol containingType, ImmutableArray<ISymbol> members, string localNameOpt) { using var _1 = ArrayBuilder<SyntaxNode>.GetInstance(out var statements); // A ref like type can not be boxed. Because of this an overloaded Equals taking object in the general case // can never be true, because an equivalent object can never be boxed into the object itself. Therefore only // need to return false. if (containingType.IsRefLikeType) { statements.Add(factory.ReturnStatement(factory.FalseLiteralExpression())); return statements.ToImmutable(); } // Come up with a good name for the local variable we're going to compare against. // For example, if the class name is "CustomerOrder" then we'll generate: // // var order = obj as CustomerOrder; var localName = localNameOpt ?? GetLocalName(containingType); var localNameExpression = factory.IdentifierName(localName); var objNameExpression = factory.IdentifierName(ObjName); // These will be all the expressions that we'll '&&' together inside the final // return statement of 'Equals'. using var _2 = ArrayBuilder<SyntaxNode>.GetInstance(out var expressions); if (factory.SyntaxGeneratorInternal.SupportsPatterns(parseOptions)) { // If we support patterns then we can do "return obj is MyType myType && ..." expressions.Add( factory.SyntaxGeneratorInternal.IsPatternExpression(objNameExpression, factory.SyntaxGeneratorInternal.DeclarationPattern(containingType, localName))); } else if (containingType.IsValueType) { // If we're a value type, then we need an is-check first to make sure // the object is our type: // // if (!(obj is MyType)) // { // return false; // } var ifStatement = factory.IfStatement( factory.LogicalNotExpression( factory.IsTypeExpression( objNameExpression, containingType)), new[] { factory.ReturnStatement(factory.FalseLiteralExpression()) }); // Next, we cast the argument to our type: // // var myType = (MyType)obj; var localDeclaration = factory.SimpleLocalDeclarationStatement(factory.SyntaxGeneratorInternal, containingType, localName, factory.CastExpression(containingType, objNameExpression)); statements.Add(ifStatement); statements.Add(localDeclaration); } else { // It's not a value type, we can just use "as" to test the parameter is the right type: // // var myType = obj as MyType; var localDeclaration = factory.SimpleLocalDeclarationStatement(factory.SyntaxGeneratorInternal, containingType, localName, factory.TryCastExpression(objNameExpression, containingType)); statements.Add(localDeclaration); // Ensure that the parameter we got was not null (which also ensures the 'as' test // succeeded): // // myType != null expressions.Add(factory.ReferenceNotEqualsExpression(localNameExpression, factory.NullLiteralExpression())); } if (!containingType.IsValueType && HasExistingBaseEqualsMethod(containingType)) { // If we're overriding something that also provided an overridden 'Equals', // then ensure the base type thinks it is equals as well. // // base.Equals(obj) expressions.Add(factory.InvocationExpression( factory.MemberAccessExpression( factory.BaseExpression(), factory.IdentifierName(EqualsName)), objNameExpression)); } AddMemberChecks(factory, generatorInternal, compilation, members, localNameExpression, expressions); // Now combine all the comparison expressions together into one final statement like: // // return myType != null && // base.Equals(obj) && // this.S1 == myType.S1; statements.Add(factory.ReturnStatement( expressions.Aggregate(factory.LogicalAndExpression))); return statements.ToImmutable(); } private static void AddMemberChecks( SyntaxGenerator factory, SyntaxGeneratorInternal generatorInternal, Compilation compilation, ImmutableArray<ISymbol> members, SyntaxNode localNameExpression, ArrayBuilder<SyntaxNode> expressions) { var iequatableType = compilation.GetTypeByMetadataName(typeof(IEquatable<>).FullName); // Now, iterate over all the supplied members and ensure that our instance // and the parameter think they are equals. Specialize how we do this for // common types. Fall-back to EqualityComparer<SType>.Default.Equals for // everything else. foreach (var member in members) { var symbolNameExpression = factory.IdentifierName(member.Name); var thisSymbol = factory.MemberAccessExpression(factory.ThisExpression(), symbolNameExpression) .WithAdditionalAnnotations(Simplification.Simplifier.Annotation); var otherSymbol = factory.MemberAccessExpression(localNameExpression, symbolNameExpression); var memberType = member.GetSymbolType(); if (ShouldUseEqualityOperator(memberType)) { expressions.Add(factory.ValueEqualsExpression(thisSymbol, otherSymbol)); continue; } var valueIEquatable = memberType?.IsValueType == true && ImplementsIEquatable(memberType, iequatableType); if (valueIEquatable || memberType?.IsTupleType == true) { // If it's a value type and implements IEquatable<T>, Or if it's a tuple, then // just call directly into .Equals. This keeps the code simple and avoids an // unnecessary null check. // // this.a.Equals(other.a) expressions.Add(factory.InvocationExpression( factory.MemberAccessExpression(thisSymbol, nameof(object.Equals)), otherSymbol)); continue; } // Otherwise call EqualityComparer<SType>.Default.Equals(this.a, other.a). // This will do the appropriate null checks as well as calling directly // into IEquatable<T>.Equals implementations if available. expressions.Add(factory.InvocationExpression( factory.MemberAccessExpression( GetDefaultEqualityComparer(factory, generatorInternal, compilation, GetType(compilation, member)), factory.IdentifierName(EqualsName)), thisSymbol, otherSymbol)); } } private static ImmutableArray<SyntaxNode> CreateIEquatableEqualsMethodStatements( SyntaxGenerator factory, SyntaxGeneratorInternal generatorInternal, Compilation compilation, INamedTypeSymbol containingType, ImmutableArray<ISymbol> members) { var statements = ArrayBuilder<SyntaxNode>.GetInstance(); var otherNameExpression = factory.IdentifierName(OtherName); // These will be all the expressions that we'll '&&' together inside the final // return statement of 'Equals'. using var _ = ArrayBuilder<SyntaxNode>.GetInstance(out var expressions); if (!containingType.IsValueType) { // It's not a value type. Ensure that the parameter we got was not null. // // other != null expressions.Add(factory.ReferenceNotEqualsExpression(otherNameExpression, factory.NullLiteralExpression())); if (HasExistingBaseEqualsMethod(containingType)) { // If we're overriding something that also provided an overridden 'Equals', // then ensure the base type thinks it is equals as well. // // base.Equals(obj) expressions.Add(factory.InvocationExpression( factory.MemberAccessExpression( factory.BaseExpression(), factory.IdentifierName(EqualsName)), otherNameExpression)); } } AddMemberChecks(factory, generatorInternal, compilation, members, otherNameExpression, expressions); // Now combine all the comparison expressions together into one final statement like: // // return other != null && // base.Equals(other) && // this.S1 == other.S1; statements.Add(factory.ReturnStatement( expressions.Aggregate(factory.LogicalAndExpression))); return statements.ToImmutableAndFree(); } public static string GetLocalName(this ITypeSymbol containingType) { var name = containingType.Name; if (name.Length > 0) { using var parts = TemporaryArray<TextSpan>.Empty; StringBreaker.AddWordParts(name, ref parts.AsRef()); for (var i = parts.Count - 1; i >= 0; i--) { var p = parts[i]; if (p.Length > 0 && char.IsLetter(name[p.Start])) { return name.Substring(p.Start, p.Length).ToCamelCase(); } } } return "v"; } private static bool ImplementsIEquatable(ITypeSymbol memberType, INamedTypeSymbol iequatableType) { if (iequatableType != null) { // We compare ignoring nested nullability here, as it's possible the underlying object could have implemented IEquatable<Type> // or IEquatable<Type?>. From the perspective of this, either is allowable. var constructed = iequatableType.Construct(memberType); return memberType.AllInterfaces.Contains(constructed, equalityComparer: SymbolEqualityComparer.Default); } return false; } private static bool ShouldUseEqualityOperator(ITypeSymbol typeSymbol) { if (typeSymbol != null) { if (typeSymbol.IsNullable(out var underlyingType)) { typeSymbol = underlyingType; } if (typeSymbol.IsEnumType()) { return true; } switch (typeSymbol.SpecialType) { case SpecialType.System_Boolean: case SpecialType.System_Char: case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Decimal: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_String: case SpecialType.System_DateTime: return true; } } return false; } private static bool HasExistingBaseEqualsMethod(INamedTypeSymbol containingType) { // Check if any of our base types override Equals. If so, first check with them. var existingMethods = from baseType in containingType.GetBaseTypes() from method in baseType.GetMembers(EqualsName).OfType<IMethodSymbol>() where method.IsOverride && method.DeclaredAccessibility == Accessibility.Public && !method.IsStatic && method.Parameters.Length == 1 && method.ReturnType.SpecialType == SpecialType.System_Boolean && method.Parameters[0].Type.SpecialType == SpecialType.System_Object && !method.IsAbstract select method; return existingMethods.Any(); } } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Core/Portable/Symbols/SymbolVisitor.cs
// Licensed to the .NET Foundation under one or more 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 { public abstract class SymbolVisitor { public virtual void Visit(ISymbol? symbol) { symbol?.Accept(this); } public virtual void DefaultVisit(ISymbol symbol) { } public virtual void VisitAlias(IAliasSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitArrayType(IArrayTypeSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitAssembly(IAssemblySymbol symbol) { DefaultVisit(symbol); } public virtual void VisitDiscard(IDiscardSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitDynamicType(IDynamicTypeSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitEvent(IEventSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitField(IFieldSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitLabel(ILabelSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitLocal(ILocalSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitMethod(IMethodSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitModule(IModuleSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitNamedType(INamedTypeSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitNamespace(INamespaceSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitParameter(IParameterSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitPointerType(IPointerTypeSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitProperty(IPropertySymbol symbol) { DefaultVisit(symbol); } public virtual void VisitRangeVariable(IRangeVariableSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitTypeParameter(ITypeParameterSymbol symbol) { DefaultVisit(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. namespace Microsoft.CodeAnalysis { public abstract class SymbolVisitor { public virtual void Visit(ISymbol? symbol) { symbol?.Accept(this); } public virtual void DefaultVisit(ISymbol symbol) { } public virtual void VisitAlias(IAliasSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitArrayType(IArrayTypeSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitAssembly(IAssemblySymbol symbol) { DefaultVisit(symbol); } public virtual void VisitDiscard(IDiscardSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitDynamicType(IDynamicTypeSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitEvent(IEventSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitField(IFieldSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitLabel(ILabelSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitLocal(ILocalSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitMethod(IMethodSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitModule(IModuleSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitNamedType(INamedTypeSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitNamespace(INamespaceSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitParameter(IParameterSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitPointerType(IPointerTypeSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitProperty(IPropertySymbol symbol) { DefaultVisit(symbol); } public virtual void VisitRangeVariable(IRangeVariableSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitTypeParameter(ITypeParameterSymbol symbol) { DefaultVisit(symbol); } } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedProperty.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeGen; using Cci = Microsoft.Cci; namespace Microsoft.CodeAnalysis.Emit.NoPia { internal abstract partial class EmbeddedTypesManager< TPEModuleBuilder, TModuleCompilationState, TEmbeddedTypesManager, TSyntaxNode, TAttributeData, TSymbol, TAssemblySymbol, TNamedTypeSymbol, TFieldSymbol, TMethodSymbol, TEventSymbol, TPropertySymbol, TParameterSymbol, TTypeParameterSymbol, TEmbeddedType, TEmbeddedField, TEmbeddedMethod, TEmbeddedEvent, TEmbeddedProperty, TEmbeddedParameter, TEmbeddedTypeParameter> { internal abstract class CommonEmbeddedProperty : CommonEmbeddedMember<TPropertySymbol>, Cci.IPropertyDefinition { private readonly ImmutableArray<TEmbeddedParameter> _parameters; private readonly TEmbeddedMethod _getter; private readonly TEmbeddedMethod _setter; protected CommonEmbeddedProperty(TPropertySymbol underlyingProperty, TEmbeddedMethod getter, TEmbeddedMethod setter) : base(underlyingProperty) { Debug.Assert(getter != null || setter != null); _getter = getter; _setter = setter; _parameters = GetParameters(); } internal override TEmbeddedTypesManager TypeManager { get { return AnAccessor.TypeManager; } } protected abstract ImmutableArray<TEmbeddedParameter> GetParameters(); protected abstract bool IsRuntimeSpecial { get; } protected abstract bool IsSpecialName { get; } protected abstract Cci.ISignature UnderlyingPropertySignature { get; } protected abstract TEmbeddedType ContainingType { get; } protected abstract Cci.TypeMemberVisibility Visibility { get; } protected abstract string Name { get; } public TPropertySymbol UnderlyingProperty { get { return this.UnderlyingSymbol; } } Cci.IMethodReference Cci.IPropertyDefinition.Getter { get { return _getter; } } Cci.IMethodReference Cci.IPropertyDefinition.Setter { get { return _setter; } } IEnumerable<Cci.IMethodReference> Cci.IPropertyDefinition.GetAccessors(EmitContext context) { if (_getter != null) { yield return _getter; } if (_setter != null) { yield return _setter; } } bool Cci.IPropertyDefinition.HasDefaultValue { get { return false; } } MetadataConstant Cci.IPropertyDefinition.DefaultValue { get { return null; } } bool Cci.IPropertyDefinition.IsRuntimeSpecial { get { return IsRuntimeSpecial; } } bool Cci.IPropertyDefinition.IsSpecialName { get { return IsSpecialName; } } ImmutableArray<Cci.IParameterDefinition> Cci.IPropertyDefinition.Parameters { get { return StaticCast<Cci.IParameterDefinition>.From(_parameters); } } Cci.CallingConvention Cci.ISignature.CallingConvention { get { return UnderlyingPropertySignature.CallingConvention; } } ushort Cci.ISignature.ParameterCount { get { return (ushort)_parameters.Length; } } ImmutableArray<Cci.IParameterTypeInformation> Cci.ISignature.GetParameters(EmitContext context) { return StaticCast<Cci.IParameterTypeInformation>.From(_parameters); } ImmutableArray<Cci.ICustomModifier> Cci.ISignature.ReturnValueCustomModifiers { get { return UnderlyingPropertySignature.ReturnValueCustomModifiers; } } ImmutableArray<Cci.ICustomModifier> Cci.ISignature.RefCustomModifiers { get { return UnderlyingPropertySignature.RefCustomModifiers; } } bool Cci.ISignature.ReturnValueIsByRef { get { return UnderlyingPropertySignature.ReturnValueIsByRef; } } Cci.ITypeReference Cci.ISignature.GetType(EmitContext context) { return UnderlyingPropertySignature.GetType(context); } protected TEmbeddedMethod AnAccessor { get { return _getter ?? _setter; } } Cci.ITypeDefinition Cci.ITypeDefinitionMember.ContainingTypeDefinition { get { return ContainingType; } } Cci.TypeMemberVisibility Cci.ITypeDefinitionMember.Visibility { get { return Visibility; } } Cci.ITypeReference Cci.ITypeMemberReference.GetContainingType(EmitContext context) { return ContainingType; } void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor) { visitor.Visit((Cci.IPropertyDefinition)this); } Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context) { return this; } string Cci.INamedEntity.Name { get { return Name; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeGen; using Cci = Microsoft.Cci; namespace Microsoft.CodeAnalysis.Emit.NoPia { internal abstract partial class EmbeddedTypesManager< TPEModuleBuilder, TModuleCompilationState, TEmbeddedTypesManager, TSyntaxNode, TAttributeData, TSymbol, TAssemblySymbol, TNamedTypeSymbol, TFieldSymbol, TMethodSymbol, TEventSymbol, TPropertySymbol, TParameterSymbol, TTypeParameterSymbol, TEmbeddedType, TEmbeddedField, TEmbeddedMethod, TEmbeddedEvent, TEmbeddedProperty, TEmbeddedParameter, TEmbeddedTypeParameter> { internal abstract class CommonEmbeddedProperty : CommonEmbeddedMember<TPropertySymbol>, Cci.IPropertyDefinition { private readonly ImmutableArray<TEmbeddedParameter> _parameters; private readonly TEmbeddedMethod _getter; private readonly TEmbeddedMethod _setter; protected CommonEmbeddedProperty(TPropertySymbol underlyingProperty, TEmbeddedMethod getter, TEmbeddedMethod setter) : base(underlyingProperty) { Debug.Assert(getter != null || setter != null); _getter = getter; _setter = setter; _parameters = GetParameters(); } internal override TEmbeddedTypesManager TypeManager { get { return AnAccessor.TypeManager; } } protected abstract ImmutableArray<TEmbeddedParameter> GetParameters(); protected abstract bool IsRuntimeSpecial { get; } protected abstract bool IsSpecialName { get; } protected abstract Cci.ISignature UnderlyingPropertySignature { get; } protected abstract TEmbeddedType ContainingType { get; } protected abstract Cci.TypeMemberVisibility Visibility { get; } protected abstract string Name { get; } public TPropertySymbol UnderlyingProperty { get { return this.UnderlyingSymbol; } } Cci.IMethodReference Cci.IPropertyDefinition.Getter { get { return _getter; } } Cci.IMethodReference Cci.IPropertyDefinition.Setter { get { return _setter; } } IEnumerable<Cci.IMethodReference> Cci.IPropertyDefinition.GetAccessors(EmitContext context) { if (_getter != null) { yield return _getter; } if (_setter != null) { yield return _setter; } } bool Cci.IPropertyDefinition.HasDefaultValue { get { return false; } } MetadataConstant Cci.IPropertyDefinition.DefaultValue { get { return null; } } bool Cci.IPropertyDefinition.IsRuntimeSpecial { get { return IsRuntimeSpecial; } } bool Cci.IPropertyDefinition.IsSpecialName { get { return IsSpecialName; } } ImmutableArray<Cci.IParameterDefinition> Cci.IPropertyDefinition.Parameters { get { return StaticCast<Cci.IParameterDefinition>.From(_parameters); } } Cci.CallingConvention Cci.ISignature.CallingConvention { get { return UnderlyingPropertySignature.CallingConvention; } } ushort Cci.ISignature.ParameterCount { get { return (ushort)_parameters.Length; } } ImmutableArray<Cci.IParameterTypeInformation> Cci.ISignature.GetParameters(EmitContext context) { return StaticCast<Cci.IParameterTypeInformation>.From(_parameters); } ImmutableArray<Cci.ICustomModifier> Cci.ISignature.ReturnValueCustomModifiers { get { return UnderlyingPropertySignature.ReturnValueCustomModifiers; } } ImmutableArray<Cci.ICustomModifier> Cci.ISignature.RefCustomModifiers { get { return UnderlyingPropertySignature.RefCustomModifiers; } } bool Cci.ISignature.ReturnValueIsByRef { get { return UnderlyingPropertySignature.ReturnValueIsByRef; } } Cci.ITypeReference Cci.ISignature.GetType(EmitContext context) { return UnderlyingPropertySignature.GetType(context); } protected TEmbeddedMethod AnAccessor { get { return _getter ?? _setter; } } Cci.ITypeDefinition Cci.ITypeDefinitionMember.ContainingTypeDefinition { get { return ContainingType; } } Cci.TypeMemberVisibility Cci.ITypeDefinitionMember.Visibility { get { return Visibility; } } Cci.ITypeReference Cci.ITypeMemberReference.GetContainingType(EmitContext context) { return ContainingType; } void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor) { visitor.Visit((Cci.IPropertyDefinition)this); } Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context) { return this; } string Cci.INamedEntity.Name { get { return Name; } } } } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Scripting/Core/Hosting/InteractiveScriptGlobals.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.IO; namespace Microsoft.CodeAnalysis.Scripting.Hosting { /// <summary> /// Defines global members that common REPL (Read Eval Print Loop) hosts make available in /// the interactive session. /// </summary> /// <remarks> /// It is recommended for hosts to expose the members defined by this class and implement /// the same semantics, so that they can run scripts written against standard hosts. /// /// Specialized hosts that target niche scenarios might choose to not provide this functionality. /// </remarks> public class InteractiveScriptGlobals { private readonly TextWriter _outputWriter; private readonly ObjectFormatter _objectFormatter; /// <summary> /// Arguments given to the script. /// </summary> public IList<string> Args { get; } /// <summary> /// Pretty-prints an object. /// </summary> public void Print(object value) { _outputWriter.WriteLine(_objectFormatter.FormatObject(value, PrintOptions)); } public IList<string> ReferencePaths { get; } public IList<string> SourcePaths { get; } public PrintOptions PrintOptions { get; } public InteractiveScriptGlobals(TextWriter outputWriter, ObjectFormatter objectFormatter) { if (outputWriter == null) { throw new ArgumentNullException(nameof(outputWriter)); } if (objectFormatter == null) { throw new ArgumentNullException(nameof(objectFormatter)); } Debug.Assert(outputWriter != null); Debug.Assert(objectFormatter != null); ReferencePaths = new SearchPaths(); SourcePaths = new SearchPaths(); Args = new List<string>(); PrintOptions = new PrintOptions(); _outputWriter = outputWriter; _objectFormatter = objectFormatter; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.IO; namespace Microsoft.CodeAnalysis.Scripting.Hosting { /// <summary> /// Defines global members that common REPL (Read Eval Print Loop) hosts make available in /// the interactive session. /// </summary> /// <remarks> /// It is recommended for hosts to expose the members defined by this class and implement /// the same semantics, so that they can run scripts written against standard hosts. /// /// Specialized hosts that target niche scenarios might choose to not provide this functionality. /// </remarks> public class InteractiveScriptGlobals { private readonly TextWriter _outputWriter; private readonly ObjectFormatter _objectFormatter; /// <summary> /// Arguments given to the script. /// </summary> public IList<string> Args { get; } /// <summary> /// Pretty-prints an object. /// </summary> public void Print(object value) { _outputWriter.WriteLine(_objectFormatter.FormatObject(value, PrintOptions)); } public IList<string> ReferencePaths { get; } public IList<string> SourcePaths { get; } public PrintOptions PrintOptions { get; } public InteractiveScriptGlobals(TextWriter outputWriter, ObjectFormatter objectFormatter) { if (outputWriter == null) { throw new ArgumentNullException(nameof(outputWriter)); } if (objectFormatter == null) { throw new ArgumentNullException(nameof(objectFormatter)); } Debug.Assert(outputWriter != null); Debug.Assert(objectFormatter != null); ReferencePaths = new SearchPaths(); SourcePaths = new SearchPaths(); Args = new List<string>(); PrintOptions = new PrintOptions(); _outputWriter = outputWriter; _objectFormatter = objectFormatter; } } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Features/Lsif/Generator/Graph/Id.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph { /// <summary> /// Represents an ID of a vertex or edge. /// </summary> /// <typeparam name="T">Used to distinguish what type of object this ID applies to. This is dropped in serialization, but simply helps /// to ensure type safety in the code so we don't cross IDs of different types.</typeparam> internal struct Id<T> : IEquatable<Id<T>>, ISerializableId where T : Element { public Id(int id) { NumericId = id; } public int NumericId { get; } public override bool Equals(object? obj) { return obj is Id<T> other && Equals(other); } public bool Equals(Id<T> other) { return other.NumericId == NumericId; } public override int GetHashCode() { return NumericId.GetHashCode(); } public static bool operator ==(Id<T> left, Id<T> right) { return left.Equals(right); } public static bool operator !=(Id<T> left, Id<T> right) { return !(left == right); } public override string ToString() { return $"{NumericId}"; } } internal interface ISerializableId { public int NumericId { get; } } internal static class IdExtensions { /// <summary> /// "Casts" a strongly type ID representing a derived type to a base type. /// </summary> public static Id<TOut> As<TIn, TOut>(this Id<TIn> id) where TOut : Element where TIn : TOut { return new Id<TOut>(id.NumericId); } /// <summary> /// Fetches a strongly-typed <see cref="Id{T}"/> for a given element. /// </summary> public static Id<T> GetId<T>(this T element) where T : Element { return new Id<T>(element.Id.NumericId); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph { /// <summary> /// Represents an ID of a vertex or edge. /// </summary> /// <typeparam name="T">Used to distinguish what type of object this ID applies to. This is dropped in serialization, but simply helps /// to ensure type safety in the code so we don't cross IDs of different types.</typeparam> internal struct Id<T> : IEquatable<Id<T>>, ISerializableId where T : Element { public Id(int id) { NumericId = id; } public int NumericId { get; } public override bool Equals(object? obj) { return obj is Id<T> other && Equals(other); } public bool Equals(Id<T> other) { return other.NumericId == NumericId; } public override int GetHashCode() { return NumericId.GetHashCode(); } public static bool operator ==(Id<T> left, Id<T> right) { return left.Equals(right); } public static bool operator !=(Id<T> left, Id<T> right) { return !(left == right); } public override string ToString() { return $"{NumericId}"; } } internal interface ISerializableId { public int NumericId { get; } } internal static class IdExtensions { /// <summary> /// "Casts" a strongly type ID representing a derived type to a base type. /// </summary> public static Id<TOut> As<TIn, TOut>(this Id<TIn> id) where TOut : Element where TIn : TOut { return new Id<TOut>(id.NumericId); } /// <summary> /// Fetches a strongly-typed <see cref="Id{T}"/> for a given element. /// </summary> public static Id<T> GetId<T>(this T element) where T : Element { return new Id<T>(element.Id.NumericId); } } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Core/Portable/Symbols/Attributes/WellKnownAttributeData.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Base class for storing information decoded from well-known custom attributes. /// </summary> internal abstract class WellKnownAttributeData { #pragma warning disable CA1802 // Remove suppression once https://github.com/dotnet/roslyn/issues/20894 is fixed /// <summary> /// Used to distinguish cases when attribute is applied with null value and when attribute is not applied. /// For some well-known attributes, the latter case will return string stored in <see cref="StringMissingValue"/> /// field. /// </summary> public static readonly string StringMissingValue = nameof(StringMissingValue); #pragma warning restore CA1802 #if DEBUG private bool _isSealed; private bool _anyDataStored; #endif public WellKnownAttributeData() { #if DEBUG _isSealed = false; _anyDataStored = false; #endif } [Conditional("DEBUG")] protected void VerifySealed(bool expected = true) { #if DEBUG Debug.Assert(_isSealed == expected); #endif } [Conditional("DEBUG")] internal void VerifyDataStored(bool expected = true) { #if DEBUG Debug.Assert(_anyDataStored == expected); #endif } [Conditional("DEBUG")] protected void SetDataStored() { #if DEBUG _anyDataStored = true; #endif } [Conditional("DEBUG")] internal static void Seal(WellKnownAttributeData data) { #if DEBUG if (data != null) { Debug.Assert(!data._isSealed); Debug.Assert(data._anyDataStored); data._isSealed = true; } #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. #nullable disable using System; using System.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Base class for storing information decoded from well-known custom attributes. /// </summary> internal abstract class WellKnownAttributeData { #pragma warning disable CA1802 // Remove suppression once https://github.com/dotnet/roslyn/issues/20894 is fixed /// <summary> /// Used to distinguish cases when attribute is applied with null value and when attribute is not applied. /// For some well-known attributes, the latter case will return string stored in <see cref="StringMissingValue"/> /// field. /// </summary> public static readonly string StringMissingValue = nameof(StringMissingValue); #pragma warning restore CA1802 #if DEBUG private bool _isSealed; private bool _anyDataStored; #endif public WellKnownAttributeData() { #if DEBUG _isSealed = false; _anyDataStored = false; #endif } [Conditional("DEBUG")] protected void VerifySealed(bool expected = true) { #if DEBUG Debug.Assert(_isSealed == expected); #endif } [Conditional("DEBUG")] internal void VerifyDataStored(bool expected = true) { #if DEBUG Debug.Assert(_anyDataStored == expected); #endif } [Conditional("DEBUG")] protected void SetDataStored() { #if DEBUG _anyDataStored = true; #endif } [Conditional("DEBUG")] internal static void Seal(WellKnownAttributeData data) { #if DEBUG if (data != null) { Debug.Assert(!data._isSealed); Debug.Assert(data._anyDataStored); data._isSealed = true; } #endif } } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Test/Core/Compilation/FlowAnalysis/BasicBlockReachabilityDataFlowAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using System.Threading; namespace Microsoft.CodeAnalysis.FlowAnalysis { internal sealed class BasicBlockReachabilityDataFlowAnalyzer : DataFlowAnalyzer<bool> { private BitVector _visited = BitVector.Empty; private BasicBlockReachabilityDataFlowAnalyzer() { } public static BitVector Run(ControlFlowGraph controlFlowGraph) { var analyzer = new BasicBlockReachabilityDataFlowAnalyzer(); _ = CustomDataFlowAnalysis<bool>.Run(controlFlowGraph, analyzer, CancellationToken.None); return analyzer._visited; } // Do not analyze unreachable control flow branches and blocks. // This way all blocks that are called back to be analyzed in AnalyzeBlock are reachable // and the remaining blocks are unreachable. public override bool AnalyzeUnreachableBlocks => false; public override bool AnalyzeBlock(BasicBlock basicBlock, CancellationToken cancellationToken) { SetCurrentAnalysisData(basicBlock, isReachable: true, cancellationToken); return true; } public override bool AnalyzeNonConditionalBranch(BasicBlock basicBlock, bool currentIsReachable, CancellationToken cancellationToken) { // Feasibility of control flow branches is analyzed by the core CustomDataFlowAnalysis // walker. If it identifies a branch as infeasible, it never invokes // this callback. // Assert that we are on a reachable control flow path, and retain the current reachability. Debug.Assert(currentIsReachable); return currentIsReachable; } public override (bool fallThroughSuccessorData, bool conditionalSuccessorData) AnalyzeConditionalBranch( BasicBlock basicBlock, bool currentIsReachable, CancellationToken cancellationToken) { // Feasibility of control flow branches is analyzed by the core CustomDataFlowAnalysis // walker. If it identifies a branch as infeasible, it never invokes // this callback. // Assert that we are on a reachable control flow path, and retain the current reachability // for both the destination blocks. Debug.Assert(currentIsReachable); return (currentIsReachable, currentIsReachable); } public override void SetCurrentAnalysisData(BasicBlock basicBlock, bool isReachable, CancellationToken cancellationToken) { _visited[basicBlock.Ordinal] = isReachable; } public override bool GetCurrentAnalysisData(BasicBlock basicBlock) => _visited[basicBlock.Ordinal]; // A basic block is considered unreachable by default. public override bool GetEmptyAnalysisData() => false; // Destination block is reachable if either of the predecessor blocks are reachable. public override bool Merge(bool predecessor1IsReachable, bool predecessor2IsReachable, CancellationToken cancellationToken) => predecessor1IsReachable || predecessor2IsReachable; public override bool IsEqual(bool isReachable1, bool isReachable2) => isReachable1 == isReachable2; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using System.Threading; namespace Microsoft.CodeAnalysis.FlowAnalysis { internal sealed class BasicBlockReachabilityDataFlowAnalyzer : DataFlowAnalyzer<bool> { private BitVector _visited = BitVector.Empty; private BasicBlockReachabilityDataFlowAnalyzer() { } public static BitVector Run(ControlFlowGraph controlFlowGraph) { var analyzer = new BasicBlockReachabilityDataFlowAnalyzer(); _ = CustomDataFlowAnalysis<bool>.Run(controlFlowGraph, analyzer, CancellationToken.None); return analyzer._visited; } // Do not analyze unreachable control flow branches and blocks. // This way all blocks that are called back to be analyzed in AnalyzeBlock are reachable // and the remaining blocks are unreachable. public override bool AnalyzeUnreachableBlocks => false; public override bool AnalyzeBlock(BasicBlock basicBlock, CancellationToken cancellationToken) { SetCurrentAnalysisData(basicBlock, isReachable: true, cancellationToken); return true; } public override bool AnalyzeNonConditionalBranch(BasicBlock basicBlock, bool currentIsReachable, CancellationToken cancellationToken) { // Feasibility of control flow branches is analyzed by the core CustomDataFlowAnalysis // walker. If it identifies a branch as infeasible, it never invokes // this callback. // Assert that we are on a reachable control flow path, and retain the current reachability. Debug.Assert(currentIsReachable); return currentIsReachable; } public override (bool fallThroughSuccessorData, bool conditionalSuccessorData) AnalyzeConditionalBranch( BasicBlock basicBlock, bool currentIsReachable, CancellationToken cancellationToken) { // Feasibility of control flow branches is analyzed by the core CustomDataFlowAnalysis // walker. If it identifies a branch as infeasible, it never invokes // this callback. // Assert that we are on a reachable control flow path, and retain the current reachability // for both the destination blocks. Debug.Assert(currentIsReachable); return (currentIsReachable, currentIsReachable); } public override void SetCurrentAnalysisData(BasicBlock basicBlock, bool isReachable, CancellationToken cancellationToken) { _visited[basicBlock.Ordinal] = isReachable; } public override bool GetCurrentAnalysisData(BasicBlock basicBlock) => _visited[basicBlock.Ordinal]; // A basic block is considered unreachable by default. public override bool GetEmptyAnalysisData() => false; // Destination block is reachable if either of the predecessor blocks are reachable. public override bool Merge(bool predecessor1IsReachable, bool predecessor2IsReachable, CancellationToken cancellationToken) => predecessor1IsReachable || predecessor2IsReachable; public override bool IsEqual(bool isReachable1, bool isReachable2) => isReachable1 == isReachable2; } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Dependencies/CodeAnalysis.Debugging/CustomDebugInfoKind.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Debugging { /// <summary> /// The kinds of custom debug info that we know how to interpret. /// The values correspond to possible values of the "kind" byte /// in the record header. /// </summary> internal enum CustomDebugInfoKind : byte { /// <summary> /// C# only. Encodes the sizes of using groups that are applicable to the method. /// The actual import strings are stored separately trhu ISymUnmanagedWriter.UsingNamespace. /// </summary> UsingGroups = 0, /// <summary> /// C# only. Indicates that per-method debug information (import strings) is stored on another method, /// whose token is specified. /// </summary> ForwardMethodInfo = 1, /// <summary> /// C# only. Indicates that per-module debug information (assembly reference aliases) is stored on another method, /// whose token is specified. /// </summary> ForwardModuleInfo = 2, /// <summary> /// C# only. Specifies local scopes for state machine hoisted local variables. /// </summary> StateMachineHoistedLocalScopes = 3, /// <summary> /// C# and VB. The name of the state machine type. Emitted for async and iterator kick-off methods. /// </summary> StateMachineTypeName = 4, /// <summary> /// C# only. Dynamic flags for local variables and constants. /// </summary> DynamicLocals = 5, /// <summary> /// C# and VB. Encodes EnC local variable slot map. /// See https://github.com/dotnet/corefx/blob/main/src/System.Reflection.Metadata/specs/PortablePdb-Metadata.md#EditAndContinueLocalSlotMap. /// </summary> EditAndContinueLocalSlotMap = 6, /// <summary> /// C# and VB. Encodes EnC lambda map. /// See https://github.com/dotnet/corefx/blob/main/src/System.Reflection.Metadata/specs/PortablePdb-Metadata.md#EditAndContinueLambdaAndClosureMap. /// </summary> EditAndContinueLambdaMap = 7, /// <summary> /// C# and VB. Tuple element names for local variables and constants. /// </summary> TupleElementNames = 8, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.Debugging { /// <summary> /// The kinds of custom debug info that we know how to interpret. /// The values correspond to possible values of the "kind" byte /// in the record header. /// </summary> internal enum CustomDebugInfoKind : byte { /// <summary> /// C# only. Encodes the sizes of using groups that are applicable to the method. /// The actual import strings are stored separately trhu ISymUnmanagedWriter.UsingNamespace. /// </summary> UsingGroups = 0, /// <summary> /// C# only. Indicates that per-method debug information (import strings) is stored on another method, /// whose token is specified. /// </summary> ForwardMethodInfo = 1, /// <summary> /// C# only. Indicates that per-module debug information (assembly reference aliases) is stored on another method, /// whose token is specified. /// </summary> ForwardModuleInfo = 2, /// <summary> /// C# only. Specifies local scopes for state machine hoisted local variables. /// </summary> StateMachineHoistedLocalScopes = 3, /// <summary> /// C# and VB. The name of the state machine type. Emitted for async and iterator kick-off methods. /// </summary> StateMachineTypeName = 4, /// <summary> /// C# only. Dynamic flags for local variables and constants. /// </summary> DynamicLocals = 5, /// <summary> /// C# and VB. Encodes EnC local variable slot map. /// See https://github.com/dotnet/corefx/blob/main/src/System.Reflection.Metadata/specs/PortablePdb-Metadata.md#EditAndContinueLocalSlotMap. /// </summary> EditAndContinueLocalSlotMap = 6, /// <summary> /// C# and VB. Encodes EnC lambda map. /// See https://github.com/dotnet/corefx/blob/main/src/System.Reflection.Metadata/specs/PortablePdb-Metadata.md#EditAndContinueLambdaAndClosureMap. /// </summary> EditAndContinueLambdaMap = 7, /// <summary> /// C# and VB. Tuple element names for local variables and constants. /// </summary> TupleElementNames = 8, } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Features/Core/Portable/Completion/INotifyCommittingItemCompletionProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// Interface to implement if the provider want to sign up for notifacation when one of the items it provided /// is being committed by the host, since calling <see cref="CompletionProvider.GetChangeAsync"/> doesn't necessarily /// lead to commission. /// </summary> internal interface INotifyCommittingItemCompletionProvider { /// <summary> /// This is invoked when one of the items provided by this provider is being committed. /// </summary> /// <remarks> /// Host provides no guarantee when will this be called (i.e. pre or post document change), nor the text /// change will actually happen at all (e.g. the commit operation might be cancelled due to cancellation/exception/etc.) /// </remarks> Task NotifyCommittingItemAsync(Document document, CompletionItem item, char? commitKey, 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.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// Interface to implement if the provider want to sign up for notifacation when one of the items it provided /// is being committed by the host, since calling <see cref="CompletionProvider.GetChangeAsync"/> doesn't necessarily /// lead to commission. /// </summary> internal interface INotifyCommittingItemCompletionProvider { /// <summary> /// This is invoked when one of the items provided by this provider is being committed. /// </summary> /// <remarks> /// Host provides no guarantee when will this be called (i.e. pre or post document change), nor the text /// change will actually happen at all (e.g. the commit operation might be cancelled due to cancellation/exception/etc.) /// </remarks> Task NotifyCommittingItemAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/IReferenceCountedDisposable.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Roslyn.Utilities { /// <summary> /// A covariant interface form of <see cref="ReferenceCountedDisposable{T}"/> that lets you re-cast an <see cref="ReferenceCountedDisposable{T}"/> /// to a more base type. This can include types that do not implement <see cref="IDisposable"/> if you want to prevent a caller from accidentally /// disposing <see cref="Target"/> directly. /// </summary> /// <typeparam name="T"></typeparam> internal interface IReferenceCountedDisposable<out T> : IDisposable #if !CODE_STYLE , IAsyncDisposable #endif where T : class { /// <summary> /// Gets the target object. /// </summary> /// <remarks> /// <para>This call is not valid after <see cref="IDisposable.Dispose"/> is called. If this property or the target /// object is used concurrently with a call to <see cref="IDisposable.Dispose"/>, it is possible for the code to be /// using a disposed object. After the current instance is disposed, this property throws /// <see cref="ObjectDisposedException"/>. However, the exact time when this property starts throwing after /// <see cref="IDisposable.Dispose"/> is called is unspecified; code is expected to not use this property or the object /// it returns after any code invokes <see cref="IDisposable.Dispose"/>.</para> /// </remarks> /// <value>The target object.</value> T Target { get; } /// <summary> /// Increments the reference count for the disposable object, and returns a new disposable reference to it. /// </summary> /// <remarks> /// <para>The returned object is an independent reference to the same underlying object. Disposing of the /// returned value multiple times will only cause the reference count to be decreased once.</para> /// </remarks> /// <returns>A new <see cref="ReferenceCountedDisposable{T}"/> pointing to the same underlying object, if it /// has not yet been disposed; otherwise, <see langword="null"/> if this reference to the underlying object /// has already been disposed.</returns> IReferenceCountedDisposable<T>? TryAddReference(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Roslyn.Utilities { /// <summary> /// A covariant interface form of <see cref="ReferenceCountedDisposable{T}"/> that lets you re-cast an <see cref="ReferenceCountedDisposable{T}"/> /// to a more base type. This can include types that do not implement <see cref="IDisposable"/> if you want to prevent a caller from accidentally /// disposing <see cref="Target"/> directly. /// </summary> /// <typeparam name="T"></typeparam> internal interface IReferenceCountedDisposable<out T> : IDisposable #if !CODE_STYLE , IAsyncDisposable #endif where T : class { /// <summary> /// Gets the target object. /// </summary> /// <remarks> /// <para>This call is not valid after <see cref="IDisposable.Dispose"/> is called. If this property or the target /// object is used concurrently with a call to <see cref="IDisposable.Dispose"/>, it is possible for the code to be /// using a disposed object. After the current instance is disposed, this property throws /// <see cref="ObjectDisposedException"/>. However, the exact time when this property starts throwing after /// <see cref="IDisposable.Dispose"/> is called is unspecified; code is expected to not use this property or the object /// it returns after any code invokes <see cref="IDisposable.Dispose"/>.</para> /// </remarks> /// <value>The target object.</value> T Target { get; } /// <summary> /// Increments the reference count for the disposable object, and returns a new disposable reference to it. /// </summary> /// <remarks> /// <para>The returned object is an independent reference to the same underlying object. Disposing of the /// returned value multiple times will only cause the reference count to be decreased once.</para> /// </remarks> /// <returns>A new <see cref="ReferenceCountedDisposable{T}"/> pointing to the same underlying object, if it /// has not yet been disposed; otherwise, <see langword="null"/> if this reference to the underlying object /// has already been disposed.</returns> IReferenceCountedDisposable<T>? TryAddReference(); } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Features/Core/Portable/CodeFixes/FixAllOccurrences/IFixMultipleOccurrencesService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.CodeFixes { internal interface IFixMultipleOccurrencesService : IWorkspaceService { /// <summary> /// Get the fix multiple occurrences code fix for the given diagnostics with source locations. /// NOTE: This method does not apply the fix to the workspace. /// </summary> Solution GetFix( ImmutableDictionary<Document, ImmutableArray<Diagnostic>> diagnosticsToFix, Workspace workspace, CodeFixProvider fixProvider, FixAllProvider fixAllProvider, string equivalenceKey, string waitDialogTitle, string waitDialogMessage, CancellationToken cancellationToken); /// <summary> /// Get the fix multiple occurrences code fix for the given diagnostics with source locations. /// NOTE: This method does not apply the fix to the workspace. /// </summary> Solution GetFix( ImmutableDictionary<Project, ImmutableArray<Diagnostic>> diagnosticsToFix, Workspace workspace, CodeFixProvider fixProvider, FixAllProvider fixAllProvider, string equivalenceKey, string waitDialogTitle, string waitDialogMessage, 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 Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.CodeFixes { internal interface IFixMultipleOccurrencesService : IWorkspaceService { /// <summary> /// Get the fix multiple occurrences code fix for the given diagnostics with source locations. /// NOTE: This method does not apply the fix to the workspace. /// </summary> Solution GetFix( ImmutableDictionary<Document, ImmutableArray<Diagnostic>> diagnosticsToFix, Workspace workspace, CodeFixProvider fixProvider, FixAllProvider fixAllProvider, string equivalenceKey, string waitDialogTitle, string waitDialogMessage, CancellationToken cancellationToken); /// <summary> /// Get the fix multiple occurrences code fix for the given diagnostics with source locations. /// NOTE: This method does not apply the fix to the workspace. /// </summary> Solution GetFix( ImmutableDictionary<Project, ImmutableArray<Diagnostic>> diagnosticsToFix, Workspace workspace, CodeFixProvider fixProvider, FixAllProvider fixAllProvider, string equivalenceKey, string waitDialogTitle, string waitDialogMessage, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/CSharp/Test/Interactive/Commands/InteractiveWindowCommandHandlerTestState.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Xml.Linq; using Microsoft.CodeAnalysis.Editor.Interactive; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.InteractiveWindow; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Interactive.Commands { /// <summary> /// This class creates a mock execution state that allows to send CopyToInteractive and ExeciteInInteractive. /// Commands against a mock InteractiveWindow. /// </summary> internal class InteractiveWindowCommandHandlerTestState : AbstractCommandHandlerTestState { public InteractiveWindowTestHost TestHost { get; } private readonly InteractiveCommandHandler _commandHandler; public ITextView WindowTextView => TestHost.Window.TextView; public ITextBuffer WindowCurrentLanguageBuffer => TestHost.Window.CurrentLanguageBuffer; public ITextSnapshot WindowSnapshot => WindowCurrentLanguageBuffer.CurrentSnapshot; public TestInteractiveEvaluator Evaluator => TestHost.Evaluator; private ICommandHandler<ExecuteInInteractiveCommandArgs> ExecuteInInteractiveCommandHandler => _commandHandler; private ICommandHandler<CopyToInteractiveCommandArgs> CopyToInteractiveCommandHandler => _commandHandler; public InteractiveWindowCommandHandlerTestState(XElement workspaceElement) : base(workspaceElement, EditorTestCompositions.InteractiveWindow, workspaceKind: null) { TestHost = new InteractiveWindowTestHost(GetExportedValue<IInteractiveWindowFactoryService>()); _commandHandler = new TestInteractiveCommandHandler( TestHost.Window, GetExportedValue<ISendToInteractiveSubmissionProvider>(), GetExportedValue<IContentTypeRegistryService>(), GetExportedValue<IEditorOptionsFactoryService>(), GetExportedValue<IEditorOperationsFactoryService>()); } public static InteractiveWindowCommandHandlerTestState CreateTestState(string markup) { var workspaceXml = XElement.Parse($@" <Workspace> <Project Language=""C#"" CommonReferences=""true""> <Document>{markup}</Document> </Project> </Workspace> "); return new InteractiveWindowCommandHandlerTestState(workspaceXml); } public void SendCopyToInteractive() { var copyToInteractiveArgs = new CopyToInteractiveCommandArgs(TextView, SubjectBuffer); CopyToInteractiveCommandHandler.ExecuteCommand(copyToInteractiveArgs, TestCommandExecutionContext.Create()); } public void ExecuteInInteractive() { var executeInInteractiveArgs = new ExecuteInInteractiveCommandArgs(TextView, SubjectBuffer); ExecuteInInteractiveCommandHandler.ExecuteCommand(executeInInteractiveArgs, TestCommandExecutionContext.Create()); } public CommandState GetStateForExecuteInInteractive() { var executeInInteractiveArgs = new ExecuteInInteractiveCommandArgs(TextView, SubjectBuffer); return ExecuteInInteractiveCommandHandler.GetCommandState(executeInInteractiveArgs); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Xml.Linq; using Microsoft.CodeAnalysis.Editor.Interactive; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.InteractiveWindow; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Interactive.Commands { /// <summary> /// This class creates a mock execution state that allows to send CopyToInteractive and ExeciteInInteractive. /// Commands against a mock InteractiveWindow. /// </summary> internal class InteractiveWindowCommandHandlerTestState : AbstractCommandHandlerTestState { public InteractiveWindowTestHost TestHost { get; } private readonly InteractiveCommandHandler _commandHandler; public ITextView WindowTextView => TestHost.Window.TextView; public ITextBuffer WindowCurrentLanguageBuffer => TestHost.Window.CurrentLanguageBuffer; public ITextSnapshot WindowSnapshot => WindowCurrentLanguageBuffer.CurrentSnapshot; public TestInteractiveEvaluator Evaluator => TestHost.Evaluator; private ICommandHandler<ExecuteInInteractiveCommandArgs> ExecuteInInteractiveCommandHandler => _commandHandler; private ICommandHandler<CopyToInteractiveCommandArgs> CopyToInteractiveCommandHandler => _commandHandler; public InteractiveWindowCommandHandlerTestState(XElement workspaceElement) : base(workspaceElement, EditorTestCompositions.InteractiveWindow, workspaceKind: null) { TestHost = new InteractiveWindowTestHost(GetExportedValue<IInteractiveWindowFactoryService>()); _commandHandler = new TestInteractiveCommandHandler( TestHost.Window, GetExportedValue<ISendToInteractiveSubmissionProvider>(), GetExportedValue<IContentTypeRegistryService>(), GetExportedValue<IEditorOptionsFactoryService>(), GetExportedValue<IEditorOperationsFactoryService>()); } public static InteractiveWindowCommandHandlerTestState CreateTestState(string markup) { var workspaceXml = XElement.Parse($@" <Workspace> <Project Language=""C#"" CommonReferences=""true""> <Document>{markup}</Document> </Project> </Workspace> "); return new InteractiveWindowCommandHandlerTestState(workspaceXml); } public void SendCopyToInteractive() { var copyToInteractiveArgs = new CopyToInteractiveCommandArgs(TextView, SubjectBuffer); CopyToInteractiveCommandHandler.ExecuteCommand(copyToInteractiveArgs, TestCommandExecutionContext.Create()); } public void ExecuteInInteractive() { var executeInInteractiveArgs = new ExecuteInInteractiveCommandArgs(TextView, SubjectBuffer); ExecuteInInteractiveCommandHandler.ExecuteCommand(executeInInteractiveArgs, TestCommandExecutionContext.Create()); } public CommandState GetStateForExecuteInInteractive() { var executeInInteractiveArgs = new ExecuteInInteractiveCommandArgs(TextView, SubjectBuffer); return ExecuteInInteractiveCommandHandler.GetCommandState(executeInInteractiveArgs); } } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenTypeofTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CodeGenTypeOfTests : CSharpTestBase { [Fact] public void TestTypeofSimple() { var source = @" class C { static void Main() { System.Console.WriteLine(typeof(C)); } }"; var comp = CompileAndVerify(source, expectedOutput: "C"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 16 (0x10) .maxstack 1 IL_0000: ldtoken ""C"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: ret }"); } [Fact] public void TestTypeofNonGeneric() { var source = @" namespace Source { class Class { } struct Struct { } enum Enum { e } interface Interface { } class StaticClass { } } class Program { static void Main() { // From source System.Console.WriteLine(typeof(Source.Class)); System.Console.WriteLine(typeof(Source.Struct)); System.Console.WriteLine(typeof(Source.Enum)); System.Console.WriteLine(typeof(Source.Interface)); System.Console.WriteLine(typeof(Source.StaticClass)); // From metadata System.Console.WriteLine(typeof(string)); System.Console.WriteLine(typeof(int)); System.Console.WriteLine(typeof(System.IO.FileMode)); System.Console.WriteLine(typeof(System.IFormattable)); System.Console.WriteLine(typeof(System.Math)); // Special System.Console.WriteLine(typeof(void)); } }"; var comp = CompileAndVerify(source, expectedOutput: @" Source.Class Source.Struct Source.Enum Source.Interface Source.StaticClass System.String System.Int32 System.IO.FileMode System.IFormattable System.Math System.Void"); comp.VerifyDiagnostics(); comp.VerifyIL("Program.Main", @"{ // Code size 166 (0xa6) .maxstack 1 IL_0000: ldtoken ""Source.Class"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: ldtoken ""Source.Struct"" IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0019: call ""void System.Console.WriteLine(object)"" IL_001e: ldtoken ""Source.Enum"" IL_0023: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0028: call ""void System.Console.WriteLine(object)"" IL_002d: ldtoken ""Source.Interface"" IL_0032: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0037: call ""void System.Console.WriteLine(object)"" IL_003c: ldtoken ""Source.StaticClass"" IL_0041: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0046: call ""void System.Console.WriteLine(object)"" IL_004b: ldtoken ""string"" IL_0050: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0055: call ""void System.Console.WriteLine(object)"" IL_005a: ldtoken ""int"" IL_005f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0064: call ""void System.Console.WriteLine(object)"" IL_0069: ldtoken ""System.IO.FileMode"" IL_006e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0073: call ""void System.Console.WriteLine(object)"" IL_0078: ldtoken ""System.IFormattable"" IL_007d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0082: call ""void System.Console.WriteLine(object)"" IL_0087: ldtoken ""System.Math"" IL_008c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0091: call ""void System.Console.WriteLine(object)"" IL_0096: ldtoken ""void"" IL_009b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00a0: call ""void System.Console.WriteLine(object)"" IL_00a5: ret }"); } [Fact] public void TestTypeofGeneric() { var source = @" class Class1<T> { } class Class2<T, U> { } class Program { static void Main() { System.Console.WriteLine(typeof(Class1<int>)); System.Console.WriteLine(typeof(Class1<Class1<int>>)); System.Console.WriteLine(typeof(Class2<int, long>)); System.Console.WriteLine(typeof(Class2<Class1<int>, Class1<long>>)); } }"; var comp = CompileAndVerify(source, expectedOutput: @" Class1`1[System.Int32] Class1`1[Class1`1[System.Int32]] Class2`2[System.Int32,System.Int64] Class2`2[Class1`1[System.Int32],Class1`1[System.Int64]]"); comp.VerifyDiagnostics(); comp.VerifyIL("Program.Main", @"{ // Code size 61 (0x3d) .maxstack 1 IL_0000: ldtoken ""Class1<int>"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: ldtoken ""Class1<Class1<int>>"" IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0019: call ""void System.Console.WriteLine(object)"" IL_001e: ldtoken ""Class2<int, long>"" IL_0023: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0028: call ""void System.Console.WriteLine(object)"" IL_002d: ldtoken ""Class2<Class1<int>, Class1<long>>"" IL_0032: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0037: call ""void System.Console.WriteLine(object)"" IL_003c: ret }"); } [Fact] public void TestTypeofTypeParameter() { var source = @" class Class<T> { public static void Print() { System.Console.WriteLine(typeof(T)); System.Console.WriteLine(typeof(Class<T>)); } public static void Print<U>() { System.Console.WriteLine(typeof(U)); System.Console.WriteLine(typeof(Class<U>)); } } class Program { static void Main() { Class<int>.Print(); Class<Class<int>>.Print(); Class<int>.Print<long>(); Class<Class<int>>.Print<Class<long>>(); } }"; var comp = CompileAndVerify(source, expectedOutput: @" System.Int32 Class`1[System.Int32] Class`1[System.Int32] Class`1[Class`1[System.Int32]] System.Int64 Class`1[System.Int64] Class`1[System.Int64] Class`1[Class`1[System.Int64]]"); comp.VerifyDiagnostics(); comp.VerifyIL("Class<T>.Print", @"{ // Code size 31 (0x1f) .maxstack 1 IL_0000: ldtoken ""T"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: ldtoken ""Class<T>"" IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0019: call ""void System.Console.WriteLine(object)"" IL_001e: ret }"); comp.VerifyIL("Class<T>.Print<U>", @"{ // Code size 31 (0x1f) .maxstack 1 IL_0000: ldtoken ""U"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: ldtoken ""Class<U>"" IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0019: call ""void System.Console.WriteLine(object)"" IL_001e: ret }"); } [Fact] public void TestTypeofUnboundGeneric() { var source = @" class Class1<T> { } class Class2<T, U> { } class Program { static void Main() { System.Console.WriteLine(typeof(Class1<>)); System.Console.WriteLine(typeof(Class2<,>)); } }"; var comp = CompileAndVerify(source, expectedOutput: @" Class1`1[T] Class2`2[T,U]"); comp.VerifyDiagnostics(); comp.VerifyIL("Program.Main", @"{ // Code size 31 (0x1f) .maxstack 1 IL_0000: ldtoken ""Class1<T>"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: ldtoken ""Class2<T, U>"" IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0019: call ""void System.Console.WriteLine(object)"" IL_001e: ret }"); } [WorkItem(542581, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542581")] [Fact] public void TestTypeofInheritedNestedTypeThroughUnboundGeneric_01() { var source = @" using System; class D<T> : C, I1, I2<T, int> { } interface I1 { } interface I2<T, U> { } class F<T> { public class E {} } class G<T> : F<T>, I1, I2<T, int> { } class H<T, U> { public class E {} } class K<T> : H<T, int>{ } class C { public class E { } static void Main() { Console.WriteLine(typeof(D<>.E)); Console.WriteLine(typeof(D<>).BaseType); var interfaces = typeof(D<>).GetInterfaces(); Console.WriteLine(interfaces[0]); Console.WriteLine(interfaces[1]); Console.WriteLine(typeof(G<>.E)); Console.WriteLine(typeof(G<>).BaseType); interfaces = typeof(G<>).GetInterfaces(); Console.WriteLine(interfaces[0]); Console.WriteLine(interfaces[1]); Console.WriteLine(typeof(K<>.E)); Console.WriteLine(typeof(K<>).BaseType); } }"; var expected = @"C+E C I1 I2`2[T,System.Int32] F`1+E[T] F`1[T] I1 I2`2[T,System.Int32] H`2+E[T,U] H`2[T,System.Int32]"; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [WorkItem(542581, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542581")] [WorkItem(9850, "https://github.com/dotnet/roslyn/issues/9850")] [Fact] public void TestTypeofInheritedNestedTypeThroughUnboundGeneric_02() { var source = @" using System; class C { public class E { } public class E<V> { } static void Main() { var t1 = typeof(D<>.E); Console.WriteLine(t1); var t2 = typeof(F<>.E); var t3 = typeof(G<>.E); Console.WriteLine(t2); Console.WriteLine(t3); Console.WriteLine(t2.Equals(t3)); var t4 = typeof(D<>.E<>); Console.WriteLine(t4); var t5 = typeof(F<>.E<>); var t6 = typeof(G<>.E<>); Console.WriteLine(t5); Console.WriteLine(t6); Console.WriteLine(t5.Equals(t6)); } } class C<U> { public class E { } public class E<V> { } } class D<T> : C { } class F<T> : C<T> { } class G<T> : C<int> { } "; var expected = @"C+E C`1+E[U] C`1+E[U] True C+E`1[V] C`1+E`1[U,V] C`1+E`1[U,V] True"; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [WorkItem(542581, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542581")] [Fact] public void TestTypeofInheritedNestedTypeThroughUnboundGeneric_Attribute() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class TestAttribute : Attribute { public TestAttribute(System.Type type){} } class D<T> : C, I1, I2<T, int> { } interface I1 { } interface I2<T, U> { } class F<T> { public class E {} } class G<T> : F<T>, I1, I2<T, int> { } class H<T, U> { public class E {} } class K<T> : H<T, int>{ } [TestAttribute(typeof(D<>))] [TestAttribute(typeof(D<>.E))] [TestAttribute(typeof(G<>))] [TestAttribute(typeof(G<>.E))] [TestAttribute(typeof(K<>))] [TestAttribute(typeof(K<>.E))] class C { public class E { } static void Main() { typeof(C).GetCustomAttributes(false); } }"; var comp = CompileAndVerify(source, expectedOutput: ""); } [Fact] public void TestTypeofArray() { var source = @" class Class1<T> { } class Program { static void Print<U>() { System.Console.WriteLine(typeof(int[])); System.Console.WriteLine(typeof(int[,])); System.Console.WriteLine(typeof(int[][])); System.Console.WriteLine(typeof(U[])); System.Console.WriteLine(typeof(Class1<U>[])); System.Console.WriteLine(typeof(Class1<int>[])); } static void Main() { Print<long>(); } }"; var comp = CompileAndVerify(source, expectedOutput: @" System.Int32[] System.Int32[,] System.Int32[][] System.Int64[] Class1`1[System.Int64][] Class1`1[System.Int32][]"); comp.VerifyDiagnostics(); comp.VerifyIL("Program.Print<U>", @"{ // Code size 91 (0x5b) .maxstack 1 IL_0000: ldtoken ""int[]"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: ldtoken ""int[,]"" IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0019: call ""void System.Console.WriteLine(object)"" IL_001e: ldtoken ""int[][]"" IL_0023: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0028: call ""void System.Console.WriteLine(object)"" IL_002d: ldtoken ""U[]"" IL_0032: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0037: call ""void System.Console.WriteLine(object)"" IL_003c: ldtoken ""Class1<U>[]"" IL_0041: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0046: call ""void System.Console.WriteLine(object)"" IL_004b: ldtoken ""Class1<int>[]"" IL_0050: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0055: call ""void System.Console.WriteLine(object)"" IL_005a: ret }"); } [Fact] public void TestTypeofNested() { var source = @" class Outer<T> { public static void Print() { System.Console.WriteLine(typeof(Inner<>)); System.Console.WriteLine(typeof(Inner<T>)); System.Console.WriteLine(typeof(Inner<int>)); System.Console.WriteLine(typeof(Outer<>.Inner<>)); // System.Console.WriteLine(typeof(Outer<>.Inner<T>)); //CS7003 // System.Console.WriteLine(typeof(Outer<>.Inner<int>)); //CS7003 // System.Console.WriteLine(typeof(Outer<T>.Inner<>)); //CS7003 System.Console.WriteLine(typeof(Outer<T>.Inner<T>)); System.Console.WriteLine(typeof(Outer<T>.Inner<int>)); // System.Console.WriteLine(typeof(Outer<int>.Inner<>)); //CS7003 System.Console.WriteLine(typeof(Outer<int>.Inner<T>)); System.Console.WriteLine(typeof(Outer<int>.Inner<int>)); } class Inner<U> { } } class Program { static void Main() { Outer<long>.Print(); } }"; var comp = CompileAndVerify(source, expectedOutput: @" Outer`1+Inner`1[T,U] Outer`1+Inner`1[System.Int64,System.Int64] Outer`1+Inner`1[System.Int64,System.Int32] Outer`1+Inner`1[T,U] Outer`1+Inner`1[System.Int64,System.Int64] Outer`1+Inner`1[System.Int64,System.Int32] Outer`1+Inner`1[System.Int32,System.Int64] Outer`1+Inner`1[System.Int32,System.Int32]"); comp.VerifyDiagnostics(); comp.VerifyIL("Outer<T>.Print", @"{ // Code size 121 (0x79) .maxstack 1 IL_0000: ldtoken ""Outer<T>.Inner<U>"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: ldtoken ""Outer<T>.Inner<T>"" IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0019: call ""void System.Console.WriteLine(object)"" IL_001e: ldtoken ""Outer<T>.Inner<int>"" IL_0023: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0028: call ""void System.Console.WriteLine(object)"" IL_002d: ldtoken ""Outer<T>.Inner<U>"" IL_0032: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0037: call ""void System.Console.WriteLine(object)"" IL_003c: ldtoken ""Outer<T>.Inner<T>"" IL_0041: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0046: call ""void System.Console.WriteLine(object)"" IL_004b: ldtoken ""Outer<T>.Inner<int>"" IL_0050: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0055: call ""void System.Console.WriteLine(object)"" IL_005a: ldtoken ""Outer<int>.Inner<T>"" IL_005f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0064: call ""void System.Console.WriteLine(object)"" IL_0069: ldtoken ""Outer<int>.Inner<int>"" IL_006e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0073: call ""void System.Console.WriteLine(object)"" IL_0078: ret }"); } [Fact] public void TestTypeofInLambda() { var source = @" using System; public class Outer<T> { public class Inner<U> { public Action Method<V>(V v) { return () => { Console.WriteLine(v); Console.WriteLine(typeof(T)); Console.WriteLine(typeof(U)); Console.WriteLine(typeof(V)); Console.WriteLine(typeof(Outer<>)); Console.WriteLine(typeof(Outer<T>)); Console.WriteLine(typeof(Outer<U>)); Console.WriteLine(typeof(Outer<V>)); Console.WriteLine(typeof(Inner<>)); Console.WriteLine(typeof(Inner<T>)); Console.WriteLine(typeof(Inner<U>)); Console.WriteLine(typeof(Inner<V>)); }; } } } class Program { static void Main() { Action a = new Outer<int>.Inner<char>().Method<byte>(1); a(); } }"; var comp = CompileAndVerify(source, expectedOutput: @" 1 System.Int32 System.Char System.Byte Outer`1[T] Outer`1[System.Int32] Outer`1[System.Char] Outer`1[System.Byte] Outer`1+Inner`1[T,U] Outer`1+Inner`1[System.Int32,System.Int32] Outer`1+Inner`1[System.Int32,System.Char] Outer`1+Inner`1[System.Int32,System.Byte]"); comp.VerifyDiagnostics(); } [WorkItem(541600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541600")] [Fact] public void TestTypeOfAlias4TypeMemberOfGeneric() { var source = @" using System; using MyTestClass = TestClass<string>; public class TestClass<T> { public enum TestEnum { First = 0, } } public class mem178 { public static int Main() { Console.Write(typeof(MyTestClass.TestEnum)); return 0; } } "; CompileAndVerify(source, expectedOutput: @"TestClass`1+TestEnum[System.String]"); } [WorkItem(541618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541618")] [Fact] public void TestTypeOfAlias5TypeMemberOfGeneric() { var source = @" using OuterOfString = Outer<string>; using OuterOfInt = Outer<int>; public class Outer<T> { public class Inner<U> { } } public class Program { public static void Main() { System.Console.WriteLine(typeof(OuterOfString.Inner<>) == typeof(OuterOfInt.Inner<>)); } } "; // NOTE: this is the Dev10 output. Change to false if we decide to take a breaking change. CompileAndVerify(source, expectedOutput: @"True"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CodeGenTypeOfTests : CSharpTestBase { [Fact] public void TestTypeofSimple() { var source = @" class C { static void Main() { System.Console.WriteLine(typeof(C)); } }"; var comp = CompileAndVerify(source, expectedOutput: "C"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 16 (0x10) .maxstack 1 IL_0000: ldtoken ""C"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: ret }"); } [Fact] public void TestTypeofNonGeneric() { var source = @" namespace Source { class Class { } struct Struct { } enum Enum { e } interface Interface { } class StaticClass { } } class Program { static void Main() { // From source System.Console.WriteLine(typeof(Source.Class)); System.Console.WriteLine(typeof(Source.Struct)); System.Console.WriteLine(typeof(Source.Enum)); System.Console.WriteLine(typeof(Source.Interface)); System.Console.WriteLine(typeof(Source.StaticClass)); // From metadata System.Console.WriteLine(typeof(string)); System.Console.WriteLine(typeof(int)); System.Console.WriteLine(typeof(System.IO.FileMode)); System.Console.WriteLine(typeof(System.IFormattable)); System.Console.WriteLine(typeof(System.Math)); // Special System.Console.WriteLine(typeof(void)); } }"; var comp = CompileAndVerify(source, expectedOutput: @" Source.Class Source.Struct Source.Enum Source.Interface Source.StaticClass System.String System.Int32 System.IO.FileMode System.IFormattable System.Math System.Void"); comp.VerifyDiagnostics(); comp.VerifyIL("Program.Main", @"{ // Code size 166 (0xa6) .maxstack 1 IL_0000: ldtoken ""Source.Class"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: ldtoken ""Source.Struct"" IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0019: call ""void System.Console.WriteLine(object)"" IL_001e: ldtoken ""Source.Enum"" IL_0023: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0028: call ""void System.Console.WriteLine(object)"" IL_002d: ldtoken ""Source.Interface"" IL_0032: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0037: call ""void System.Console.WriteLine(object)"" IL_003c: ldtoken ""Source.StaticClass"" IL_0041: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0046: call ""void System.Console.WriteLine(object)"" IL_004b: ldtoken ""string"" IL_0050: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0055: call ""void System.Console.WriteLine(object)"" IL_005a: ldtoken ""int"" IL_005f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0064: call ""void System.Console.WriteLine(object)"" IL_0069: ldtoken ""System.IO.FileMode"" IL_006e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0073: call ""void System.Console.WriteLine(object)"" IL_0078: ldtoken ""System.IFormattable"" IL_007d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0082: call ""void System.Console.WriteLine(object)"" IL_0087: ldtoken ""System.Math"" IL_008c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0091: call ""void System.Console.WriteLine(object)"" IL_0096: ldtoken ""void"" IL_009b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00a0: call ""void System.Console.WriteLine(object)"" IL_00a5: ret }"); } [Fact] public void TestTypeofGeneric() { var source = @" class Class1<T> { } class Class2<T, U> { } class Program { static void Main() { System.Console.WriteLine(typeof(Class1<int>)); System.Console.WriteLine(typeof(Class1<Class1<int>>)); System.Console.WriteLine(typeof(Class2<int, long>)); System.Console.WriteLine(typeof(Class2<Class1<int>, Class1<long>>)); } }"; var comp = CompileAndVerify(source, expectedOutput: @" Class1`1[System.Int32] Class1`1[Class1`1[System.Int32]] Class2`2[System.Int32,System.Int64] Class2`2[Class1`1[System.Int32],Class1`1[System.Int64]]"); comp.VerifyDiagnostics(); comp.VerifyIL("Program.Main", @"{ // Code size 61 (0x3d) .maxstack 1 IL_0000: ldtoken ""Class1<int>"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: ldtoken ""Class1<Class1<int>>"" IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0019: call ""void System.Console.WriteLine(object)"" IL_001e: ldtoken ""Class2<int, long>"" IL_0023: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0028: call ""void System.Console.WriteLine(object)"" IL_002d: ldtoken ""Class2<Class1<int>, Class1<long>>"" IL_0032: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0037: call ""void System.Console.WriteLine(object)"" IL_003c: ret }"); } [Fact] public void TestTypeofTypeParameter() { var source = @" class Class<T> { public static void Print() { System.Console.WriteLine(typeof(T)); System.Console.WriteLine(typeof(Class<T>)); } public static void Print<U>() { System.Console.WriteLine(typeof(U)); System.Console.WriteLine(typeof(Class<U>)); } } class Program { static void Main() { Class<int>.Print(); Class<Class<int>>.Print(); Class<int>.Print<long>(); Class<Class<int>>.Print<Class<long>>(); } }"; var comp = CompileAndVerify(source, expectedOutput: @" System.Int32 Class`1[System.Int32] Class`1[System.Int32] Class`1[Class`1[System.Int32]] System.Int64 Class`1[System.Int64] Class`1[System.Int64] Class`1[Class`1[System.Int64]]"); comp.VerifyDiagnostics(); comp.VerifyIL("Class<T>.Print", @"{ // Code size 31 (0x1f) .maxstack 1 IL_0000: ldtoken ""T"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: ldtoken ""Class<T>"" IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0019: call ""void System.Console.WriteLine(object)"" IL_001e: ret }"); comp.VerifyIL("Class<T>.Print<U>", @"{ // Code size 31 (0x1f) .maxstack 1 IL_0000: ldtoken ""U"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: ldtoken ""Class<U>"" IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0019: call ""void System.Console.WriteLine(object)"" IL_001e: ret }"); } [Fact] public void TestTypeofUnboundGeneric() { var source = @" class Class1<T> { } class Class2<T, U> { } class Program { static void Main() { System.Console.WriteLine(typeof(Class1<>)); System.Console.WriteLine(typeof(Class2<,>)); } }"; var comp = CompileAndVerify(source, expectedOutput: @" Class1`1[T] Class2`2[T,U]"); comp.VerifyDiagnostics(); comp.VerifyIL("Program.Main", @"{ // Code size 31 (0x1f) .maxstack 1 IL_0000: ldtoken ""Class1<T>"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: ldtoken ""Class2<T, U>"" IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0019: call ""void System.Console.WriteLine(object)"" IL_001e: ret }"); } [WorkItem(542581, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542581")] [Fact] public void TestTypeofInheritedNestedTypeThroughUnboundGeneric_01() { var source = @" using System; class D<T> : C, I1, I2<T, int> { } interface I1 { } interface I2<T, U> { } class F<T> { public class E {} } class G<T> : F<T>, I1, I2<T, int> { } class H<T, U> { public class E {} } class K<T> : H<T, int>{ } class C { public class E { } static void Main() { Console.WriteLine(typeof(D<>.E)); Console.WriteLine(typeof(D<>).BaseType); var interfaces = typeof(D<>).GetInterfaces(); Console.WriteLine(interfaces[0]); Console.WriteLine(interfaces[1]); Console.WriteLine(typeof(G<>.E)); Console.WriteLine(typeof(G<>).BaseType); interfaces = typeof(G<>).GetInterfaces(); Console.WriteLine(interfaces[0]); Console.WriteLine(interfaces[1]); Console.WriteLine(typeof(K<>.E)); Console.WriteLine(typeof(K<>).BaseType); } }"; var expected = @"C+E C I1 I2`2[T,System.Int32] F`1+E[T] F`1[T] I1 I2`2[T,System.Int32] H`2+E[T,U] H`2[T,System.Int32]"; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [WorkItem(542581, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542581")] [WorkItem(9850, "https://github.com/dotnet/roslyn/issues/9850")] [Fact] public void TestTypeofInheritedNestedTypeThroughUnboundGeneric_02() { var source = @" using System; class C { public class E { } public class E<V> { } static void Main() { var t1 = typeof(D<>.E); Console.WriteLine(t1); var t2 = typeof(F<>.E); var t3 = typeof(G<>.E); Console.WriteLine(t2); Console.WriteLine(t3); Console.WriteLine(t2.Equals(t3)); var t4 = typeof(D<>.E<>); Console.WriteLine(t4); var t5 = typeof(F<>.E<>); var t6 = typeof(G<>.E<>); Console.WriteLine(t5); Console.WriteLine(t6); Console.WriteLine(t5.Equals(t6)); } } class C<U> { public class E { } public class E<V> { } } class D<T> : C { } class F<T> : C<T> { } class G<T> : C<int> { } "; var expected = @"C+E C`1+E[U] C`1+E[U] True C+E`1[V] C`1+E`1[U,V] C`1+E`1[U,V] True"; var comp = CompileAndVerify(source, expectedOutput: expected); comp.VerifyDiagnostics(); } [WorkItem(542581, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542581")] [Fact] public void TestTypeofInheritedNestedTypeThroughUnboundGeneric_Attribute() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class TestAttribute : Attribute { public TestAttribute(System.Type type){} } class D<T> : C, I1, I2<T, int> { } interface I1 { } interface I2<T, U> { } class F<T> { public class E {} } class G<T> : F<T>, I1, I2<T, int> { } class H<T, U> { public class E {} } class K<T> : H<T, int>{ } [TestAttribute(typeof(D<>))] [TestAttribute(typeof(D<>.E))] [TestAttribute(typeof(G<>))] [TestAttribute(typeof(G<>.E))] [TestAttribute(typeof(K<>))] [TestAttribute(typeof(K<>.E))] class C { public class E { } static void Main() { typeof(C).GetCustomAttributes(false); } }"; var comp = CompileAndVerify(source, expectedOutput: ""); } [Fact] public void TestTypeofArray() { var source = @" class Class1<T> { } class Program { static void Print<U>() { System.Console.WriteLine(typeof(int[])); System.Console.WriteLine(typeof(int[,])); System.Console.WriteLine(typeof(int[][])); System.Console.WriteLine(typeof(U[])); System.Console.WriteLine(typeof(Class1<U>[])); System.Console.WriteLine(typeof(Class1<int>[])); } static void Main() { Print<long>(); } }"; var comp = CompileAndVerify(source, expectedOutput: @" System.Int32[] System.Int32[,] System.Int32[][] System.Int64[] Class1`1[System.Int64][] Class1`1[System.Int32][]"); comp.VerifyDiagnostics(); comp.VerifyIL("Program.Print<U>", @"{ // Code size 91 (0x5b) .maxstack 1 IL_0000: ldtoken ""int[]"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: ldtoken ""int[,]"" IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0019: call ""void System.Console.WriteLine(object)"" IL_001e: ldtoken ""int[][]"" IL_0023: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0028: call ""void System.Console.WriteLine(object)"" IL_002d: ldtoken ""U[]"" IL_0032: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0037: call ""void System.Console.WriteLine(object)"" IL_003c: ldtoken ""Class1<U>[]"" IL_0041: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0046: call ""void System.Console.WriteLine(object)"" IL_004b: ldtoken ""Class1<int>[]"" IL_0050: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0055: call ""void System.Console.WriteLine(object)"" IL_005a: ret }"); } [Fact] public void TestTypeofNested() { var source = @" class Outer<T> { public static void Print() { System.Console.WriteLine(typeof(Inner<>)); System.Console.WriteLine(typeof(Inner<T>)); System.Console.WriteLine(typeof(Inner<int>)); System.Console.WriteLine(typeof(Outer<>.Inner<>)); // System.Console.WriteLine(typeof(Outer<>.Inner<T>)); //CS7003 // System.Console.WriteLine(typeof(Outer<>.Inner<int>)); //CS7003 // System.Console.WriteLine(typeof(Outer<T>.Inner<>)); //CS7003 System.Console.WriteLine(typeof(Outer<T>.Inner<T>)); System.Console.WriteLine(typeof(Outer<T>.Inner<int>)); // System.Console.WriteLine(typeof(Outer<int>.Inner<>)); //CS7003 System.Console.WriteLine(typeof(Outer<int>.Inner<T>)); System.Console.WriteLine(typeof(Outer<int>.Inner<int>)); } class Inner<U> { } } class Program { static void Main() { Outer<long>.Print(); } }"; var comp = CompileAndVerify(source, expectedOutput: @" Outer`1+Inner`1[T,U] Outer`1+Inner`1[System.Int64,System.Int64] Outer`1+Inner`1[System.Int64,System.Int32] Outer`1+Inner`1[T,U] Outer`1+Inner`1[System.Int64,System.Int64] Outer`1+Inner`1[System.Int64,System.Int32] Outer`1+Inner`1[System.Int32,System.Int64] Outer`1+Inner`1[System.Int32,System.Int32]"); comp.VerifyDiagnostics(); comp.VerifyIL("Outer<T>.Print", @"{ // Code size 121 (0x79) .maxstack 1 IL_0000: ldtoken ""Outer<T>.Inner<U>"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: ldtoken ""Outer<T>.Inner<T>"" IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0019: call ""void System.Console.WriteLine(object)"" IL_001e: ldtoken ""Outer<T>.Inner<int>"" IL_0023: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0028: call ""void System.Console.WriteLine(object)"" IL_002d: ldtoken ""Outer<T>.Inner<U>"" IL_0032: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0037: call ""void System.Console.WriteLine(object)"" IL_003c: ldtoken ""Outer<T>.Inner<T>"" IL_0041: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0046: call ""void System.Console.WriteLine(object)"" IL_004b: ldtoken ""Outer<T>.Inner<int>"" IL_0050: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0055: call ""void System.Console.WriteLine(object)"" IL_005a: ldtoken ""Outer<int>.Inner<T>"" IL_005f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0064: call ""void System.Console.WriteLine(object)"" IL_0069: ldtoken ""Outer<int>.Inner<int>"" IL_006e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0073: call ""void System.Console.WriteLine(object)"" IL_0078: ret }"); } [Fact] public void TestTypeofInLambda() { var source = @" using System; public class Outer<T> { public class Inner<U> { public Action Method<V>(V v) { return () => { Console.WriteLine(v); Console.WriteLine(typeof(T)); Console.WriteLine(typeof(U)); Console.WriteLine(typeof(V)); Console.WriteLine(typeof(Outer<>)); Console.WriteLine(typeof(Outer<T>)); Console.WriteLine(typeof(Outer<U>)); Console.WriteLine(typeof(Outer<V>)); Console.WriteLine(typeof(Inner<>)); Console.WriteLine(typeof(Inner<T>)); Console.WriteLine(typeof(Inner<U>)); Console.WriteLine(typeof(Inner<V>)); }; } } } class Program { static void Main() { Action a = new Outer<int>.Inner<char>().Method<byte>(1); a(); } }"; var comp = CompileAndVerify(source, expectedOutput: @" 1 System.Int32 System.Char System.Byte Outer`1[T] Outer`1[System.Int32] Outer`1[System.Char] Outer`1[System.Byte] Outer`1+Inner`1[T,U] Outer`1+Inner`1[System.Int32,System.Int32] Outer`1+Inner`1[System.Int32,System.Char] Outer`1+Inner`1[System.Int32,System.Byte]"); comp.VerifyDiagnostics(); } [WorkItem(541600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541600")] [Fact] public void TestTypeOfAlias4TypeMemberOfGeneric() { var source = @" using System; using MyTestClass = TestClass<string>; public class TestClass<T> { public enum TestEnum { First = 0, } } public class mem178 { public static int Main() { Console.Write(typeof(MyTestClass.TestEnum)); return 0; } } "; CompileAndVerify(source, expectedOutput: @"TestClass`1+TestEnum[System.String]"); } [WorkItem(541618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541618")] [Fact] public void TestTypeOfAlias5TypeMemberOfGeneric() { var source = @" using OuterOfString = Outer<string>; using OuterOfInt = Outer<int>; public class Outer<T> { public class Inner<U> { } } public class Program { public static void Main() { System.Console.WriteLine(typeof(OuterOfString.Inner<>) == typeof(OuterOfInt.Inner<>)); } } "; // NOTE: this is the Dev10 output. Change to false if we decide to take a breaking change. CompileAndVerify(source, expectedOutput: @"True"); } } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/Core/Portable/Workspace/Host/SourceFiles/IDynamicFileInfoProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Host { /// <summary> /// Provider for the <see cref="DynamicFileInfo"/> /// /// implementer of this service should be pure free-thread meaning it can't switch to UI thread underneath. /// otherwise, we can get into dead lock if we wait for the dynamic file info from UI thread /// </summary> internal interface IDynamicFileInfoProvider { /// <summary> /// return <see cref="DynamicFileInfo"/> for the context given /// </summary> /// <param name="projectId"><see cref="ProjectId"/> this file belongs to</param> /// <param name="projectFilePath">full path to project file (ex, csproj)</param> /// <param name="filePath">full path to non source file (ex, cshtml)</param> /// <returns>null if this provider can't handle the given file</returns> Task<DynamicFileInfo> GetDynamicFileInfoAsync(ProjectId projectId, string projectFilePath, string filePath, CancellationToken cancellationToken); /// <summary> /// let provider know certain file has been removed /// </summary> /// <param name="projectId"><see cref="ProjectId"/> this file belongs to</param> /// <param name="projectFilePath">full path to project file (ex, csproj)</param> /// <param name="filePath">full path to non source file (ex, cshtml)</param> Task RemoveDynamicFileInfoAsync(ProjectId projectId, string projectFilePath, string filePath, CancellationToken cancellationToken); /// <summary> /// indicate content of a file has updated. the event argument "string" should be same as "filepath" given to <see cref="GetDynamicFileInfoAsync(ProjectId, string, string, CancellationToken)"/> /// </summary> event EventHandler<string> Updated; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Host { /// <summary> /// Provider for the <see cref="DynamicFileInfo"/> /// /// implementer of this service should be pure free-thread meaning it can't switch to UI thread underneath. /// otherwise, we can get into dead lock if we wait for the dynamic file info from UI thread /// </summary> internal interface IDynamicFileInfoProvider { /// <summary> /// return <see cref="DynamicFileInfo"/> for the context given /// </summary> /// <param name="projectId"><see cref="ProjectId"/> this file belongs to</param> /// <param name="projectFilePath">full path to project file (ex, csproj)</param> /// <param name="filePath">full path to non source file (ex, cshtml)</param> /// <returns>null if this provider can't handle the given file</returns> Task<DynamicFileInfo> GetDynamicFileInfoAsync(ProjectId projectId, string projectFilePath, string filePath, CancellationToken cancellationToken); /// <summary> /// let provider know certain file has been removed /// </summary> /// <param name="projectId"><see cref="ProjectId"/> this file belongs to</param> /// <param name="projectFilePath">full path to project file (ex, csproj)</param> /// <param name="filePath">full path to non source file (ex, cshtml)</param> Task RemoveDynamicFileInfoAsync(ProjectId projectId, string projectFilePath, string filePath, CancellationToken cancellationToken); /// <summary> /// indicate content of a file has updated. the event argument "string" should be same as "filepath" given to <see cref="GetDynamicFileInfoAsync(ProjectId, string, string, CancellationToken)"/> /// </summary> event EventHandler<string> Updated; } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo_Metadata.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PersistentStorage; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { internal partial class SymbolTreeInfo { private static string GetMetadataNameWithoutBackticks(MetadataReader reader, StringHandle name) { var blobReader = reader.GetBlobReader(name); var backtickIndex = blobReader.IndexOf((byte)'`'); if (backtickIndex == -1) { return reader.GetString(name); } unsafe { return MetadataStringDecoder.DefaultUTF8.GetString( blobReader.CurrentPointer, backtickIndex); } } public static MetadataId GetMetadataIdNoThrow(PortableExecutableReference reference) { try { return reference.GetMetadataId(); } catch (Exception e) when (e is BadImageFormatException || e is IOException) { return null; } } private static Metadata GetMetadataNoThrow(PortableExecutableReference reference) { try { return reference.GetMetadata(); } catch (Exception e) when (e is BadImageFormatException || e is IOException) { return null; } } public static ValueTask<SymbolTreeInfo> GetInfoForMetadataReferenceAsync( Solution solution, PortableExecutableReference reference, bool loadOnly, CancellationToken cancellationToken) { var checksum = GetMetadataChecksum(solution, reference, cancellationToken); return GetInfoForMetadataReferenceAsync( solution, reference, checksum, loadOnly, cancellationToken); } /// <summary> /// Produces a <see cref="SymbolTreeInfo"/> for a given <see cref="PortableExecutableReference"/>. /// Note: will never return null; /// </summary> [PerformanceSensitive("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1224834", OftenCompletesSynchronously = true)] public static async ValueTask<SymbolTreeInfo> GetInfoForMetadataReferenceAsync( Solution solution, PortableExecutableReference reference, Checksum checksum, bool loadOnly, CancellationToken cancellationToken) { var metadataId = GetMetadataIdNoThrow(reference); if (metadataId == null) return CreateEmpty(checksum); if (s_metadataIdToInfo.TryGetValue(metadataId, out var infoTask)) { var info = await infoTask.GetValueAsync(cancellationToken).ConfigureAwait(false); if (info.Checksum == checksum) return info; } var metadata = GetMetadataNoThrow(reference); if (metadata == null) return CreateEmpty(checksum); // If the data isn't in the table, and the client only wants the data if already loaded, then bail out as we // have no results to give. The data will eventually populate in memory due to // SymbolTreeInfoIncrementalAnalyzer eventually getting around to loading it. if (loadOnly) return null; return await GetInfoForMetadataReferenceSlowAsync( solution.Workspace, SolutionKey.ToSolutionKey(solution), reference, checksum, metadata, cancellationToken).ConfigureAwait(false); } private static async Task<SymbolTreeInfo> GetInfoForMetadataReferenceSlowAsync( Workspace workspace, SolutionKey solutionKey, PortableExecutableReference reference, Checksum checksum, Metadata metadata, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Important: this captured async lazy may live a long time *without* computing the final results. As such, // it is important that it note capture any large state. For example, it should not hold onto a Solution // instance. var asyncLazy = s_metadataIdToInfo.GetValue( metadata.Id, id => new AsyncLazy<SymbolTreeInfo>( c => TryCreateMetadataSymbolTreeInfoAsync(workspace, solutionKey, reference, checksum, c), cacheResult: true)); return await asyncLazy.GetValueAsync(cancellationToken).ConfigureAwait(false); } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/33131", AllowCaptures = false)] public static Checksum GetMetadataChecksum( Solution solution, PortableExecutableReference reference, CancellationToken cancellationToken) { // We can reuse the index for any given reference as long as it hasn't changed. // So our checksum is just the checksum for the PEReference itself. // First see if the value is already in the cache, to avoid an allocation if possible. if (ChecksumCache.TryGetValue(reference, out var cached)) { return cached; } // Break things up to the fast path above and this slow path where we allocate a closure. return GetMetadataChecksumSlow(solution, reference, cancellationToken); } private static Checksum GetMetadataChecksumSlow(Solution solution, PortableExecutableReference reference, CancellationToken cancellationToken) { return ChecksumCache.GetOrCreate(reference, _ => { var serializer = solution.Workspace.Services.GetService<ISerializerService>(); var checksum = serializer.CreateChecksum(reference, cancellationToken); // Include serialization format version in our checksum. That way if the // version ever changes, all persisted data won't match the current checksum // we expect, and we'll recompute things. return Checksum.Create(checksum, SerializationFormatChecksum); }); } private static Task<SymbolTreeInfo> TryCreateMetadataSymbolTreeInfoAsync( Workspace workspace, SolutionKey solutionKey, PortableExecutableReference reference, Checksum checksum, CancellationToken cancellationToken) { var filePath = reference.FilePath; var result = TryLoadOrCreateAsync( workspace, solutionKey, checksum, loadOnly: false, createAsync: () => CreateMetadataSymbolTreeInfoAsync(workspace, solutionKey, checksum, reference), keySuffix: "_Metadata_" + filePath, tryReadObject: reader => TryReadSymbolTreeInfo(reader, checksum, nodes => GetSpellCheckerAsync(workspace, solutionKey, checksum, filePath, nodes)), cancellationToken: cancellationToken); Contract.ThrowIfNull(result != null); return result; } private static Task<SymbolTreeInfo> CreateMetadataSymbolTreeInfoAsync( Workspace workspace, SolutionKey solutionKey, Checksum checksum, PortableExecutableReference reference) { var creator = new MetadataInfoCreator(workspace, solutionKey, checksum, reference); return Task.FromResult(creator.Create()); } private struct MetadataInfoCreator : IDisposable { private static readonly Predicate<string> s_isNotNullOrEmpty = s => !string.IsNullOrEmpty(s); private static readonly ObjectPool<List<string>> s_stringListPool = SharedPools.Default<List<string>>(); private readonly Workspace _workspace; private readonly SolutionKey _solutionKey; private readonly Checksum _checksum; private readonly PortableExecutableReference _reference; private readonly OrderPreservingMultiDictionary<string, string> _inheritanceMap; private readonly OrderPreservingMultiDictionary<MetadataNode, MetadataNode> _parentToChildren; private readonly MetadataNode _rootNode; // The metadata reader for the current metadata in the PEReference. private MetadataReader _metadataReader; // The set of type definitions we've read out of the current metadata reader. private readonly List<MetadataDefinition> _allTypeDefinitions; // Map from node represents extension method to list of possible parameter type info. // We can have more than one if there's multiple methods with same name but different receiver type. // e.g. // // public static bool AnotherExtensionMethod1(this int x); // public static bool AnotherExtensionMethod1(this bool x); // private readonly MultiDictionary<MetadataNode, ParameterTypeInfo> _extensionMethodToParameterTypeInfo; private bool _containsExtensionsMethod; public MetadataInfoCreator( Workspace workspace, SolutionKey solutionKey, Checksum checksum, PortableExecutableReference reference) { _workspace = workspace; _solutionKey = solutionKey; _checksum = checksum; _reference = reference; _metadataReader = null; _allTypeDefinitions = new List<MetadataDefinition>(); _containsExtensionsMethod = false; _inheritanceMap = OrderPreservingMultiDictionary<string, string>.GetInstance(); _parentToChildren = OrderPreservingMultiDictionary<MetadataNode, MetadataNode>.GetInstance(); _extensionMethodToParameterTypeInfo = new MultiDictionary<MetadataNode, ParameterTypeInfo>(); _rootNode = MetadataNode.Allocate(name: ""); } private static ImmutableArray<ModuleMetadata> GetModuleMetadata(Metadata metadata) { try { if (metadata is AssemblyMetadata assembly) { return assembly.GetModules(); } else if (metadata is ModuleMetadata module) { return ImmutableArray.Create(module); } } catch (BadImageFormatException) { // Trying to get the modules of an assembly can throw. For example, if // there is an invalid public-key defined for the assembly. See: // https://devdiv.visualstudio.com/DevDiv/_workitems?id=234447 } return ImmutableArray<ModuleMetadata>.Empty; } internal SymbolTreeInfo Create() { foreach (var moduleMetadata in GetModuleMetadata(GetMetadataNoThrow(_reference))) { try { _metadataReader = moduleMetadata.GetMetadataReader(); // First, walk all the symbols from metadata, populating the parentToChilren // map accordingly. GenerateMetadataNodes(); // Now, once we populated the initial map, go and get all the inheritance // information for all the types in the metadata. This may refer to // types that we haven't seen yet. We'll add those types to the parentToChildren // map accordingly. PopulateInheritanceMap(); // Clear the set of type definitions we read out of this piece of metadata. _allTypeDefinitions.Clear(); } catch (BadImageFormatException) { // any operation off metadata can throw BadImageFormatException continue; } } var extensionMethodsMap = new MultiDictionary<string, ExtensionMethodInfo>(); var unsortedNodes = GenerateUnsortedNodes(extensionMethodsMap); return CreateSymbolTreeInfo( _workspace, _solutionKey, _checksum, _reference.FilePath, unsortedNodes, _inheritanceMap, extensionMethodsMap); } public void Dispose() { // Return all the metadata nodes back to the pool so that they can be // used for the next PEReference we read. foreach (var (_, children) in _parentToChildren) { foreach (var child in children) MetadataNode.Free(child); } MetadataNode.Free(_rootNode); _parentToChildren.Free(); _inheritanceMap.Free(); } private void GenerateMetadataNodes() { var globalNamespace = _metadataReader.GetNamespaceDefinitionRoot(); var definitionMap = OrderPreservingMultiDictionary<string, MetadataDefinition>.GetInstance(); try { LookupMetadataDefinitions(globalNamespace, definitionMap); foreach (var (name, definitions) in definitionMap) GenerateMetadataNodes(_rootNode, name, definitions); } finally { definitionMap.Free(); } } private void GenerateMetadataNodes( MetadataNode parentNode, string nodeName, OrderPreservingMultiDictionary<string, MetadataDefinition>.ValueSet definitionsWithSameName) { if (!UnicodeCharacterUtilities.IsValidIdentifier(nodeName)) { return; } var childNode = MetadataNode.Allocate(nodeName); _parentToChildren.Add(parentNode, childNode); // Add all child members var definitionMap = OrderPreservingMultiDictionary<string, MetadataDefinition>.GetInstance(); try { foreach (var definition in definitionsWithSameName) { if (definition.Kind == MetadataDefinitionKind.Member) { // We need to support having multiple methods with same name but different receiver type. _extensionMethodToParameterTypeInfo.Add(childNode, definition.ReceiverTypeInfo); } LookupMetadataDefinitions(definition, definitionMap); } foreach (var (name, definitions) in definitionMap) GenerateMetadataNodes(childNode, name, definitions); } finally { definitionMap.Free(); } } private void LookupMetadataDefinitions( MetadataDefinition definition, OrderPreservingMultiDictionary<string, MetadataDefinition> definitionMap) { switch (definition.Kind) { case MetadataDefinitionKind.Namespace: LookupMetadataDefinitions(definition.Namespace, definitionMap); break; case MetadataDefinitionKind.Type: LookupMetadataDefinitions(definition.Type, definitionMap); break; } } private void LookupMetadataDefinitions( TypeDefinition typeDefinition, OrderPreservingMultiDictionary<string, MetadataDefinition> definitionMap) { // Only bother looking for extension methods in static types. // Note this check means we would ignore extension methods declared in assemblies // compiled from VB code, since a module in VB is compiled into class with // "sealed" attribute but not "abstract". // Although this can be addressed by checking custom attributes, // we believe this is not a common scenario to warrant potential perf impact. if ((typeDefinition.Attributes & TypeAttributes.Abstract) != 0 && (typeDefinition.Attributes & TypeAttributes.Sealed) != 0) { foreach (var child in typeDefinition.GetMethods()) { var method = _metadataReader.GetMethodDefinition(child); if ((method.Attributes & MethodAttributes.SpecialName) != 0 || (method.Attributes & MethodAttributes.RTSpecialName) != 0) { continue; } // SymbolTreeInfo is only searched for types and extension methods. // So we don't want to pull in all methods here. As a simple approximation // we just pull in methods that have attributes on them. if ((method.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Public && (method.Attributes & MethodAttributes.Static) != 0 && method.GetParameters().Count > 0 && method.GetCustomAttributes().Count > 0) { // Decode method signature to get the receiver type name (i.e. type name for the first parameter) var blob = _metadataReader.GetBlobReader(method.Signature); var decoder = new SignatureDecoder<ParameterTypeInfo, object>(ParameterTypeInfoProvider.Instance, _metadataReader, genericContext: null); var signature = decoder.DecodeMethodSignature(ref blob); // It'd be good if we don't need to go through all parameters and make unnecessary allocations. // However, this is not possible with meatadata reader API right now (although it's possible by copying code from meatadata reader implementaion) if (signature.ParameterTypes.Length > 0) { _containsExtensionsMethod = true; var firstParameterTypeInfo = signature.ParameterTypes[0]; var definition = new MetadataDefinition(MetadataDefinitionKind.Member, _metadataReader.GetString(method.Name), firstParameterTypeInfo); definitionMap.Add(definition.Name, definition); } } } } foreach (var child in typeDefinition.GetNestedTypes()) { var type = _metadataReader.GetTypeDefinition(child); // We don't include internals from metadata assemblies. It's less likely that // a project would have IVT to it and so it helps us save on memory. It also // means we can avoid loading lots and lots of obfuscated code in the case the // dll was obfuscated. if (IsPublic(type.Attributes)) { var definition = MetadataDefinition.Create(_metadataReader, type); definitionMap.Add(definition.Name, definition); _allTypeDefinitions.Add(definition); } } } private void LookupMetadataDefinitions( NamespaceDefinition namespaceDefinition, OrderPreservingMultiDictionary<string, MetadataDefinition> definitionMap) { foreach (var child in namespaceDefinition.NamespaceDefinitions) { var definition = MetadataDefinition.Create(_metadataReader, child); definitionMap.Add(definition.Name, definition); } foreach (var child in namespaceDefinition.TypeDefinitions) { var typeDefinition = _metadataReader.GetTypeDefinition(child); if (IsPublic(typeDefinition.Attributes)) { var definition = MetadataDefinition.Create(_metadataReader, typeDefinition); definitionMap.Add(definition.Name, definition); _allTypeDefinitions.Add(definition); } } } private static bool IsPublic(TypeAttributes attributes) { var masked = attributes & TypeAttributes.VisibilityMask; return masked == TypeAttributes.Public || masked == TypeAttributes.NestedPublic; } private void PopulateInheritanceMap() { foreach (var typeDefinition in _allTypeDefinitions) { Debug.Assert(typeDefinition.Kind == MetadataDefinitionKind.Type); PopulateInheritance(typeDefinition); } } private void PopulateInheritance(MetadataDefinition metadataTypeDefinition) { var derivedTypeDefinition = metadataTypeDefinition.Type; var interfaceImplHandles = derivedTypeDefinition.GetInterfaceImplementations(); if (derivedTypeDefinition.BaseType.IsNil && interfaceImplHandles.Count == 0) { return; } var derivedTypeSimpleName = metadataTypeDefinition.Name; PopulateInheritance(derivedTypeSimpleName, derivedTypeDefinition.BaseType); foreach (var interfaceImplHandle in interfaceImplHandles) { if (!interfaceImplHandle.IsNil) { var interfaceImpl = _metadataReader.GetInterfaceImplementation(interfaceImplHandle); PopulateInheritance(derivedTypeSimpleName, interfaceImpl.Interface); } } } private void PopulateInheritance( string derivedTypeSimpleName, EntityHandle baseTypeOrInterfaceHandle) { if (baseTypeOrInterfaceHandle.IsNil) { return; } var baseTypeNameParts = s_stringListPool.Allocate(); try { AddBaseTypeNameParts(baseTypeOrInterfaceHandle, baseTypeNameParts); if (baseTypeNameParts.Count > 0 && baseTypeNameParts.TrueForAll(s_isNotNullOrEmpty)) { var lastPart = baseTypeNameParts.Last(); if (!_inheritanceMap.Contains(lastPart, derivedTypeSimpleName)) { _inheritanceMap.Add(baseTypeNameParts.Last(), derivedTypeSimpleName); } // The parent/child map may not know about this base-type yet (for example, // if the base type is a reference to a type outside of this assembly). // Add the base type to our map so we'll be able to resolve it later if // requested. EnsureParentsAndChildren(baseTypeNameParts); } } finally { s_stringListPool.ClearAndFree(baseTypeNameParts); } } private void AddBaseTypeNameParts( EntityHandle baseTypeOrInterfaceHandle, List<string> simpleNames) { var typeDefOrRefHandle = GetTypeDefOrRefHandle(baseTypeOrInterfaceHandle); if (typeDefOrRefHandle.Kind == HandleKind.TypeDefinition) { AddTypeDefinitionNameParts((TypeDefinitionHandle)typeDefOrRefHandle, simpleNames); } else if (typeDefOrRefHandle.Kind == HandleKind.TypeReference) { AddTypeReferenceNameParts((TypeReferenceHandle)typeDefOrRefHandle, simpleNames); } } private void AddTypeDefinitionNameParts( TypeDefinitionHandle handle, List<string> simpleNames) { var typeDefinition = _metadataReader.GetTypeDefinition(handle); var declaringType = typeDefinition.GetDeclaringType(); if (declaringType.IsNil) { // Not a nested type, just add the containing namespace. AddNamespaceParts(typeDefinition.NamespaceDefinition, simpleNames); } else { // We're a nested type, recurse and add the type we're declared in. // It will handle adding the namespace properly. AddTypeDefinitionNameParts(declaringType, simpleNames); } // Now add the simple name of the type itself. simpleNames.Add(GetMetadataNameWithoutBackticks(_metadataReader, typeDefinition.Name)); } private void AddNamespaceParts( StringHandle namespaceHandle, List<string> simpleNames) { var blobReader = _metadataReader.GetBlobReader(namespaceHandle); while (true) { var dotIndex = blobReader.IndexOf((byte)'.'); unsafe { // Note: we won't get any string sharing as we're just using the // default string decoded. However, that's ok. We only produce // these strings when we first read metadata. Then we create and // persist our own index. In the future when we read in that index // there's no way for us to share strings between us and the // compiler at that point. if (dotIndex == -1) { simpleNames.Add(MetadataStringDecoder.DefaultUTF8.GetString( blobReader.CurrentPointer, blobReader.RemainingBytes)); return; } else { simpleNames.Add(MetadataStringDecoder.DefaultUTF8.GetString( blobReader.CurrentPointer, dotIndex)); blobReader.Offset += dotIndex + 1; } } } } private void AddNamespaceParts( NamespaceDefinitionHandle namespaceHandle, List<string> simpleNames) { if (namespaceHandle.IsNil) { return; } var namespaceDefinition = _metadataReader.GetNamespaceDefinition(namespaceHandle); AddNamespaceParts(namespaceDefinition.Parent, simpleNames); simpleNames.Add(_metadataReader.GetString(namespaceDefinition.Name)); } private void AddTypeReferenceNameParts(TypeReferenceHandle handle, List<string> simpleNames) { var typeReference = _metadataReader.GetTypeReference(handle); AddNamespaceParts(typeReference.Namespace, simpleNames); simpleNames.Add(GetMetadataNameWithoutBackticks(_metadataReader, typeReference.Name)); } private EntityHandle GetTypeDefOrRefHandle(EntityHandle baseTypeOrInterfaceHandle) { switch (baseTypeOrInterfaceHandle.Kind) { case HandleKind.TypeDefinition: case HandleKind.TypeReference: return baseTypeOrInterfaceHandle; case HandleKind.TypeSpecification: return FirstEntityHandleProvider.Instance.GetTypeFromSpecification( _metadataReader, (TypeSpecificationHandle)baseTypeOrInterfaceHandle); default: return default; } } private void EnsureParentsAndChildren(List<string> simpleNames) { var currentNode = _rootNode; foreach (var simpleName in simpleNames) { var childNode = GetOrCreateChildNode(currentNode, simpleName); currentNode = childNode; } } private MetadataNode GetOrCreateChildNode( MetadataNode currentNode, string simpleName) { if (_parentToChildren.TryGetValue(currentNode, static (childNode, simpleName) => childNode.Name == simpleName, simpleName, out var childNode)) { // Found an existing child node. Just return that and all // future parts off of it. return childNode; } // Couldn't find a child node with this name. Make a new node for // it and return that for all future parts to be added to. var newChildNode = MetadataNode.Allocate(simpleName); _parentToChildren.Add(currentNode, newChildNode); return newChildNode; } private ImmutableArray<BuilderNode> GenerateUnsortedNodes(MultiDictionary<string, ExtensionMethodInfo> receiverTypeNameToMethodMap) { var unsortedNodes = ArrayBuilder<BuilderNode>.GetInstance(); unsortedNodes.Add(BuilderNode.RootNode); AddUnsortedNodes(unsortedNodes, receiverTypeNameToMethodMap, parentNode: _rootNode, parentIndex: 0, fullyQualifiedContainerName: _containsExtensionsMethod ? "" : null); return unsortedNodes.ToImmutableAndFree(); } private void AddUnsortedNodes(ArrayBuilder<BuilderNode> unsortedNodes, MultiDictionary<string, ExtensionMethodInfo> receiverTypeNameToMethodMap, MetadataNode parentNode, int parentIndex, string fullyQualifiedContainerName) { foreach (var child in _parentToChildren[parentNode]) { var childNode = new BuilderNode(child.Name, parentIndex, _extensionMethodToParameterTypeInfo[child]); var childIndex = unsortedNodes.Count; unsortedNodes.Add(childNode); if (fullyQualifiedContainerName != null) { foreach (var parameterTypeInfo in _extensionMethodToParameterTypeInfo[child]) { // We do not differentiate array of different kinds for simplicity. // e.g. int[], int[][], int[,], etc. are all represented as int[] in the index. // similar for complex receiver types, "[]" means it's an array type, "" otherwise. var parameterTypeName = (parameterTypeInfo.IsComplexType, parameterTypeInfo.IsArray) switch { (true, true) => Extensions.ComplexArrayReceiverTypeName, // complex array type, e.g. "T[,]" (true, false) => Extensions.ComplexReceiverTypeName, // complex non-array type, e.g. "T" (false, true) => parameterTypeInfo.Name + Extensions.ArrayReceiverTypeNameSuffix, // simple array type, e.g. "int[][,]" (false, false) => parameterTypeInfo.Name // simple non-array type, e.g. "int" }; receiverTypeNameToMethodMap.Add(parameterTypeName, new ExtensionMethodInfo(fullyQualifiedContainerName, child.Name)); } } AddUnsortedNodes(unsortedNodes, receiverTypeNameToMethodMap, child, childIndex, Concat(fullyQualifiedContainerName, child.Name)); } static string Concat(string containerName, string name) { if (containerName == null) { return null; } if (containerName.Length == 0) { return name; } return containerName + "." + name; } } } private class MetadataNode { public string Name { get; private set; } private static readonly ObjectPool<MetadataNode> s_pool = SharedPools.Default<MetadataNode>(); public static MetadataNode Allocate(string name) { var node = s_pool.Allocate(); Debug.Assert(node.Name == null); node.Name = name; return node; } public static void Free(MetadataNode node) { Debug.Assert(node.Name != null); node.Name = null; s_pool.Free(node); } } private enum MetadataDefinitionKind { Namespace, Type, Member, } private struct MetadataDefinition { public string Name { get; } public MetadataDefinitionKind Kind { get; } /// <summary> /// Only applies to member kind. Represents the type info of the first parameter. /// </summary> public ParameterTypeInfo ReceiverTypeInfo { get; } public NamespaceDefinition Namespace { get; private set; } public TypeDefinition Type { get; private set; } public MetadataDefinition(MetadataDefinitionKind kind, string name, ParameterTypeInfo receiverTypeInfo = default) : this() { Kind = kind; Name = name; ReceiverTypeInfo = receiverTypeInfo; } public static MetadataDefinition Create( MetadataReader reader, NamespaceDefinitionHandle namespaceHandle) { var definition = reader.GetNamespaceDefinition(namespaceHandle); return new MetadataDefinition( MetadataDefinitionKind.Namespace, reader.GetString(definition.Name)) { Namespace = definition }; } public static MetadataDefinition Create( MetadataReader reader, TypeDefinition definition) { var typeName = GetMetadataNameWithoutBackticks(reader, definition.Name); return new MetadataDefinition(MetadataDefinitionKind.Type, typeName) { Type = definition }; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PersistentStorage; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { internal partial class SymbolTreeInfo { private static string GetMetadataNameWithoutBackticks(MetadataReader reader, StringHandle name) { var blobReader = reader.GetBlobReader(name); var backtickIndex = blobReader.IndexOf((byte)'`'); if (backtickIndex == -1) { return reader.GetString(name); } unsafe { return MetadataStringDecoder.DefaultUTF8.GetString( blobReader.CurrentPointer, backtickIndex); } } public static MetadataId GetMetadataIdNoThrow(PortableExecutableReference reference) { try { return reference.GetMetadataId(); } catch (Exception e) when (e is BadImageFormatException || e is IOException) { return null; } } private static Metadata GetMetadataNoThrow(PortableExecutableReference reference) { try { return reference.GetMetadata(); } catch (Exception e) when (e is BadImageFormatException || e is IOException) { return null; } } public static ValueTask<SymbolTreeInfo> GetInfoForMetadataReferenceAsync( Solution solution, PortableExecutableReference reference, bool loadOnly, CancellationToken cancellationToken) { var checksum = GetMetadataChecksum(solution, reference, cancellationToken); return GetInfoForMetadataReferenceAsync( solution, reference, checksum, loadOnly, cancellationToken); } /// <summary> /// Produces a <see cref="SymbolTreeInfo"/> for a given <see cref="PortableExecutableReference"/>. /// Note: will never return null; /// </summary> [PerformanceSensitive("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1224834", OftenCompletesSynchronously = true)] public static async ValueTask<SymbolTreeInfo> GetInfoForMetadataReferenceAsync( Solution solution, PortableExecutableReference reference, Checksum checksum, bool loadOnly, CancellationToken cancellationToken) { var metadataId = GetMetadataIdNoThrow(reference); if (metadataId == null) return CreateEmpty(checksum); if (s_metadataIdToInfo.TryGetValue(metadataId, out var infoTask)) { var info = await infoTask.GetValueAsync(cancellationToken).ConfigureAwait(false); if (info.Checksum == checksum) return info; } var metadata = GetMetadataNoThrow(reference); if (metadata == null) return CreateEmpty(checksum); // If the data isn't in the table, and the client only wants the data if already loaded, then bail out as we // have no results to give. The data will eventually populate in memory due to // SymbolTreeInfoIncrementalAnalyzer eventually getting around to loading it. if (loadOnly) return null; return await GetInfoForMetadataReferenceSlowAsync( solution.Workspace, SolutionKey.ToSolutionKey(solution), reference, checksum, metadata, cancellationToken).ConfigureAwait(false); } private static async Task<SymbolTreeInfo> GetInfoForMetadataReferenceSlowAsync( Workspace workspace, SolutionKey solutionKey, PortableExecutableReference reference, Checksum checksum, Metadata metadata, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Important: this captured async lazy may live a long time *without* computing the final results. As such, // it is important that it note capture any large state. For example, it should not hold onto a Solution // instance. var asyncLazy = s_metadataIdToInfo.GetValue( metadata.Id, id => new AsyncLazy<SymbolTreeInfo>( c => TryCreateMetadataSymbolTreeInfoAsync(workspace, solutionKey, reference, checksum, c), cacheResult: true)); return await asyncLazy.GetValueAsync(cancellationToken).ConfigureAwait(false); } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/33131", AllowCaptures = false)] public static Checksum GetMetadataChecksum( Solution solution, PortableExecutableReference reference, CancellationToken cancellationToken) { // We can reuse the index for any given reference as long as it hasn't changed. // So our checksum is just the checksum for the PEReference itself. // First see if the value is already in the cache, to avoid an allocation if possible. if (ChecksumCache.TryGetValue(reference, out var cached)) { return cached; } // Break things up to the fast path above and this slow path where we allocate a closure. return GetMetadataChecksumSlow(solution, reference, cancellationToken); } private static Checksum GetMetadataChecksumSlow(Solution solution, PortableExecutableReference reference, CancellationToken cancellationToken) { return ChecksumCache.GetOrCreate(reference, _ => { var serializer = solution.Workspace.Services.GetService<ISerializerService>(); var checksum = serializer.CreateChecksum(reference, cancellationToken); // Include serialization format version in our checksum. That way if the // version ever changes, all persisted data won't match the current checksum // we expect, and we'll recompute things. return Checksum.Create(checksum, SerializationFormatChecksum); }); } private static Task<SymbolTreeInfo> TryCreateMetadataSymbolTreeInfoAsync( Workspace workspace, SolutionKey solutionKey, PortableExecutableReference reference, Checksum checksum, CancellationToken cancellationToken) { var filePath = reference.FilePath; var result = TryLoadOrCreateAsync( workspace, solutionKey, checksum, loadOnly: false, createAsync: () => CreateMetadataSymbolTreeInfoAsync(workspace, solutionKey, checksum, reference), keySuffix: "_Metadata_" + filePath, tryReadObject: reader => TryReadSymbolTreeInfo(reader, checksum, nodes => GetSpellCheckerAsync(workspace, solutionKey, checksum, filePath, nodes)), cancellationToken: cancellationToken); Contract.ThrowIfNull(result != null); return result; } private static Task<SymbolTreeInfo> CreateMetadataSymbolTreeInfoAsync( Workspace workspace, SolutionKey solutionKey, Checksum checksum, PortableExecutableReference reference) { var creator = new MetadataInfoCreator(workspace, solutionKey, checksum, reference); return Task.FromResult(creator.Create()); } private struct MetadataInfoCreator : IDisposable { private static readonly Predicate<string> s_isNotNullOrEmpty = s => !string.IsNullOrEmpty(s); private static readonly ObjectPool<List<string>> s_stringListPool = SharedPools.Default<List<string>>(); private readonly Workspace _workspace; private readonly SolutionKey _solutionKey; private readonly Checksum _checksum; private readonly PortableExecutableReference _reference; private readonly OrderPreservingMultiDictionary<string, string> _inheritanceMap; private readonly OrderPreservingMultiDictionary<MetadataNode, MetadataNode> _parentToChildren; private readonly MetadataNode _rootNode; // The metadata reader for the current metadata in the PEReference. private MetadataReader _metadataReader; // The set of type definitions we've read out of the current metadata reader. private readonly List<MetadataDefinition> _allTypeDefinitions; // Map from node represents extension method to list of possible parameter type info. // We can have more than one if there's multiple methods with same name but different receiver type. // e.g. // // public static bool AnotherExtensionMethod1(this int x); // public static bool AnotherExtensionMethod1(this bool x); // private readonly MultiDictionary<MetadataNode, ParameterTypeInfo> _extensionMethodToParameterTypeInfo; private bool _containsExtensionsMethod; public MetadataInfoCreator( Workspace workspace, SolutionKey solutionKey, Checksum checksum, PortableExecutableReference reference) { _workspace = workspace; _solutionKey = solutionKey; _checksum = checksum; _reference = reference; _metadataReader = null; _allTypeDefinitions = new List<MetadataDefinition>(); _containsExtensionsMethod = false; _inheritanceMap = OrderPreservingMultiDictionary<string, string>.GetInstance(); _parentToChildren = OrderPreservingMultiDictionary<MetadataNode, MetadataNode>.GetInstance(); _extensionMethodToParameterTypeInfo = new MultiDictionary<MetadataNode, ParameterTypeInfo>(); _rootNode = MetadataNode.Allocate(name: ""); } private static ImmutableArray<ModuleMetadata> GetModuleMetadata(Metadata metadata) { try { if (metadata is AssemblyMetadata assembly) { return assembly.GetModules(); } else if (metadata is ModuleMetadata module) { return ImmutableArray.Create(module); } } catch (BadImageFormatException) { // Trying to get the modules of an assembly can throw. For example, if // there is an invalid public-key defined for the assembly. See: // https://devdiv.visualstudio.com/DevDiv/_workitems?id=234447 } return ImmutableArray<ModuleMetadata>.Empty; } internal SymbolTreeInfo Create() { foreach (var moduleMetadata in GetModuleMetadata(GetMetadataNoThrow(_reference))) { try { _metadataReader = moduleMetadata.GetMetadataReader(); // First, walk all the symbols from metadata, populating the parentToChilren // map accordingly. GenerateMetadataNodes(); // Now, once we populated the initial map, go and get all the inheritance // information for all the types in the metadata. This may refer to // types that we haven't seen yet. We'll add those types to the parentToChildren // map accordingly. PopulateInheritanceMap(); // Clear the set of type definitions we read out of this piece of metadata. _allTypeDefinitions.Clear(); } catch (BadImageFormatException) { // any operation off metadata can throw BadImageFormatException continue; } } var extensionMethodsMap = new MultiDictionary<string, ExtensionMethodInfo>(); var unsortedNodes = GenerateUnsortedNodes(extensionMethodsMap); return CreateSymbolTreeInfo( _workspace, _solutionKey, _checksum, _reference.FilePath, unsortedNodes, _inheritanceMap, extensionMethodsMap); } public void Dispose() { // Return all the metadata nodes back to the pool so that they can be // used for the next PEReference we read. foreach (var (_, children) in _parentToChildren) { foreach (var child in children) MetadataNode.Free(child); } MetadataNode.Free(_rootNode); _parentToChildren.Free(); _inheritanceMap.Free(); } private void GenerateMetadataNodes() { var globalNamespace = _metadataReader.GetNamespaceDefinitionRoot(); var definitionMap = OrderPreservingMultiDictionary<string, MetadataDefinition>.GetInstance(); try { LookupMetadataDefinitions(globalNamespace, definitionMap); foreach (var (name, definitions) in definitionMap) GenerateMetadataNodes(_rootNode, name, definitions); } finally { definitionMap.Free(); } } private void GenerateMetadataNodes( MetadataNode parentNode, string nodeName, OrderPreservingMultiDictionary<string, MetadataDefinition>.ValueSet definitionsWithSameName) { if (!UnicodeCharacterUtilities.IsValidIdentifier(nodeName)) { return; } var childNode = MetadataNode.Allocate(nodeName); _parentToChildren.Add(parentNode, childNode); // Add all child members var definitionMap = OrderPreservingMultiDictionary<string, MetadataDefinition>.GetInstance(); try { foreach (var definition in definitionsWithSameName) { if (definition.Kind == MetadataDefinitionKind.Member) { // We need to support having multiple methods with same name but different receiver type. _extensionMethodToParameterTypeInfo.Add(childNode, definition.ReceiverTypeInfo); } LookupMetadataDefinitions(definition, definitionMap); } foreach (var (name, definitions) in definitionMap) GenerateMetadataNodes(childNode, name, definitions); } finally { definitionMap.Free(); } } private void LookupMetadataDefinitions( MetadataDefinition definition, OrderPreservingMultiDictionary<string, MetadataDefinition> definitionMap) { switch (definition.Kind) { case MetadataDefinitionKind.Namespace: LookupMetadataDefinitions(definition.Namespace, definitionMap); break; case MetadataDefinitionKind.Type: LookupMetadataDefinitions(definition.Type, definitionMap); break; } } private void LookupMetadataDefinitions( TypeDefinition typeDefinition, OrderPreservingMultiDictionary<string, MetadataDefinition> definitionMap) { // Only bother looking for extension methods in static types. // Note this check means we would ignore extension methods declared in assemblies // compiled from VB code, since a module in VB is compiled into class with // "sealed" attribute but not "abstract". // Although this can be addressed by checking custom attributes, // we believe this is not a common scenario to warrant potential perf impact. if ((typeDefinition.Attributes & TypeAttributes.Abstract) != 0 && (typeDefinition.Attributes & TypeAttributes.Sealed) != 0) { foreach (var child in typeDefinition.GetMethods()) { var method = _metadataReader.GetMethodDefinition(child); if ((method.Attributes & MethodAttributes.SpecialName) != 0 || (method.Attributes & MethodAttributes.RTSpecialName) != 0) { continue; } // SymbolTreeInfo is only searched for types and extension methods. // So we don't want to pull in all methods here. As a simple approximation // we just pull in methods that have attributes on them. if ((method.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Public && (method.Attributes & MethodAttributes.Static) != 0 && method.GetParameters().Count > 0 && method.GetCustomAttributes().Count > 0) { // Decode method signature to get the receiver type name (i.e. type name for the first parameter) var blob = _metadataReader.GetBlobReader(method.Signature); var decoder = new SignatureDecoder<ParameterTypeInfo, object>(ParameterTypeInfoProvider.Instance, _metadataReader, genericContext: null); var signature = decoder.DecodeMethodSignature(ref blob); // It'd be good if we don't need to go through all parameters and make unnecessary allocations. // However, this is not possible with meatadata reader API right now (although it's possible by copying code from meatadata reader implementaion) if (signature.ParameterTypes.Length > 0) { _containsExtensionsMethod = true; var firstParameterTypeInfo = signature.ParameterTypes[0]; var definition = new MetadataDefinition(MetadataDefinitionKind.Member, _metadataReader.GetString(method.Name), firstParameterTypeInfo); definitionMap.Add(definition.Name, definition); } } } } foreach (var child in typeDefinition.GetNestedTypes()) { var type = _metadataReader.GetTypeDefinition(child); // We don't include internals from metadata assemblies. It's less likely that // a project would have IVT to it and so it helps us save on memory. It also // means we can avoid loading lots and lots of obfuscated code in the case the // dll was obfuscated. if (IsPublic(type.Attributes)) { var definition = MetadataDefinition.Create(_metadataReader, type); definitionMap.Add(definition.Name, definition); _allTypeDefinitions.Add(definition); } } } private void LookupMetadataDefinitions( NamespaceDefinition namespaceDefinition, OrderPreservingMultiDictionary<string, MetadataDefinition> definitionMap) { foreach (var child in namespaceDefinition.NamespaceDefinitions) { var definition = MetadataDefinition.Create(_metadataReader, child); definitionMap.Add(definition.Name, definition); } foreach (var child in namespaceDefinition.TypeDefinitions) { var typeDefinition = _metadataReader.GetTypeDefinition(child); if (IsPublic(typeDefinition.Attributes)) { var definition = MetadataDefinition.Create(_metadataReader, typeDefinition); definitionMap.Add(definition.Name, definition); _allTypeDefinitions.Add(definition); } } } private static bool IsPublic(TypeAttributes attributes) { var masked = attributes & TypeAttributes.VisibilityMask; return masked == TypeAttributes.Public || masked == TypeAttributes.NestedPublic; } private void PopulateInheritanceMap() { foreach (var typeDefinition in _allTypeDefinitions) { Debug.Assert(typeDefinition.Kind == MetadataDefinitionKind.Type); PopulateInheritance(typeDefinition); } } private void PopulateInheritance(MetadataDefinition metadataTypeDefinition) { var derivedTypeDefinition = metadataTypeDefinition.Type; var interfaceImplHandles = derivedTypeDefinition.GetInterfaceImplementations(); if (derivedTypeDefinition.BaseType.IsNil && interfaceImplHandles.Count == 0) { return; } var derivedTypeSimpleName = metadataTypeDefinition.Name; PopulateInheritance(derivedTypeSimpleName, derivedTypeDefinition.BaseType); foreach (var interfaceImplHandle in interfaceImplHandles) { if (!interfaceImplHandle.IsNil) { var interfaceImpl = _metadataReader.GetInterfaceImplementation(interfaceImplHandle); PopulateInheritance(derivedTypeSimpleName, interfaceImpl.Interface); } } } private void PopulateInheritance( string derivedTypeSimpleName, EntityHandle baseTypeOrInterfaceHandle) { if (baseTypeOrInterfaceHandle.IsNil) { return; } var baseTypeNameParts = s_stringListPool.Allocate(); try { AddBaseTypeNameParts(baseTypeOrInterfaceHandle, baseTypeNameParts); if (baseTypeNameParts.Count > 0 && baseTypeNameParts.TrueForAll(s_isNotNullOrEmpty)) { var lastPart = baseTypeNameParts.Last(); if (!_inheritanceMap.Contains(lastPart, derivedTypeSimpleName)) { _inheritanceMap.Add(baseTypeNameParts.Last(), derivedTypeSimpleName); } // The parent/child map may not know about this base-type yet (for example, // if the base type is a reference to a type outside of this assembly). // Add the base type to our map so we'll be able to resolve it later if // requested. EnsureParentsAndChildren(baseTypeNameParts); } } finally { s_stringListPool.ClearAndFree(baseTypeNameParts); } } private void AddBaseTypeNameParts( EntityHandle baseTypeOrInterfaceHandle, List<string> simpleNames) { var typeDefOrRefHandle = GetTypeDefOrRefHandle(baseTypeOrInterfaceHandle); if (typeDefOrRefHandle.Kind == HandleKind.TypeDefinition) { AddTypeDefinitionNameParts((TypeDefinitionHandle)typeDefOrRefHandle, simpleNames); } else if (typeDefOrRefHandle.Kind == HandleKind.TypeReference) { AddTypeReferenceNameParts((TypeReferenceHandle)typeDefOrRefHandle, simpleNames); } } private void AddTypeDefinitionNameParts( TypeDefinitionHandle handle, List<string> simpleNames) { var typeDefinition = _metadataReader.GetTypeDefinition(handle); var declaringType = typeDefinition.GetDeclaringType(); if (declaringType.IsNil) { // Not a nested type, just add the containing namespace. AddNamespaceParts(typeDefinition.NamespaceDefinition, simpleNames); } else { // We're a nested type, recurse and add the type we're declared in. // It will handle adding the namespace properly. AddTypeDefinitionNameParts(declaringType, simpleNames); } // Now add the simple name of the type itself. simpleNames.Add(GetMetadataNameWithoutBackticks(_metadataReader, typeDefinition.Name)); } private void AddNamespaceParts( StringHandle namespaceHandle, List<string> simpleNames) { var blobReader = _metadataReader.GetBlobReader(namespaceHandle); while (true) { var dotIndex = blobReader.IndexOf((byte)'.'); unsafe { // Note: we won't get any string sharing as we're just using the // default string decoded. However, that's ok. We only produce // these strings when we first read metadata. Then we create and // persist our own index. In the future when we read in that index // there's no way for us to share strings between us and the // compiler at that point. if (dotIndex == -1) { simpleNames.Add(MetadataStringDecoder.DefaultUTF8.GetString( blobReader.CurrentPointer, blobReader.RemainingBytes)); return; } else { simpleNames.Add(MetadataStringDecoder.DefaultUTF8.GetString( blobReader.CurrentPointer, dotIndex)); blobReader.Offset += dotIndex + 1; } } } } private void AddNamespaceParts( NamespaceDefinitionHandle namespaceHandle, List<string> simpleNames) { if (namespaceHandle.IsNil) { return; } var namespaceDefinition = _metadataReader.GetNamespaceDefinition(namespaceHandle); AddNamespaceParts(namespaceDefinition.Parent, simpleNames); simpleNames.Add(_metadataReader.GetString(namespaceDefinition.Name)); } private void AddTypeReferenceNameParts(TypeReferenceHandle handle, List<string> simpleNames) { var typeReference = _metadataReader.GetTypeReference(handle); AddNamespaceParts(typeReference.Namespace, simpleNames); simpleNames.Add(GetMetadataNameWithoutBackticks(_metadataReader, typeReference.Name)); } private EntityHandle GetTypeDefOrRefHandle(EntityHandle baseTypeOrInterfaceHandle) { switch (baseTypeOrInterfaceHandle.Kind) { case HandleKind.TypeDefinition: case HandleKind.TypeReference: return baseTypeOrInterfaceHandle; case HandleKind.TypeSpecification: return FirstEntityHandleProvider.Instance.GetTypeFromSpecification( _metadataReader, (TypeSpecificationHandle)baseTypeOrInterfaceHandle); default: return default; } } private void EnsureParentsAndChildren(List<string> simpleNames) { var currentNode = _rootNode; foreach (var simpleName in simpleNames) { var childNode = GetOrCreateChildNode(currentNode, simpleName); currentNode = childNode; } } private MetadataNode GetOrCreateChildNode( MetadataNode currentNode, string simpleName) { if (_parentToChildren.TryGetValue(currentNode, static (childNode, simpleName) => childNode.Name == simpleName, simpleName, out var childNode)) { // Found an existing child node. Just return that and all // future parts off of it. return childNode; } // Couldn't find a child node with this name. Make a new node for // it and return that for all future parts to be added to. var newChildNode = MetadataNode.Allocate(simpleName); _parentToChildren.Add(currentNode, newChildNode); return newChildNode; } private ImmutableArray<BuilderNode> GenerateUnsortedNodes(MultiDictionary<string, ExtensionMethodInfo> receiverTypeNameToMethodMap) { var unsortedNodes = ArrayBuilder<BuilderNode>.GetInstance(); unsortedNodes.Add(BuilderNode.RootNode); AddUnsortedNodes(unsortedNodes, receiverTypeNameToMethodMap, parentNode: _rootNode, parentIndex: 0, fullyQualifiedContainerName: _containsExtensionsMethod ? "" : null); return unsortedNodes.ToImmutableAndFree(); } private void AddUnsortedNodes(ArrayBuilder<BuilderNode> unsortedNodes, MultiDictionary<string, ExtensionMethodInfo> receiverTypeNameToMethodMap, MetadataNode parentNode, int parentIndex, string fullyQualifiedContainerName) { foreach (var child in _parentToChildren[parentNode]) { var childNode = new BuilderNode(child.Name, parentIndex, _extensionMethodToParameterTypeInfo[child]); var childIndex = unsortedNodes.Count; unsortedNodes.Add(childNode); if (fullyQualifiedContainerName != null) { foreach (var parameterTypeInfo in _extensionMethodToParameterTypeInfo[child]) { // We do not differentiate array of different kinds for simplicity. // e.g. int[], int[][], int[,], etc. are all represented as int[] in the index. // similar for complex receiver types, "[]" means it's an array type, "" otherwise. var parameterTypeName = (parameterTypeInfo.IsComplexType, parameterTypeInfo.IsArray) switch { (true, true) => Extensions.ComplexArrayReceiverTypeName, // complex array type, e.g. "T[,]" (true, false) => Extensions.ComplexReceiverTypeName, // complex non-array type, e.g. "T" (false, true) => parameterTypeInfo.Name + Extensions.ArrayReceiverTypeNameSuffix, // simple array type, e.g. "int[][,]" (false, false) => parameterTypeInfo.Name // simple non-array type, e.g. "int" }; receiverTypeNameToMethodMap.Add(parameterTypeName, new ExtensionMethodInfo(fullyQualifiedContainerName, child.Name)); } } AddUnsortedNodes(unsortedNodes, receiverTypeNameToMethodMap, child, childIndex, Concat(fullyQualifiedContainerName, child.Name)); } static string Concat(string containerName, string name) { if (containerName == null) { return null; } if (containerName.Length == 0) { return name; } return containerName + "." + name; } } } private class MetadataNode { public string Name { get; private set; } private static readonly ObjectPool<MetadataNode> s_pool = SharedPools.Default<MetadataNode>(); public static MetadataNode Allocate(string name) { var node = s_pool.Allocate(); Debug.Assert(node.Name == null); node.Name = name; return node; } public static void Free(MetadataNode node) { Debug.Assert(node.Name != null); node.Name = null; s_pool.Free(node); } } private enum MetadataDefinitionKind { Namespace, Type, Member, } private struct MetadataDefinition { public string Name { get; } public MetadataDefinitionKind Kind { get; } /// <summary> /// Only applies to member kind. Represents the type info of the first parameter. /// </summary> public ParameterTypeInfo ReceiverTypeInfo { get; } public NamespaceDefinition Namespace { get; private set; } public TypeDefinition Type { get; private set; } public MetadataDefinition(MetadataDefinitionKind kind, string name, ParameterTypeInfo receiverTypeInfo = default) : this() { Kind = kind; Name = name; ReceiverTypeInfo = receiverTypeInfo; } public static MetadataDefinition Create( MetadataReader reader, NamespaceDefinitionHandle namespaceHandle) { var definition = reader.GetNamespaceDefinition(namespaceHandle); return new MetadataDefinition( MetadataDefinitionKind.Namespace, reader.GetString(definition.Name)) { Namespace = definition }; } public static MetadataDefinition Create( MetadataReader reader, TypeDefinition definition) { var typeName = GetMetadataNameWithoutBackticks(reader, definition.Name); return new MetadataDefinition(MetadataDefinitionKind.Type, typeName) { Type = definition }; } } } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/Core/Impl/CodeModel/ExternalElements/ExternalCodeDelegate.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE.CodeDelegate))] public sealed class ExternalCodeDelegate : AbstractExternalCodeType, EnvDTE80.CodeDelegate2, EnvDTE.CodeDelegate, EnvDTE.CodeType, EnvDTE80.CodeElement2, EnvDTE.CodeElement { internal static EnvDTE.CodeDelegate Create(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol) { var element = new ExternalCodeDelegate(state, projectId, typeSymbol); return (EnvDTE.CodeDelegate)ComAggregate.CreateAggregatedObject(element); } private ExternalCodeDelegate(CodeModelState state, ProjectId projectId, ITypeSymbol symbol) : base(state, projectId, symbol) { } public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementDelegate; } } public EnvDTE.CodeClass BaseClass { get { throw Exceptions.ThrowEFail(); } } public EnvDTE.CodeElements Parameters { get { throw new NotImplementedException(); } } public EnvDTE.CodeTypeRef Type { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public bool IsGeneric { get { throw new NotImplementedException(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE.CodeDelegate))] public sealed class ExternalCodeDelegate : AbstractExternalCodeType, EnvDTE80.CodeDelegate2, EnvDTE.CodeDelegate, EnvDTE.CodeType, EnvDTE80.CodeElement2, EnvDTE.CodeElement { internal static EnvDTE.CodeDelegate Create(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol) { var element = new ExternalCodeDelegate(state, projectId, typeSymbol); return (EnvDTE.CodeDelegate)ComAggregate.CreateAggregatedObject(element); } private ExternalCodeDelegate(CodeModelState state, ProjectId projectId, ITypeSymbol symbol) : base(state, projectId, symbol) { } public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementDelegate; } } public EnvDTE.CodeClass BaseClass { get { throw Exceptions.ThrowEFail(); } } public EnvDTE.CodeElements Parameters { get { throw new NotImplementedException(); } } public EnvDTE.CodeTypeRef Type { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public bool IsGeneric { get { throw new NotImplementedException(); } } } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Portable/BoundTree/BoundNullCoalescingOperatorResultKind.cs
// Licensed to the .NET Foundation under one or more 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 { /// <summary> /// Represents the operand type used for the result of a null-coalescing /// operator. Used when determining nullability. /// </summary> internal enum BoundNullCoalescingOperatorResultKind { /// <summary> /// No valid type for operator. /// </summary> NoCommonType, /// <summary> /// Type of left operand is used. /// </summary> LeftType, /// <summary> /// Nullable underlying type of left operand is used. /// </summary> LeftUnwrappedType, /// <summary> /// Type of right operand is used. /// </summary> RightType, /// <summary> /// Type of right operand is used and nullable left operand is converted /// to underlying type before converting to right operand type. /// </summary> LeftUnwrappedRightType, /// <summary> /// Type of right operand is dynamic and is used. /// </summary> RightDynamicType, } }
// Licensed to the .NET Foundation under one or more 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 { /// <summary> /// Represents the operand type used for the result of a null-coalescing /// operator. Used when determining nullability. /// </summary> internal enum BoundNullCoalescingOperatorResultKind { /// <summary> /// No valid type for operator. /// </summary> NoCommonType, /// <summary> /// Type of left operand is used. /// </summary> LeftType, /// <summary> /// Nullable underlying type of left operand is used. /// </summary> LeftUnwrappedType, /// <summary> /// Type of right operand is used. /// </summary> RightType, /// <summary> /// Type of right operand is used and nullable left operand is converted /// to underlying type before converting to right operand type. /// </summary> LeftUnwrappedRightType, /// <summary> /// Type of right operand is dynamic and is used. /// </summary> RightDynamicType, } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/Core/Impl/CodeModel/AbstractCodeModelObject_CodeGen.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Options; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { /// <summary> /// This is the root class for all code model objects. It contains methods that /// are common to everything. /// </summary> public partial class AbstractCodeModelObject { private static CodeGenerationOptions GetCodeGenerationOptions( EnvDTE.vsCMAccess access, ParseOptions parseOptions, OptionSet options) { var generateDefaultAccessibility = (access & EnvDTE.vsCMAccess.vsCMAccessDefault) == 0; return new CodeGenerationOptions( generateDefaultAccessibility: generateDefaultAccessibility, parseOptions: parseOptions, options: options); } protected SyntaxNode CreateConstructorDeclaration(SyntaxNode containerNode, string typeName, EnvDTE.vsCMAccess access) { var destination = CodeModelService.GetDestination(containerNode); var newMethodSymbol = CodeGenerationSymbolFactory.CreateConstructorSymbol( attributes: default, accessibility: CodeModelService.GetAccessibility(access, SymbolKind.Method, destination), modifiers: new DeclarationModifiers(), typeName: typeName, parameters: default); return CodeGenerationService.CreateMethodDeclaration( newMethodSymbol, destination, options: GetCodeGenerationOptions( access, containerNode.SyntaxTree.Options, options: null)); } protected SyntaxNode CreateDestructorDeclaration(SyntaxNode containerNode, string typeName) { var destination = CodeModelService.GetDestination(containerNode); var newMethodSymbol = CodeGenerationSymbolFactory.CreateDestructorSymbol( attributes: default, typeName: typeName); return CodeGenerationService.CreateMethodDeclaration( newMethodSymbol, destination); } protected SyntaxNode CreateDelegateTypeDeclaration(SyntaxNode containerNode, string name, EnvDTE.vsCMAccess access, INamedTypeSymbol returnType) { var destination = CodeModelService.GetDestination(containerNode); var newTypeSymbol = CodeGenerationSymbolFactory.CreateDelegateTypeSymbol( attributes: default, accessibility: CodeModelService.GetAccessibility(access, SymbolKind.NamedType, destination), modifiers: new DeclarationModifiers(), returnType: returnType, refKind: RefKind.None, name: name); return CodeGenerationService.CreateNamedTypeDeclaration( newTypeSymbol, destination, options: GetCodeGenerationOptions( access, containerNode.SyntaxTree.Options, options: null)); } protected SyntaxNode CreateEventDeclaration(SyntaxNode containerNode, string name, EnvDTE.vsCMAccess access, ITypeSymbol type, bool createPropertyStyleEvent) { var destination = CodeModelService.GetDestination(containerNode); IMethodSymbol addMethod = null; IMethodSymbol removeMethod = null; if (createPropertyStyleEvent) { addMethod = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: default, accessibility: Accessibility.NotApplicable, modifiers: new DeclarationModifiers(), returnType: null, refKind: RefKind.None, explicitInterfaceImplementations: default, name: "add_" + name, typeParameters: default, parameters: default); removeMethod = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: default, accessibility: Accessibility.NotApplicable, modifiers: new DeclarationModifiers(), returnType: null, refKind: RefKind.None, explicitInterfaceImplementations: default, name: "remove_" + name, typeParameters: default, parameters: default); } var newEventSymbol = CodeGenerationSymbolFactory.CreateEventSymbol( attributes: default, accessibility: CodeModelService.GetAccessibility(access, SymbolKind.Event, destination), modifiers: new DeclarationModifiers(), type: type, explicitInterfaceImplementations: default, name: name, addMethod: addMethod, removeMethod: removeMethod); return CodeGenerationService.CreateEventDeclaration( newEventSymbol, destination, options: GetCodeGenerationOptions( access, containerNode.SyntaxTree.Options, options: null)); } protected SyntaxNode CreateFieldDeclaration(SyntaxNode containerNode, string name, EnvDTE.vsCMAccess access, ITypeSymbol type) { var destination = CodeModelService.GetDestination(containerNode); var newFieldSymbol = CodeGenerationSymbolFactory.CreateFieldSymbol( attributes: default, accessibility: CodeModelService.GetAccessibility(access, SymbolKind.Field, destination), modifiers: new DeclarationModifiers(isWithEvents: CodeModelService.GetWithEvents(access)), type: type, name: name); return CodeGenerationService.CreateFieldDeclaration( newFieldSymbol, destination, options: GetCodeGenerationOptions( access, containerNode.SyntaxTree.Options, options: null)); } protected SyntaxNode CreateMethodDeclaration(SyntaxNode containerNode, string name, EnvDTE.vsCMAccess access, ITypeSymbol returnType) { var destination = CodeModelService.GetDestination(containerNode); var newMethodSymbol = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: default, accessibility: CodeModelService.GetAccessibility(access, SymbolKind.Method, destination), modifiers: new DeclarationModifiers(), returnType: returnType, refKind: RefKind.None, explicitInterfaceImplementations: default, name: name, typeParameters: default, parameters: default); var codeGenerationOptions = GetCodeGenerationOptions( access, containerNode.SyntaxTree.Options, options: null); if (destination == CodeGenerationDestination.InterfaceType) { // Generating method with body is allowed when targeting an interface, // so we have to explicitly disable it here. codeGenerationOptions = codeGenerationOptions.With(generateMethodBodies: false); } return CodeGenerationService.CreateMethodDeclaration( newMethodSymbol, destination, options: codeGenerationOptions); } protected SyntaxNode CreatePropertyDeclaration( SyntaxNode containerNode, string name, bool generateGetter, bool generateSetter, EnvDTE.vsCMAccess access, ITypeSymbol type, OptionSet options) { var destination = CodeModelService.GetDestination(containerNode); IMethodSymbol getMethod = null; if (generateGetter) { getMethod = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: default, accessibility: Accessibility.NotApplicable, modifiers: new DeclarationModifiers(), returnType: null, refKind: RefKind.None, explicitInterfaceImplementations: default, name: "get_" + name, typeParameters: default, parameters: default, statements: ImmutableArray.Create(CodeModelService.CreateReturnDefaultValueStatement(type))); } IMethodSymbol setMethod = null; if (generateSetter) { setMethod = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: default, accessibility: Accessibility.NotApplicable, modifiers: new DeclarationModifiers(), returnType: null, refKind: RefKind.None, explicitInterfaceImplementations: default, name: "set_" + name, typeParameters: default, parameters: default); } var newPropertySymbol = CodeGenerationSymbolFactory.CreatePropertySymbol( attributes: default, accessibility: CodeModelService.GetAccessibility(access, SymbolKind.Field, destination), modifiers: new DeclarationModifiers(), type: type, refKind: RefKind.None, explicitInterfaceImplementations: default, name: name, parameters: default, getMethod: getMethod, setMethod: setMethod); return CodeGenerationService.CreatePropertyDeclaration( newPropertySymbol, destination, options: GetCodeGenerationOptions( access, containerNode.SyntaxTree.Options, options)); } protected SyntaxNode CreateNamespaceDeclaration(SyntaxNode containerNode, string name) { var destination = CodeModelService.GetDestination(containerNode); var newNamespaceSymbol = CodeGenerationSymbolFactory.CreateNamespaceSymbol(name); var newNamespace = CodeGenerationService.CreateNamespaceDeclaration( newNamespaceSymbol, destination); return newNamespace; } protected SyntaxNode CreateTypeDeclaration( SyntaxNode containerNode, TypeKind typeKind, string name, EnvDTE.vsCMAccess access, INamedTypeSymbol baseType = null, ImmutableArray<INamedTypeSymbol> implementedInterfaces = default) { var destination = CodeModelService.GetDestination(containerNode); var newTypeSymbol = CodeGenerationSymbolFactory.CreateNamedTypeSymbol( attributes: default, accessibility: CodeModelService.GetAccessibility(access, SymbolKind.NamedType, destination), modifiers: new DeclarationModifiers(), typeKind: typeKind, name: name, typeParameters: default, baseType: baseType, interfaces: implementedInterfaces, specialType: SpecialType.None, members: default); return CodeGenerationService.CreateNamedTypeDeclaration( newTypeSymbol, destination, options: GetCodeGenerationOptions( access, containerNode.SyntaxTree.Options, options: 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 Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Options; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { /// <summary> /// This is the root class for all code model objects. It contains methods that /// are common to everything. /// </summary> public partial class AbstractCodeModelObject { private static CodeGenerationOptions GetCodeGenerationOptions( EnvDTE.vsCMAccess access, ParseOptions parseOptions, OptionSet options) { var generateDefaultAccessibility = (access & EnvDTE.vsCMAccess.vsCMAccessDefault) == 0; return new CodeGenerationOptions( generateDefaultAccessibility: generateDefaultAccessibility, parseOptions: parseOptions, options: options); } protected SyntaxNode CreateConstructorDeclaration(SyntaxNode containerNode, string typeName, EnvDTE.vsCMAccess access) { var destination = CodeModelService.GetDestination(containerNode); var newMethodSymbol = CodeGenerationSymbolFactory.CreateConstructorSymbol( attributes: default, accessibility: CodeModelService.GetAccessibility(access, SymbolKind.Method, destination), modifiers: new DeclarationModifiers(), typeName: typeName, parameters: default); return CodeGenerationService.CreateMethodDeclaration( newMethodSymbol, destination, options: GetCodeGenerationOptions( access, containerNode.SyntaxTree.Options, options: null)); } protected SyntaxNode CreateDestructorDeclaration(SyntaxNode containerNode, string typeName) { var destination = CodeModelService.GetDestination(containerNode); var newMethodSymbol = CodeGenerationSymbolFactory.CreateDestructorSymbol( attributes: default, typeName: typeName); return CodeGenerationService.CreateMethodDeclaration( newMethodSymbol, destination); } protected SyntaxNode CreateDelegateTypeDeclaration(SyntaxNode containerNode, string name, EnvDTE.vsCMAccess access, INamedTypeSymbol returnType) { var destination = CodeModelService.GetDestination(containerNode); var newTypeSymbol = CodeGenerationSymbolFactory.CreateDelegateTypeSymbol( attributes: default, accessibility: CodeModelService.GetAccessibility(access, SymbolKind.NamedType, destination), modifiers: new DeclarationModifiers(), returnType: returnType, refKind: RefKind.None, name: name); return CodeGenerationService.CreateNamedTypeDeclaration( newTypeSymbol, destination, options: GetCodeGenerationOptions( access, containerNode.SyntaxTree.Options, options: null)); } protected SyntaxNode CreateEventDeclaration(SyntaxNode containerNode, string name, EnvDTE.vsCMAccess access, ITypeSymbol type, bool createPropertyStyleEvent) { var destination = CodeModelService.GetDestination(containerNode); IMethodSymbol addMethod = null; IMethodSymbol removeMethod = null; if (createPropertyStyleEvent) { addMethod = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: default, accessibility: Accessibility.NotApplicable, modifiers: new DeclarationModifiers(), returnType: null, refKind: RefKind.None, explicitInterfaceImplementations: default, name: "add_" + name, typeParameters: default, parameters: default); removeMethod = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: default, accessibility: Accessibility.NotApplicable, modifiers: new DeclarationModifiers(), returnType: null, refKind: RefKind.None, explicitInterfaceImplementations: default, name: "remove_" + name, typeParameters: default, parameters: default); } var newEventSymbol = CodeGenerationSymbolFactory.CreateEventSymbol( attributes: default, accessibility: CodeModelService.GetAccessibility(access, SymbolKind.Event, destination), modifiers: new DeclarationModifiers(), type: type, explicitInterfaceImplementations: default, name: name, addMethod: addMethod, removeMethod: removeMethod); return CodeGenerationService.CreateEventDeclaration( newEventSymbol, destination, options: GetCodeGenerationOptions( access, containerNode.SyntaxTree.Options, options: null)); } protected SyntaxNode CreateFieldDeclaration(SyntaxNode containerNode, string name, EnvDTE.vsCMAccess access, ITypeSymbol type) { var destination = CodeModelService.GetDestination(containerNode); var newFieldSymbol = CodeGenerationSymbolFactory.CreateFieldSymbol( attributes: default, accessibility: CodeModelService.GetAccessibility(access, SymbolKind.Field, destination), modifiers: new DeclarationModifiers(isWithEvents: CodeModelService.GetWithEvents(access)), type: type, name: name); return CodeGenerationService.CreateFieldDeclaration( newFieldSymbol, destination, options: GetCodeGenerationOptions( access, containerNode.SyntaxTree.Options, options: null)); } protected SyntaxNode CreateMethodDeclaration(SyntaxNode containerNode, string name, EnvDTE.vsCMAccess access, ITypeSymbol returnType) { var destination = CodeModelService.GetDestination(containerNode); var newMethodSymbol = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: default, accessibility: CodeModelService.GetAccessibility(access, SymbolKind.Method, destination), modifiers: new DeclarationModifiers(), returnType: returnType, refKind: RefKind.None, explicitInterfaceImplementations: default, name: name, typeParameters: default, parameters: default); var codeGenerationOptions = GetCodeGenerationOptions( access, containerNode.SyntaxTree.Options, options: null); if (destination == CodeGenerationDestination.InterfaceType) { // Generating method with body is allowed when targeting an interface, // so we have to explicitly disable it here. codeGenerationOptions = codeGenerationOptions.With(generateMethodBodies: false); } return CodeGenerationService.CreateMethodDeclaration( newMethodSymbol, destination, options: codeGenerationOptions); } protected SyntaxNode CreatePropertyDeclaration( SyntaxNode containerNode, string name, bool generateGetter, bool generateSetter, EnvDTE.vsCMAccess access, ITypeSymbol type, OptionSet options) { var destination = CodeModelService.GetDestination(containerNode); IMethodSymbol getMethod = null; if (generateGetter) { getMethod = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: default, accessibility: Accessibility.NotApplicable, modifiers: new DeclarationModifiers(), returnType: null, refKind: RefKind.None, explicitInterfaceImplementations: default, name: "get_" + name, typeParameters: default, parameters: default, statements: ImmutableArray.Create(CodeModelService.CreateReturnDefaultValueStatement(type))); } IMethodSymbol setMethod = null; if (generateSetter) { setMethod = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: default, accessibility: Accessibility.NotApplicable, modifiers: new DeclarationModifiers(), returnType: null, refKind: RefKind.None, explicitInterfaceImplementations: default, name: "set_" + name, typeParameters: default, parameters: default); } var newPropertySymbol = CodeGenerationSymbolFactory.CreatePropertySymbol( attributes: default, accessibility: CodeModelService.GetAccessibility(access, SymbolKind.Field, destination), modifiers: new DeclarationModifiers(), type: type, refKind: RefKind.None, explicitInterfaceImplementations: default, name: name, parameters: default, getMethod: getMethod, setMethod: setMethod); return CodeGenerationService.CreatePropertyDeclaration( newPropertySymbol, destination, options: GetCodeGenerationOptions( access, containerNode.SyntaxTree.Options, options)); } protected SyntaxNode CreateNamespaceDeclaration(SyntaxNode containerNode, string name) { var destination = CodeModelService.GetDestination(containerNode); var newNamespaceSymbol = CodeGenerationSymbolFactory.CreateNamespaceSymbol(name); var newNamespace = CodeGenerationService.CreateNamespaceDeclaration( newNamespaceSymbol, destination); return newNamespace; } protected SyntaxNode CreateTypeDeclaration( SyntaxNode containerNode, TypeKind typeKind, string name, EnvDTE.vsCMAccess access, INamedTypeSymbol baseType = null, ImmutableArray<INamedTypeSymbol> implementedInterfaces = default) { var destination = CodeModelService.GetDestination(containerNode); var newTypeSymbol = CodeGenerationSymbolFactory.CreateNamedTypeSymbol( attributes: default, accessibility: CodeModelService.GetAccessibility(access, SymbolKind.NamedType, destination), modifiers: new DeclarationModifiers(), typeKind: typeKind, name: name, typeParameters: default, baseType: baseType, interfaces: implementedInterfaces, specialType: SpecialType.None, members: default); return CodeGenerationService.CreateNamedTypeDeclaration( newTypeSymbol, destination, options: GetCodeGenerationOptions( access, containerNode.SyntaxTree.Options, options: null)); } } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/CompilerUtilities/ImmutableHashMap.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; using Roslyn.Utilities; using Contract = System.Diagnostics.Contracts.Contract; namespace Roslyn.Collections.Immutable { /// <summary> /// An immutable unordered hash map implementation. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(ImmutableHashMap<,>.DebuggerProxy))] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] internal sealed class ImmutableHashMap<TKey, TValue> : IImmutableDictionary<TKey, TValue> where TKey : notnull { private static readonly ImmutableHashMap<TKey, TValue> s_emptySingleton = new(); /// <summary> /// The root node of the tree that stores this map. /// </summary> private readonly Bucket? _root; /// <summary> /// The comparer used to sort keys in this map. /// </summary> private readonly IEqualityComparer<TKey> _keyComparer; /// <summary> /// The comparer used to detect equivalent values in this map. /// </summary> private readonly IEqualityComparer<TValue> _valueComparer; /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashMap&lt;TKey, TValue&gt;"/> class. /// </summary> /// <param name="root">The root.</param> /// <param name="comparer">The comparer.</param> /// <param name="valueComparer">The value comparer.</param> private ImmutableHashMap(Bucket? root, IEqualityComparer<TKey> comparer, IEqualityComparer<TValue> valueComparer) : this(comparer, valueComparer) { RoslynDebug.AssertNotNull(comparer); RoslynDebug.AssertNotNull(valueComparer); _root = root; } /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashMap&lt;TKey, TValue&gt;"/> class. /// </summary> /// <param name="comparer">The comparer.</param> /// <param name="valueComparer">The value comparer.</param> internal ImmutableHashMap(IEqualityComparer<TKey>? comparer = null, IEqualityComparer<TValue>? valueComparer = null) { _keyComparer = comparer ?? EqualityComparer<TKey>.Default; _valueComparer = valueComparer ?? EqualityComparer<TValue>.Default; } /// <summary> /// Gets an empty map with default equality comparers. /// </summary> public static ImmutableHashMap<TKey, TValue> Empty => s_emptySingleton; /// <summary> /// See the <see cref="IImmutableDictionary&lt;TKey, TValue&gt;"/> interface. /// </summary> public ImmutableHashMap<TKey, TValue> Clear() => this.IsEmpty ? this : Empty.WithComparers(_keyComparer, _valueComparer); #region Public methods /// <summary> /// See the <see cref="IImmutableDictionary&lt;TKey, TValue&gt;"/> interface. /// </summary> [Pure] public ImmutableHashMap<TKey, TValue> Add(TKey key, TValue value) { Requires.NotNullAllowStructs(key, "key"); Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null); var vb = new ValueBucket(key, value, _keyComparer.GetHashCode(key)); if (_root == null) { return this.Wrap(vb); } else { return this.Wrap(_root.Add(0, vb, _keyComparer, _valueComparer, false)); } } /// <summary> /// See the <see cref="IImmutableDictionary&lt;TKey, TValue&gt;"/> interface. /// </summary> [Pure] public ImmutableHashMap<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs) { Requires.NotNull(pairs, "pairs"); Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null); return this.AddRange(pairs, overwriteOnCollision: false, avoidToHashMap: false); } /// <summary> /// See the <see cref="IImmutableDictionary&lt;TKey, TValue&gt;"/> interface. /// </summary> [Pure] public ImmutableHashMap<TKey, TValue> SetItem(TKey key, TValue value) { Requires.NotNullAllowStructs(key, "key"); Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null); Contract.Ensures(!Contract.Result<ImmutableHashMap<TKey, TValue>>().IsEmpty); var vb = new ValueBucket(key, value, _keyComparer.GetHashCode(key)); if (_root == null) { return this.Wrap(vb); } else { return this.Wrap(_root.Add(0, vb, _keyComparer, _valueComparer, true)); } } /// <summary> /// Applies a given set of key=value pairs to an immutable dictionary, replacing any conflicting keys in the resulting dictionary. /// </summary> /// <param name="items">The key=value pairs to set on the map. Any keys that conflict with existing keys will overwrite the previous values.</param> /// <returns>An immutable dictionary.</returns> [Pure] public ImmutableHashMap<TKey, TValue> SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items) { Requires.NotNull(items, "items"); Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null); return this.AddRange(items, overwriteOnCollision: true, avoidToHashMap: false); } /// <summary> /// See the <see cref="IImmutableDictionary&lt;TKey, TValue&gt;"/> interface. /// </summary> [Pure] public ImmutableHashMap<TKey, TValue> Remove(TKey key) { Requires.NotNullAllowStructs(key, "key"); Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null); if (_root != null) { return this.Wrap(_root.Remove(_keyComparer.GetHashCode(key), key, _keyComparer)); } return this; } /// <summary> /// See the <see cref="IImmutableDictionary&lt;TKey, TValue&gt;"/> interface. /// </summary> [Pure] public ImmutableHashMap<TKey, TValue> RemoveRange(IEnumerable<TKey> keys) { Requires.NotNull(keys, "keys"); Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null); var map = _root; if (map != null) { foreach (var key in keys) { map = map.Remove(_keyComparer.GetHashCode(key), key, _keyComparer); if (map == null) { break; } } } return this.Wrap(map); } /// <summary> /// Returns a hash map that uses the specified key and value comparers and has the same contents as this map. /// </summary> /// <param name="keyComparer">The key comparer. A value of <c>null</c> results in using the default equality comparer for the type.</param> /// <param name="valueComparer">The value comparer. A value of <c>null</c> results in using the default equality comparer for the type.</param> /// <returns>The hash map with the new comparers.</returns> /// <remarks> /// In the event that a change in the key equality comparer results in a key collision, an exception is thrown. /// </remarks> [Pure] public ImmutableHashMap<TKey, TValue> WithComparers(IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer) { if (keyComparer == null) { keyComparer = EqualityComparer<TKey>.Default; } if (valueComparer == null) { valueComparer = EqualityComparer<TValue>.Default; } if (_keyComparer == keyComparer) { if (_valueComparer == valueComparer) { return this; } else { // When the key comparer is the same but the value comparer is different, we don't need a whole new tree // because the structure of the tree does not depend on the value comparer. // We just need a new root node to store the new value comparer. return new ImmutableHashMap<TKey, TValue>(_root, _keyComparer, valueComparer); } } else { var set = new ImmutableHashMap<TKey, TValue>(keyComparer, valueComparer); set = set.AddRange(this, overwriteOnCollision: false, avoidToHashMap: true); return set; } } /// <summary> /// Returns a hash map that uses the specified key comparer and current value comparer and has the same contents as this map. /// </summary> /// <param name="keyComparer">The key comparer. A value of <c>null</c> results in using the default equality comparer for the type.</param> /// <returns>The hash map with the new comparers.</returns> /// <remarks> /// In the event that a change in the key equality comparer results in a key collision, an exception is thrown. /// </remarks> [Pure] public ImmutableHashMap<TKey, TValue> WithComparers(IEqualityComparer<TKey> keyComparer) => this.WithComparers(keyComparer, _valueComparer); /// <summary> /// Determines whether the ImmutableSortedMap&lt;TKey,TValue&gt; /// contains an element with the specified value. /// </summary> /// <param name="value"> /// The value to locate in the ImmutableSortedMap&lt;TKey,TValue&gt;. /// The value can be null for reference types. /// </param> /// <returns> /// true if the ImmutableSortedMap&lt;TKey,TValue&gt; contains /// an element with the specified value; otherwise, false. /// </returns> [Pure] public bool ContainsValue(TValue value) => this.Values.Contains(value, _valueComparer); #endregion #region IImmutableDictionary<TKey, TValue> Members /// <summary> /// Gets the number of elements in this collection. /// </summary> public int Count { get { return _root != null ? _root.Count : 0; } } /// <summary> /// Gets a value indicating whether this instance is empty. /// </summary> /// <value> /// <c>true</c> if this instance is empty; otherwise, <c>false</c>. /// </value> public bool IsEmpty { get { return this.Count == 0; } } /// <summary> /// Gets the keys in the map. /// </summary> public IEnumerable<TKey> Keys { get { if (_root == null) { yield break; } var stack = new Stack<IEnumerator<Bucket>>(); stack.Push(_root.GetAll().GetEnumerator()); while (stack.Count > 0) { var en = stack.Peek(); if (en.MoveNext()) { if (en.Current is ValueBucket vb) { yield return vb.Key; } else { stack.Push(en.Current.GetAll().GetEnumerator()); } } else { stack.Pop(); } } } } /// <summary> /// Gets the values in the map. /// </summary> public IEnumerable<TValue> Values { #pragma warning disable 618 get { return this.GetValueBuckets().Select(vb => vb.Value); } #pragma warning restore 618 } /// <summary> /// Gets the <typeparamref name="TValue"/> with the specified key. /// </summary> public TValue this[TKey key] { get { if (this.TryGetValue(key, out var value)) { return value; } throw new KeyNotFoundException(); } } /// <summary> /// Determines whether the specified key contains key. /// </summary> /// <param name="key">The key.</param> /// <returns> /// <c>true</c> if the specified key contains key; otherwise, <c>false</c>. /// </returns> public bool ContainsKey(TKey key) { if (_root != null) { var vb = _root.Get(_keyComparer.GetHashCode(key), key, _keyComparer); return vb != null; } return false; } /// <summary> /// Determines whether this map contains the specified key-value pair. /// </summary> /// <param name="keyValuePair">The key value pair.</param> /// <returns> /// <c>true</c> if this map contains the key-value pair; otherwise, <c>false</c>. /// </returns> public bool Contains(KeyValuePair<TKey, TValue> keyValuePair) { if (_root != null) { var vb = _root.Get(_keyComparer.GetHashCode(keyValuePair.Key), keyValuePair.Key, _keyComparer); return vb != null && _valueComparer.Equals(vb.Value, keyValuePair.Value); } return false; } /// <summary> /// See the <see cref="IImmutableDictionary&lt;TKey, TValue&gt;"/> interface. /// </summary> #pragma warning disable CS8767 // Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes). public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) #pragma warning restore CS8767 // Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes). { if (_root != null) { var vb = _root.Get(_keyComparer.GetHashCode(key), key, _keyComparer); if (vb != null) { value = vb.Value; return true; } } value = default; return false; } /// <summary> /// See the <see cref="IImmutableDictionary&lt;TKey, TValue&gt;"/> interface. /// </summary> public bool TryGetKey(TKey equalKey, out TKey actualKey) { if (_root != null) { var vb = _root.Get(_keyComparer.GetHashCode(equalKey), equalKey, _keyComparer); if (vb != null) { actualKey = vb.Key; return true; } } actualKey = equalKey; return false; } #endregion #region IEnumerable<KeyValuePair<TKey, TValue>> Members /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() => this.GetValueBuckets().Select(vb => new KeyValuePair<TKey, TValue>(vb.Key, vb.Value)).GetEnumerator(); #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator(); #endregion /// <summary> /// Returns a <see cref="System.String" /> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String" /> that represents this instance. /// </returns> public override string ToString() { var builder = new StringBuilder("ImmutableHashMap["); var needComma = false; foreach (var kv in this) { builder.Append(kv.Key); builder.Append(":"); builder.Append(kv.Value); if (needComma) { builder.Append(","); } needComma = true; } builder.Append("]"); return builder.ToString(); } /// <summary> /// Exchanges a key for the actual key instance found in this map. /// </summary> /// <param name="key">The key to search for.</param> /// <param name="existingKey">Receives the equal key found in the map.</param> /// <returns>A value indicating whether an equal and existing key was found in the map.</returns> internal bool TryExchangeKey(TKey key, [NotNullWhen(true)] out TKey? existingKey) { var vb = _root != null ? _root.Get(_keyComparer.GetHashCode(key), key, _keyComparer) : null; if (vb != null) { existingKey = vb.Key; return true; } else { existingKey = default; return false; } } /// <summary> /// Attempts to discover an <see cref="ImmutableHashMap&lt;TKey, TValue&gt;"/> instance beneath some enumerable sequence /// if one exists. /// </summary> /// <param name="sequence">The sequence that may have come from an immutable map.</param> /// <param name="other">Receives the concrete <see cref="ImmutableHashMap&lt;TKey, TValue&gt;"/> typed value if one can be found.</param> /// <returns><c>true</c> if the cast was successful; <c>false</c> otherwise.</returns> private static bool TryCastToImmutableMap(IEnumerable<KeyValuePair<TKey, TValue>> sequence, [NotNullWhen(true)] out ImmutableHashMap<TKey, TValue>? other) { other = sequence as ImmutableHashMap<TKey, TValue>; if (other != null) { return true; } return false; } private ImmutableHashMap<TKey, TValue> Wrap(Bucket? root) { if (root == null) { return this.Clear(); } if (_root != root) { return root.Count == 0 ? this.Clear() : new ImmutableHashMap<TKey, TValue>(root, _keyComparer, _valueComparer); } return this; } /// <summary> /// Bulk adds entries to the map. /// </summary> /// <param name="pairs">The entries to add.</param> /// <param name="overwriteOnCollision"><c>true</c> to allow the <paramref name="pairs"/> sequence to include duplicate keys and let the last one win; <c>false</c> to throw on collisions.</param> /// <param name="avoidToHashMap"><c>true</c> when being called from ToHashMap to avoid StackOverflow.</param> [Pure] private ImmutableHashMap<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs, bool overwriteOnCollision, bool avoidToHashMap) { RoslynDebug.AssertNotNull(pairs); Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null); // Some optimizations may apply if we're an empty list. if (this.IsEmpty && !avoidToHashMap) { // If the items being added actually come from an ImmutableHashMap<TKey, TValue> // then there is no value in reconstructing it. if (TryCastToImmutableMap(pairs, out var other)) { return other.WithComparers(_keyComparer, _valueComparer); } } var map = this; foreach (var pair in pairs) { map = overwriteOnCollision ? map.SetItem(pair.Key, pair.Value) : map.Add(pair.Key, pair.Value); } return map; } private IEnumerable<ValueBucket> GetValueBuckets() { if (_root == null) { yield break; } var stack = new Stack<IEnumerator<Bucket>>(); stack.Push(_root.GetAll().GetEnumerator()); while (stack.Count > 0) { var en = stack.Peek(); if (en.MoveNext()) { if (en.Current is ValueBucket vb) { yield return vb; } else { stack.Push(en.Current.GetAll().GetEnumerator()); } } else { stack.Pop(); } } } private abstract class Bucket { internal abstract int Count { get; } internal abstract Bucket Add(int suggestedHashRoll, ValueBucket bucket, IEqualityComparer<TKey> comparer, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue); internal abstract Bucket? Remove(int hash, TKey key, IEqualityComparer<TKey> comparer); internal abstract ValueBucket? Get(int hash, TKey key, IEqualityComparer<TKey> comparer); internal abstract IEnumerable<Bucket> GetAll(); } private abstract class ValueOrListBucket : Bucket { /// <summary> /// The hash for this bucket. /// </summary> internal readonly int Hash; /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashMap&lt;TKey, TValue&gt;.ValueOrListBucket"/> class. /// </summary> /// <param name="hash">The hash.</param> protected ValueOrListBucket(int hash) => this.Hash = hash; } private sealed class ValueBucket : ValueOrListBucket { internal readonly TKey Key; internal readonly TValue Value; /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashMap&lt;TKey, TValue&gt;.ValueBucket"/> class. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="hashcode">The hashcode.</param> internal ValueBucket(TKey key, TValue value, int hashcode) : base(hashcode) { this.Key = key; this.Value = value; } internal override int Count => 1; internal override Bucket Add(int suggestedHashRoll, ValueBucket bucket, IEqualityComparer<TKey> comparer, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue) { if (this.Hash == bucket.Hash) { if (comparer.Equals(this.Key, bucket.Key)) { // Overwrite of same key. If the value is the same as well, don't switch out the bucket. if (valueComparer.Equals(this.Value, bucket.Value)) { return this; } else { if (overwriteExistingValue) { return bucket; } else { throw new ArgumentException(Strings.DuplicateKey); } } } else { // two of the same hash will never be happy in a hash bucket return new ListBucket(new ValueBucket[] { this, bucket }); } } else { return new HashBucket(suggestedHashRoll, this, bucket); } } internal override Bucket? Remove(int hash, TKey key, IEqualityComparer<TKey> comparer) { if (this.Hash == hash && comparer.Equals(this.Key, key)) { return null; } return this; } internal override ValueBucket? Get(int hash, TKey key, IEqualityComparer<TKey> comparer) { if (this.Hash == hash && comparer.Equals(this.Key, key)) { return this; } return null; } internal override IEnumerable<Bucket> GetAll() => SpecializedCollections.SingletonEnumerable(this); } private sealed class ListBucket : ValueOrListBucket { private readonly ValueBucket[] _buckets; /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashMap&lt;TKey, TValue&gt;.ListBucket"/> class. /// </summary> /// <param name="buckets">The buckets.</param> internal ListBucket(ValueBucket[] buckets) : base(buckets[0].Hash) { RoslynDebug.AssertNotNull(buckets); Debug.Assert(buckets.Length >= 2); _buckets = buckets; } internal override int Count => _buckets.Length; internal override Bucket Add(int suggestedHashRoll, ValueBucket bucket, IEqualityComparer<TKey> comparer, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue) { if (this.Hash == bucket.Hash) { var pos = this.Find(bucket.Key, comparer); if (pos >= 0) { // If the value hasn't changed for this key, return the original bucket. if (valueComparer.Equals(bucket.Value, _buckets[pos].Value)) { return this; } else { if (overwriteExistingValue) { return new ListBucket(_buckets.ReplaceAt(pos, bucket)); } else { throw new ArgumentException(Strings.DuplicateKey); } } } else { return new ListBucket(_buckets.InsertAt(_buckets.Length, bucket)); } } else { return new HashBucket(suggestedHashRoll, this, bucket); } } internal override Bucket? Remove(int hash, TKey key, IEqualityComparer<TKey> comparer) { if (this.Hash == hash) { var pos = this.Find(key, comparer); if (pos >= 0) { if (_buckets.Length == 1) { return null; } else if (_buckets.Length == 2) { return pos == 0 ? _buckets[1] : _buckets[0]; } else { return new ListBucket(_buckets.RemoveAt(pos)); } } } return this; } internal override ValueBucket? Get(int hash, TKey key, IEqualityComparer<TKey> comparer) { if (this.Hash == hash) { var pos = this.Find(key, comparer); if (pos >= 0) { return _buckets[pos]; } } return null; } private int Find(TKey key, IEqualityComparer<TKey> comparer) { for (var i = 0; i < _buckets.Length; i++) { if (comparer.Equals(key, _buckets[i].Key)) { return i; } } return -1; } internal override IEnumerable<Bucket> GetAll() => _buckets; } private sealed class HashBucket : Bucket { private readonly int _hashRoll; private readonly uint _used; private readonly Bucket[] _buckets; private readonly int _count; /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashMap&lt;TKey, TValue&gt;.HashBucket"/> class. /// </summary> /// <param name="hashRoll">The hash roll.</param> /// <param name="used">The used.</param> /// <param name="buckets">The buckets.</param> /// <param name="count">The count.</param> private HashBucket(int hashRoll, uint used, Bucket[] buckets, int count) { RoslynDebug.AssertNotNull(buckets); Debug.Assert(buckets.Length == CountBits(used)); _hashRoll = hashRoll & 31; _used = used; _buckets = buckets; _count = count; } /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashMap&lt;TKey, TValue&gt;.HashBucket"/> class. /// </summary> /// <param name="suggestedHashRoll">The suggested hash roll.</param> /// <param name="bucket1">The bucket1.</param> /// <param name="bucket2">The bucket2.</param> internal HashBucket(int suggestedHashRoll, ValueOrListBucket bucket1, ValueOrListBucket bucket2) { RoslynDebug.AssertNotNull(bucket1); RoslynDebug.AssertNotNull(bucket2); Debug.Assert(bucket1.Hash != bucket2.Hash); // find next hashRoll that causes these two to be slotted in different buckets var h1 = bucket1.Hash; var h2 = bucket2.Hash; int s1; int s2; for (var i = 0; i < 32; i++) { _hashRoll = (suggestedHashRoll + i) & 31; s1 = this.ComputeLogicalSlot(h1); s2 = this.ComputeLogicalSlot(h2); if (s1 != s2) { _count = 2; _used = (1u << s1) | (1u << s2); _buckets = new Bucket[2]; _buckets[this.ComputePhysicalSlot(s1)] = bucket1; _buckets[this.ComputePhysicalSlot(s2)] = bucket2; return; } } throw new InvalidOperationException(); } internal override int Count => _count; internal override Bucket Add(int suggestedHashRoll, ValueBucket bucket, IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue) { var logicalSlot = ComputeLogicalSlot(bucket.Hash); if (IsInUse(logicalSlot)) { // if this slot is in use, then add the new item to the one in this slot var physicalSlot = ComputePhysicalSlot(logicalSlot); var existing = _buckets[physicalSlot]; // suggest hash roll that will cause any nested hash bucket to use entirely new bits for picking logical slot // note: we ignore passed in suggestion, and base new suggestion off current hash roll. var added = existing.Add(_hashRoll + 5, bucket, keyComparer, valueComparer, overwriteExistingValue); if (added != existing) { var newBuckets = _buckets.ReplaceAt(physicalSlot, added); return new HashBucket(_hashRoll, _used, newBuckets, _count - existing.Count + added.Count); } else { return this; } } else { var physicalSlot = ComputePhysicalSlot(logicalSlot); var newBuckets = _buckets.InsertAt(physicalSlot, bucket); var newUsed = InsertBit(logicalSlot, _used); return new HashBucket(_hashRoll, newUsed, newBuckets, _count + bucket.Count); } } internal override Bucket? Remove(int hash, TKey key, IEqualityComparer<TKey> comparer) { var logicalSlot = ComputeLogicalSlot(hash); if (IsInUse(logicalSlot)) { var physicalSlot = ComputePhysicalSlot(logicalSlot); var existing = _buckets[physicalSlot]; var result = existing.Remove(hash, key, comparer); if (result == null) { if (_buckets.Length == 1) { return null; } else if (_buckets.Length == 2) { return physicalSlot == 0 ? _buckets[1] : _buckets[0]; } else { return new HashBucket(_hashRoll, RemoveBit(logicalSlot, _used), _buckets.RemoveAt(physicalSlot), _count - existing.Count); } } else if (_buckets[physicalSlot] != result) { return new HashBucket(_hashRoll, _used, _buckets.ReplaceAt(physicalSlot, result), _count - existing.Count + result.Count); } } return this; } internal override ValueBucket? Get(int hash, TKey key, IEqualityComparer<TKey> comparer) { var logicalSlot = ComputeLogicalSlot(hash); if (IsInUse(logicalSlot)) { var physicalSlot = ComputePhysicalSlot(logicalSlot); return _buckets[physicalSlot].Get(hash, key, comparer); } return null; } internal override IEnumerable<Bucket> GetAll() => _buckets; private bool IsInUse(int logicalSlot) => ((1 << logicalSlot) & _used) != 0; private int ComputeLogicalSlot(int hc) { var uc = unchecked((uint)hc); var rotated = RotateRight(uc, _hashRoll); return unchecked((int)(rotated & 31)); } [Pure] private static uint RotateRight(uint v, int n) { Debug.Assert(n >= 0 && n < 32); if (n == 0) { return v; } return v >> n | (v << (32 - n)); } private int ComputePhysicalSlot(int logicalSlot) { Debug.Assert(logicalSlot >= 0 && logicalSlot < 32); Contract.Ensures(Contract.Result<int>() >= 0); if (_buckets.Length == 32) { return logicalSlot; } if (logicalSlot == 0) { return 0; } var mask = uint.MaxValue >> (32 - logicalSlot); // only count the bits up to the logical slot # return CountBits(_used & mask); } [Pure] private static int CountBits(uint v) { unchecked { v -= ((v >> 1) & 0x55555555u); v = (v & 0x33333333u) + ((v >> 2) & 0x33333333u); return (int)((v + (v >> 4) & 0xF0F0F0Fu) * 0x1010101u) >> 24; } } [Pure] private static uint InsertBit(int position, uint bits) { Debug.Assert(0 == (bits & (1u << position))); return bits | (1u << position); } [Pure] private static uint RemoveBit(int position, uint bits) { Debug.Assert(0 != (bits & (1u << position))); return bits & ~(1u << position); } } #region IImmutableDictionary<TKey,TValue> Members IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Clear() => this.Clear(); IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Add(TKey key, TValue value) => this.Add(key, value); IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.SetItem(TKey key, TValue value) => this.SetItem(key, value); IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items) => this.SetItems(items); IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs) => this.AddRange(pairs); IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.RemoveRange(IEnumerable<TKey> keys) => this.RemoveRange(keys); IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Remove(TKey key) => this.Remove(key); #endregion /// <summary> /// A simple view of the immutable collection that the debugger can show to the developer. /// </summary> private class DebuggerProxy { /// <summary> /// The collection to be enumerated. /// </summary> private readonly ImmutableHashMap<TKey, TValue> _map; /// <summary> /// The simple view of the collection. /// </summary> private KeyValuePair<TKey, TValue>[]? _contents; /// <summary> /// Initializes a new instance of the <see cref="DebuggerProxy"/> class. /// </summary> /// <param name="map">The collection to display in the debugger</param> public DebuggerProxy(ImmutableHashMap<TKey, TValue> map) { Requires.NotNull(map, "map"); _map = map; } /// <summary> /// Gets a simple debugger-viewable collection. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public KeyValuePair<TKey, TValue>[] Contents { get { if (_contents == null) { _contents = _map.ToArray(); } return _contents; } } } private static class Requires { [DebuggerStepThrough] public static T NotNullAllowStructs<T>(T value, string parameterName) { if (value == null) { throw new ArgumentNullException(parameterName); } return value; } [DebuggerStepThrough] public static T NotNull<T>(T value, string parameterName) where T : class { if (value == null) { throw new ArgumentNullException(parameterName); } return value; } [DebuggerStepThrough] public static Exception FailRange(string parameterName, string? message = null) { if (string.IsNullOrEmpty(message)) { throw new ArgumentOutOfRangeException(parameterName); } throw new ArgumentOutOfRangeException(parameterName, message); } [DebuggerStepThrough] public static void Range(bool condition, string parameterName, string? message = null) { if (!condition) { Requires.FailRange(parameterName, message); } } } private static class Strings { public static string DuplicateKey => CompilerExtensionsResources.An_element_with_the_same_key_but_a_different_value_already_exists; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; using Roslyn.Utilities; using Contract = System.Diagnostics.Contracts.Contract; namespace Roslyn.Collections.Immutable { /// <summary> /// An immutable unordered hash map implementation. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(ImmutableHashMap<,>.DebuggerProxy))] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] internal sealed class ImmutableHashMap<TKey, TValue> : IImmutableDictionary<TKey, TValue> where TKey : notnull { private static readonly ImmutableHashMap<TKey, TValue> s_emptySingleton = new(); /// <summary> /// The root node of the tree that stores this map. /// </summary> private readonly Bucket? _root; /// <summary> /// The comparer used to sort keys in this map. /// </summary> private readonly IEqualityComparer<TKey> _keyComparer; /// <summary> /// The comparer used to detect equivalent values in this map. /// </summary> private readonly IEqualityComparer<TValue> _valueComparer; /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashMap&lt;TKey, TValue&gt;"/> class. /// </summary> /// <param name="root">The root.</param> /// <param name="comparer">The comparer.</param> /// <param name="valueComparer">The value comparer.</param> private ImmutableHashMap(Bucket? root, IEqualityComparer<TKey> comparer, IEqualityComparer<TValue> valueComparer) : this(comparer, valueComparer) { RoslynDebug.AssertNotNull(comparer); RoslynDebug.AssertNotNull(valueComparer); _root = root; } /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashMap&lt;TKey, TValue&gt;"/> class. /// </summary> /// <param name="comparer">The comparer.</param> /// <param name="valueComparer">The value comparer.</param> internal ImmutableHashMap(IEqualityComparer<TKey>? comparer = null, IEqualityComparer<TValue>? valueComparer = null) { _keyComparer = comparer ?? EqualityComparer<TKey>.Default; _valueComparer = valueComparer ?? EqualityComparer<TValue>.Default; } /// <summary> /// Gets an empty map with default equality comparers. /// </summary> public static ImmutableHashMap<TKey, TValue> Empty => s_emptySingleton; /// <summary> /// See the <see cref="IImmutableDictionary&lt;TKey, TValue&gt;"/> interface. /// </summary> public ImmutableHashMap<TKey, TValue> Clear() => this.IsEmpty ? this : Empty.WithComparers(_keyComparer, _valueComparer); #region Public methods /// <summary> /// See the <see cref="IImmutableDictionary&lt;TKey, TValue&gt;"/> interface. /// </summary> [Pure] public ImmutableHashMap<TKey, TValue> Add(TKey key, TValue value) { Requires.NotNullAllowStructs(key, "key"); Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null); var vb = new ValueBucket(key, value, _keyComparer.GetHashCode(key)); if (_root == null) { return this.Wrap(vb); } else { return this.Wrap(_root.Add(0, vb, _keyComparer, _valueComparer, false)); } } /// <summary> /// See the <see cref="IImmutableDictionary&lt;TKey, TValue&gt;"/> interface. /// </summary> [Pure] public ImmutableHashMap<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs) { Requires.NotNull(pairs, "pairs"); Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null); return this.AddRange(pairs, overwriteOnCollision: false, avoidToHashMap: false); } /// <summary> /// See the <see cref="IImmutableDictionary&lt;TKey, TValue&gt;"/> interface. /// </summary> [Pure] public ImmutableHashMap<TKey, TValue> SetItem(TKey key, TValue value) { Requires.NotNullAllowStructs(key, "key"); Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null); Contract.Ensures(!Contract.Result<ImmutableHashMap<TKey, TValue>>().IsEmpty); var vb = new ValueBucket(key, value, _keyComparer.GetHashCode(key)); if (_root == null) { return this.Wrap(vb); } else { return this.Wrap(_root.Add(0, vb, _keyComparer, _valueComparer, true)); } } /// <summary> /// Applies a given set of key=value pairs to an immutable dictionary, replacing any conflicting keys in the resulting dictionary. /// </summary> /// <param name="items">The key=value pairs to set on the map. Any keys that conflict with existing keys will overwrite the previous values.</param> /// <returns>An immutable dictionary.</returns> [Pure] public ImmutableHashMap<TKey, TValue> SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items) { Requires.NotNull(items, "items"); Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null); return this.AddRange(items, overwriteOnCollision: true, avoidToHashMap: false); } /// <summary> /// See the <see cref="IImmutableDictionary&lt;TKey, TValue&gt;"/> interface. /// </summary> [Pure] public ImmutableHashMap<TKey, TValue> Remove(TKey key) { Requires.NotNullAllowStructs(key, "key"); Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null); if (_root != null) { return this.Wrap(_root.Remove(_keyComparer.GetHashCode(key), key, _keyComparer)); } return this; } /// <summary> /// See the <see cref="IImmutableDictionary&lt;TKey, TValue&gt;"/> interface. /// </summary> [Pure] public ImmutableHashMap<TKey, TValue> RemoveRange(IEnumerable<TKey> keys) { Requires.NotNull(keys, "keys"); Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null); var map = _root; if (map != null) { foreach (var key in keys) { map = map.Remove(_keyComparer.GetHashCode(key), key, _keyComparer); if (map == null) { break; } } } return this.Wrap(map); } /// <summary> /// Returns a hash map that uses the specified key and value comparers and has the same contents as this map. /// </summary> /// <param name="keyComparer">The key comparer. A value of <c>null</c> results in using the default equality comparer for the type.</param> /// <param name="valueComparer">The value comparer. A value of <c>null</c> results in using the default equality comparer for the type.</param> /// <returns>The hash map with the new comparers.</returns> /// <remarks> /// In the event that a change in the key equality comparer results in a key collision, an exception is thrown. /// </remarks> [Pure] public ImmutableHashMap<TKey, TValue> WithComparers(IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer) { if (keyComparer == null) { keyComparer = EqualityComparer<TKey>.Default; } if (valueComparer == null) { valueComparer = EqualityComparer<TValue>.Default; } if (_keyComparer == keyComparer) { if (_valueComparer == valueComparer) { return this; } else { // When the key comparer is the same but the value comparer is different, we don't need a whole new tree // because the structure of the tree does not depend on the value comparer. // We just need a new root node to store the new value comparer. return new ImmutableHashMap<TKey, TValue>(_root, _keyComparer, valueComparer); } } else { var set = new ImmutableHashMap<TKey, TValue>(keyComparer, valueComparer); set = set.AddRange(this, overwriteOnCollision: false, avoidToHashMap: true); return set; } } /// <summary> /// Returns a hash map that uses the specified key comparer and current value comparer and has the same contents as this map. /// </summary> /// <param name="keyComparer">The key comparer. A value of <c>null</c> results in using the default equality comparer for the type.</param> /// <returns>The hash map with the new comparers.</returns> /// <remarks> /// In the event that a change in the key equality comparer results in a key collision, an exception is thrown. /// </remarks> [Pure] public ImmutableHashMap<TKey, TValue> WithComparers(IEqualityComparer<TKey> keyComparer) => this.WithComparers(keyComparer, _valueComparer); /// <summary> /// Determines whether the ImmutableSortedMap&lt;TKey,TValue&gt; /// contains an element with the specified value. /// </summary> /// <param name="value"> /// The value to locate in the ImmutableSortedMap&lt;TKey,TValue&gt;. /// The value can be null for reference types. /// </param> /// <returns> /// true if the ImmutableSortedMap&lt;TKey,TValue&gt; contains /// an element with the specified value; otherwise, false. /// </returns> [Pure] public bool ContainsValue(TValue value) => this.Values.Contains(value, _valueComparer); #endregion #region IImmutableDictionary<TKey, TValue> Members /// <summary> /// Gets the number of elements in this collection. /// </summary> public int Count { get { return _root != null ? _root.Count : 0; } } /// <summary> /// Gets a value indicating whether this instance is empty. /// </summary> /// <value> /// <c>true</c> if this instance is empty; otherwise, <c>false</c>. /// </value> public bool IsEmpty { get { return this.Count == 0; } } /// <summary> /// Gets the keys in the map. /// </summary> public IEnumerable<TKey> Keys { get { if (_root == null) { yield break; } var stack = new Stack<IEnumerator<Bucket>>(); stack.Push(_root.GetAll().GetEnumerator()); while (stack.Count > 0) { var en = stack.Peek(); if (en.MoveNext()) { if (en.Current is ValueBucket vb) { yield return vb.Key; } else { stack.Push(en.Current.GetAll().GetEnumerator()); } } else { stack.Pop(); } } } } /// <summary> /// Gets the values in the map. /// </summary> public IEnumerable<TValue> Values { #pragma warning disable 618 get { return this.GetValueBuckets().Select(vb => vb.Value); } #pragma warning restore 618 } /// <summary> /// Gets the <typeparamref name="TValue"/> with the specified key. /// </summary> public TValue this[TKey key] { get { if (this.TryGetValue(key, out var value)) { return value; } throw new KeyNotFoundException(); } } /// <summary> /// Determines whether the specified key contains key. /// </summary> /// <param name="key">The key.</param> /// <returns> /// <c>true</c> if the specified key contains key; otherwise, <c>false</c>. /// </returns> public bool ContainsKey(TKey key) { if (_root != null) { var vb = _root.Get(_keyComparer.GetHashCode(key), key, _keyComparer); return vb != null; } return false; } /// <summary> /// Determines whether this map contains the specified key-value pair. /// </summary> /// <param name="keyValuePair">The key value pair.</param> /// <returns> /// <c>true</c> if this map contains the key-value pair; otherwise, <c>false</c>. /// </returns> public bool Contains(KeyValuePair<TKey, TValue> keyValuePair) { if (_root != null) { var vb = _root.Get(_keyComparer.GetHashCode(keyValuePair.Key), keyValuePair.Key, _keyComparer); return vb != null && _valueComparer.Equals(vb.Value, keyValuePair.Value); } return false; } /// <summary> /// See the <see cref="IImmutableDictionary&lt;TKey, TValue&gt;"/> interface. /// </summary> #pragma warning disable CS8767 // Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes). public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) #pragma warning restore CS8767 // Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes). { if (_root != null) { var vb = _root.Get(_keyComparer.GetHashCode(key), key, _keyComparer); if (vb != null) { value = vb.Value; return true; } } value = default; return false; } /// <summary> /// See the <see cref="IImmutableDictionary&lt;TKey, TValue&gt;"/> interface. /// </summary> public bool TryGetKey(TKey equalKey, out TKey actualKey) { if (_root != null) { var vb = _root.Get(_keyComparer.GetHashCode(equalKey), equalKey, _keyComparer); if (vb != null) { actualKey = vb.Key; return true; } } actualKey = equalKey; return false; } #endregion #region IEnumerable<KeyValuePair<TKey, TValue>> Members /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() => this.GetValueBuckets().Select(vb => new KeyValuePair<TKey, TValue>(vb.Key, vb.Value)).GetEnumerator(); #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator(); #endregion /// <summary> /// Returns a <see cref="System.String" /> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String" /> that represents this instance. /// </returns> public override string ToString() { var builder = new StringBuilder("ImmutableHashMap["); var needComma = false; foreach (var kv in this) { builder.Append(kv.Key); builder.Append(":"); builder.Append(kv.Value); if (needComma) { builder.Append(","); } needComma = true; } builder.Append("]"); return builder.ToString(); } /// <summary> /// Exchanges a key for the actual key instance found in this map. /// </summary> /// <param name="key">The key to search for.</param> /// <param name="existingKey">Receives the equal key found in the map.</param> /// <returns>A value indicating whether an equal and existing key was found in the map.</returns> internal bool TryExchangeKey(TKey key, [NotNullWhen(true)] out TKey? existingKey) { var vb = _root != null ? _root.Get(_keyComparer.GetHashCode(key), key, _keyComparer) : null; if (vb != null) { existingKey = vb.Key; return true; } else { existingKey = default; return false; } } /// <summary> /// Attempts to discover an <see cref="ImmutableHashMap&lt;TKey, TValue&gt;"/> instance beneath some enumerable sequence /// if one exists. /// </summary> /// <param name="sequence">The sequence that may have come from an immutable map.</param> /// <param name="other">Receives the concrete <see cref="ImmutableHashMap&lt;TKey, TValue&gt;"/> typed value if one can be found.</param> /// <returns><c>true</c> if the cast was successful; <c>false</c> otherwise.</returns> private static bool TryCastToImmutableMap(IEnumerable<KeyValuePair<TKey, TValue>> sequence, [NotNullWhen(true)] out ImmutableHashMap<TKey, TValue>? other) { other = sequence as ImmutableHashMap<TKey, TValue>; if (other != null) { return true; } return false; } private ImmutableHashMap<TKey, TValue> Wrap(Bucket? root) { if (root == null) { return this.Clear(); } if (_root != root) { return root.Count == 0 ? this.Clear() : new ImmutableHashMap<TKey, TValue>(root, _keyComparer, _valueComparer); } return this; } /// <summary> /// Bulk adds entries to the map. /// </summary> /// <param name="pairs">The entries to add.</param> /// <param name="overwriteOnCollision"><c>true</c> to allow the <paramref name="pairs"/> sequence to include duplicate keys and let the last one win; <c>false</c> to throw on collisions.</param> /// <param name="avoidToHashMap"><c>true</c> when being called from ToHashMap to avoid StackOverflow.</param> [Pure] private ImmutableHashMap<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs, bool overwriteOnCollision, bool avoidToHashMap) { RoslynDebug.AssertNotNull(pairs); Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null); // Some optimizations may apply if we're an empty list. if (this.IsEmpty && !avoidToHashMap) { // If the items being added actually come from an ImmutableHashMap<TKey, TValue> // then there is no value in reconstructing it. if (TryCastToImmutableMap(pairs, out var other)) { return other.WithComparers(_keyComparer, _valueComparer); } } var map = this; foreach (var pair in pairs) { map = overwriteOnCollision ? map.SetItem(pair.Key, pair.Value) : map.Add(pair.Key, pair.Value); } return map; } private IEnumerable<ValueBucket> GetValueBuckets() { if (_root == null) { yield break; } var stack = new Stack<IEnumerator<Bucket>>(); stack.Push(_root.GetAll().GetEnumerator()); while (stack.Count > 0) { var en = stack.Peek(); if (en.MoveNext()) { if (en.Current is ValueBucket vb) { yield return vb; } else { stack.Push(en.Current.GetAll().GetEnumerator()); } } else { stack.Pop(); } } } private abstract class Bucket { internal abstract int Count { get; } internal abstract Bucket Add(int suggestedHashRoll, ValueBucket bucket, IEqualityComparer<TKey> comparer, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue); internal abstract Bucket? Remove(int hash, TKey key, IEqualityComparer<TKey> comparer); internal abstract ValueBucket? Get(int hash, TKey key, IEqualityComparer<TKey> comparer); internal abstract IEnumerable<Bucket> GetAll(); } private abstract class ValueOrListBucket : Bucket { /// <summary> /// The hash for this bucket. /// </summary> internal readonly int Hash; /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashMap&lt;TKey, TValue&gt;.ValueOrListBucket"/> class. /// </summary> /// <param name="hash">The hash.</param> protected ValueOrListBucket(int hash) => this.Hash = hash; } private sealed class ValueBucket : ValueOrListBucket { internal readonly TKey Key; internal readonly TValue Value; /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashMap&lt;TKey, TValue&gt;.ValueBucket"/> class. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="hashcode">The hashcode.</param> internal ValueBucket(TKey key, TValue value, int hashcode) : base(hashcode) { this.Key = key; this.Value = value; } internal override int Count => 1; internal override Bucket Add(int suggestedHashRoll, ValueBucket bucket, IEqualityComparer<TKey> comparer, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue) { if (this.Hash == bucket.Hash) { if (comparer.Equals(this.Key, bucket.Key)) { // Overwrite of same key. If the value is the same as well, don't switch out the bucket. if (valueComparer.Equals(this.Value, bucket.Value)) { return this; } else { if (overwriteExistingValue) { return bucket; } else { throw new ArgumentException(Strings.DuplicateKey); } } } else { // two of the same hash will never be happy in a hash bucket return new ListBucket(new ValueBucket[] { this, bucket }); } } else { return new HashBucket(suggestedHashRoll, this, bucket); } } internal override Bucket? Remove(int hash, TKey key, IEqualityComparer<TKey> comparer) { if (this.Hash == hash && comparer.Equals(this.Key, key)) { return null; } return this; } internal override ValueBucket? Get(int hash, TKey key, IEqualityComparer<TKey> comparer) { if (this.Hash == hash && comparer.Equals(this.Key, key)) { return this; } return null; } internal override IEnumerable<Bucket> GetAll() => SpecializedCollections.SingletonEnumerable(this); } private sealed class ListBucket : ValueOrListBucket { private readonly ValueBucket[] _buckets; /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashMap&lt;TKey, TValue&gt;.ListBucket"/> class. /// </summary> /// <param name="buckets">The buckets.</param> internal ListBucket(ValueBucket[] buckets) : base(buckets[0].Hash) { RoslynDebug.AssertNotNull(buckets); Debug.Assert(buckets.Length >= 2); _buckets = buckets; } internal override int Count => _buckets.Length; internal override Bucket Add(int suggestedHashRoll, ValueBucket bucket, IEqualityComparer<TKey> comparer, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue) { if (this.Hash == bucket.Hash) { var pos = this.Find(bucket.Key, comparer); if (pos >= 0) { // If the value hasn't changed for this key, return the original bucket. if (valueComparer.Equals(bucket.Value, _buckets[pos].Value)) { return this; } else { if (overwriteExistingValue) { return new ListBucket(_buckets.ReplaceAt(pos, bucket)); } else { throw new ArgumentException(Strings.DuplicateKey); } } } else { return new ListBucket(_buckets.InsertAt(_buckets.Length, bucket)); } } else { return new HashBucket(suggestedHashRoll, this, bucket); } } internal override Bucket? Remove(int hash, TKey key, IEqualityComparer<TKey> comparer) { if (this.Hash == hash) { var pos = this.Find(key, comparer); if (pos >= 0) { if (_buckets.Length == 1) { return null; } else if (_buckets.Length == 2) { return pos == 0 ? _buckets[1] : _buckets[0]; } else { return new ListBucket(_buckets.RemoveAt(pos)); } } } return this; } internal override ValueBucket? Get(int hash, TKey key, IEqualityComparer<TKey> comparer) { if (this.Hash == hash) { var pos = this.Find(key, comparer); if (pos >= 0) { return _buckets[pos]; } } return null; } private int Find(TKey key, IEqualityComparer<TKey> comparer) { for (var i = 0; i < _buckets.Length; i++) { if (comparer.Equals(key, _buckets[i].Key)) { return i; } } return -1; } internal override IEnumerable<Bucket> GetAll() => _buckets; } private sealed class HashBucket : Bucket { private readonly int _hashRoll; private readonly uint _used; private readonly Bucket[] _buckets; private readonly int _count; /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashMap&lt;TKey, TValue&gt;.HashBucket"/> class. /// </summary> /// <param name="hashRoll">The hash roll.</param> /// <param name="used">The used.</param> /// <param name="buckets">The buckets.</param> /// <param name="count">The count.</param> private HashBucket(int hashRoll, uint used, Bucket[] buckets, int count) { RoslynDebug.AssertNotNull(buckets); Debug.Assert(buckets.Length == CountBits(used)); _hashRoll = hashRoll & 31; _used = used; _buckets = buckets; _count = count; } /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashMap&lt;TKey, TValue&gt;.HashBucket"/> class. /// </summary> /// <param name="suggestedHashRoll">The suggested hash roll.</param> /// <param name="bucket1">The bucket1.</param> /// <param name="bucket2">The bucket2.</param> internal HashBucket(int suggestedHashRoll, ValueOrListBucket bucket1, ValueOrListBucket bucket2) { RoslynDebug.AssertNotNull(bucket1); RoslynDebug.AssertNotNull(bucket2); Debug.Assert(bucket1.Hash != bucket2.Hash); // find next hashRoll that causes these two to be slotted in different buckets var h1 = bucket1.Hash; var h2 = bucket2.Hash; int s1; int s2; for (var i = 0; i < 32; i++) { _hashRoll = (suggestedHashRoll + i) & 31; s1 = this.ComputeLogicalSlot(h1); s2 = this.ComputeLogicalSlot(h2); if (s1 != s2) { _count = 2; _used = (1u << s1) | (1u << s2); _buckets = new Bucket[2]; _buckets[this.ComputePhysicalSlot(s1)] = bucket1; _buckets[this.ComputePhysicalSlot(s2)] = bucket2; return; } } throw new InvalidOperationException(); } internal override int Count => _count; internal override Bucket Add(int suggestedHashRoll, ValueBucket bucket, IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue) { var logicalSlot = ComputeLogicalSlot(bucket.Hash); if (IsInUse(logicalSlot)) { // if this slot is in use, then add the new item to the one in this slot var physicalSlot = ComputePhysicalSlot(logicalSlot); var existing = _buckets[physicalSlot]; // suggest hash roll that will cause any nested hash bucket to use entirely new bits for picking logical slot // note: we ignore passed in suggestion, and base new suggestion off current hash roll. var added = existing.Add(_hashRoll + 5, bucket, keyComparer, valueComparer, overwriteExistingValue); if (added != existing) { var newBuckets = _buckets.ReplaceAt(physicalSlot, added); return new HashBucket(_hashRoll, _used, newBuckets, _count - existing.Count + added.Count); } else { return this; } } else { var physicalSlot = ComputePhysicalSlot(logicalSlot); var newBuckets = _buckets.InsertAt(physicalSlot, bucket); var newUsed = InsertBit(logicalSlot, _used); return new HashBucket(_hashRoll, newUsed, newBuckets, _count + bucket.Count); } } internal override Bucket? Remove(int hash, TKey key, IEqualityComparer<TKey> comparer) { var logicalSlot = ComputeLogicalSlot(hash); if (IsInUse(logicalSlot)) { var physicalSlot = ComputePhysicalSlot(logicalSlot); var existing = _buckets[physicalSlot]; var result = existing.Remove(hash, key, comparer); if (result == null) { if (_buckets.Length == 1) { return null; } else if (_buckets.Length == 2) { return physicalSlot == 0 ? _buckets[1] : _buckets[0]; } else { return new HashBucket(_hashRoll, RemoveBit(logicalSlot, _used), _buckets.RemoveAt(physicalSlot), _count - existing.Count); } } else if (_buckets[physicalSlot] != result) { return new HashBucket(_hashRoll, _used, _buckets.ReplaceAt(physicalSlot, result), _count - existing.Count + result.Count); } } return this; } internal override ValueBucket? Get(int hash, TKey key, IEqualityComparer<TKey> comparer) { var logicalSlot = ComputeLogicalSlot(hash); if (IsInUse(logicalSlot)) { var physicalSlot = ComputePhysicalSlot(logicalSlot); return _buckets[physicalSlot].Get(hash, key, comparer); } return null; } internal override IEnumerable<Bucket> GetAll() => _buckets; private bool IsInUse(int logicalSlot) => ((1 << logicalSlot) & _used) != 0; private int ComputeLogicalSlot(int hc) { var uc = unchecked((uint)hc); var rotated = RotateRight(uc, _hashRoll); return unchecked((int)(rotated & 31)); } [Pure] private static uint RotateRight(uint v, int n) { Debug.Assert(n >= 0 && n < 32); if (n == 0) { return v; } return v >> n | (v << (32 - n)); } private int ComputePhysicalSlot(int logicalSlot) { Debug.Assert(logicalSlot >= 0 && logicalSlot < 32); Contract.Ensures(Contract.Result<int>() >= 0); if (_buckets.Length == 32) { return logicalSlot; } if (logicalSlot == 0) { return 0; } var mask = uint.MaxValue >> (32 - logicalSlot); // only count the bits up to the logical slot # return CountBits(_used & mask); } [Pure] private static int CountBits(uint v) { unchecked { v -= ((v >> 1) & 0x55555555u); v = (v & 0x33333333u) + ((v >> 2) & 0x33333333u); return (int)((v + (v >> 4) & 0xF0F0F0Fu) * 0x1010101u) >> 24; } } [Pure] private static uint InsertBit(int position, uint bits) { Debug.Assert(0 == (bits & (1u << position))); return bits | (1u << position); } [Pure] private static uint RemoveBit(int position, uint bits) { Debug.Assert(0 != (bits & (1u << position))); return bits & ~(1u << position); } } #region IImmutableDictionary<TKey,TValue> Members IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Clear() => this.Clear(); IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Add(TKey key, TValue value) => this.Add(key, value); IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.SetItem(TKey key, TValue value) => this.SetItem(key, value); IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items) => this.SetItems(items); IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs) => this.AddRange(pairs); IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.RemoveRange(IEnumerable<TKey> keys) => this.RemoveRange(keys); IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Remove(TKey key) => this.Remove(key); #endregion /// <summary> /// A simple view of the immutable collection that the debugger can show to the developer. /// </summary> private class DebuggerProxy { /// <summary> /// The collection to be enumerated. /// </summary> private readonly ImmutableHashMap<TKey, TValue> _map; /// <summary> /// The simple view of the collection. /// </summary> private KeyValuePair<TKey, TValue>[]? _contents; /// <summary> /// Initializes a new instance of the <see cref="DebuggerProxy"/> class. /// </summary> /// <param name="map">The collection to display in the debugger</param> public DebuggerProxy(ImmutableHashMap<TKey, TValue> map) { Requires.NotNull(map, "map"); _map = map; } /// <summary> /// Gets a simple debugger-viewable collection. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public KeyValuePair<TKey, TValue>[] Contents { get { if (_contents == null) { _contents = _map.ToArray(); } return _contents; } } } private static class Requires { [DebuggerStepThrough] public static T NotNullAllowStructs<T>(T value, string parameterName) { if (value == null) { throw new ArgumentNullException(parameterName); } return value; } [DebuggerStepThrough] public static T NotNull<T>(T value, string parameterName) where T : class { if (value == null) { throw new ArgumentNullException(parameterName); } return value; } [DebuggerStepThrough] public static Exception FailRange(string parameterName, string? message = null) { if (string.IsNullOrEmpty(message)) { throw new ArgumentOutOfRangeException(parameterName); } throw new ArgumentOutOfRangeException(parameterName, message); } [DebuggerStepThrough] public static void Range(bool condition, string parameterName, string? message = null) { if (!condition) { Requires.FailRange(parameterName, message); } } } private static class Strings { public static string DuplicateKey => CompilerExtensionsResources.An_element_with_the_same_key_but_a_different_value_already_exists; } } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 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
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerDriver.GroupedAnalyzerActions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; using System.Linq; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { internal partial class AnalyzerDriver<TLanguageKindEnum> : AnalyzerDriver where TLanguageKindEnum : struct { /// <summary> /// <see cref="AnalyzerActions"/> grouped by <see cref="DiagnosticAnalyzer"/>, and possibly other entities, such as <see cref="OperationKind"/>, <see cref="SymbolKind"/>, etc. /// </summary> private sealed class GroupedAnalyzerActions : IGroupedAnalyzerActions { public static readonly GroupedAnalyzerActions Empty = new GroupedAnalyzerActions(ImmutableArray<(DiagnosticAnalyzer, GroupedAnalyzerActionsForAnalyzer)>.Empty, AnalyzerActions.Empty); private GroupedAnalyzerActions(ImmutableArray<(DiagnosticAnalyzer, GroupedAnalyzerActionsForAnalyzer)> groupedActionsAndAnalyzers, in AnalyzerActions analyzerActions) { GroupedActionsByAnalyzer = groupedActionsAndAnalyzers; AnalyzerActions = analyzerActions; } public ImmutableArray<(DiagnosticAnalyzer analyzer, GroupedAnalyzerActionsForAnalyzer groupedActions)> GroupedActionsByAnalyzer { get; } public AnalyzerActions AnalyzerActions { get; } public bool IsEmpty { get { var isEmpty = ReferenceEquals(this, Empty); Debug.Assert(isEmpty || !GroupedActionsByAnalyzer.IsEmpty); return isEmpty; } } public static GroupedAnalyzerActions Create(DiagnosticAnalyzer analyzer, in AnalyzerActions analyzerActions) { if (analyzerActions.IsEmpty) { return Empty; } var groupedActions = new GroupedAnalyzerActionsForAnalyzer(analyzer, analyzerActions, analyzerActionsNeedFiltering: false); var groupedActionsAndAnalyzers = ImmutableArray<(DiagnosticAnalyzer, GroupedAnalyzerActionsForAnalyzer)>.Empty.Add((analyzer, groupedActions)); return new GroupedAnalyzerActions(groupedActionsAndAnalyzers, in analyzerActions); } public static GroupedAnalyzerActions Create(ImmutableArray<DiagnosticAnalyzer> analyzers, in AnalyzerActions analyzerActions) { Debug.Assert(!analyzers.IsDefaultOrEmpty); var groups = analyzers.SelectAsArray( (analyzer, analyzerActions) => (analyzer, new GroupedAnalyzerActionsForAnalyzer(analyzer, analyzerActions, analyzerActionsNeedFiltering: true)), analyzerActions); return new GroupedAnalyzerActions(groups, in analyzerActions); } IGroupedAnalyzerActions IGroupedAnalyzerActions.Append(IGroupedAnalyzerActions igroupedAnalyzerActions) { var groupedAnalyzerActions = (GroupedAnalyzerActions)igroupedAnalyzerActions; #if DEBUG var inputAnalyzers = groupedAnalyzerActions.GroupedActionsByAnalyzer.Select(a => a.analyzer); var myAnalyzers = GroupedActionsByAnalyzer.Select(a => a.analyzer); var intersected = inputAnalyzers.Intersect(myAnalyzers); Debug.Assert(intersected.IsEmpty()); #endif var newGroupedActions = GroupedActionsByAnalyzer.AddRange(groupedAnalyzerActions.GroupedActionsByAnalyzer); var newAnalyzerActions = AnalyzerActions.Append(groupedAnalyzerActions.AnalyzerActions); return new GroupedAnalyzerActions(newGroupedActions, newAnalyzerActions); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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; using System.Linq; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { internal partial class AnalyzerDriver<TLanguageKindEnum> : AnalyzerDriver where TLanguageKindEnum : struct { /// <summary> /// <see cref="AnalyzerActions"/> grouped by <see cref="DiagnosticAnalyzer"/>, and possibly other entities, such as <see cref="OperationKind"/>, <see cref="SymbolKind"/>, etc. /// </summary> private sealed class GroupedAnalyzerActions : IGroupedAnalyzerActions { public static readonly GroupedAnalyzerActions Empty = new GroupedAnalyzerActions(ImmutableArray<(DiagnosticAnalyzer, GroupedAnalyzerActionsForAnalyzer)>.Empty, AnalyzerActions.Empty); private GroupedAnalyzerActions(ImmutableArray<(DiagnosticAnalyzer, GroupedAnalyzerActionsForAnalyzer)> groupedActionsAndAnalyzers, in AnalyzerActions analyzerActions) { GroupedActionsByAnalyzer = groupedActionsAndAnalyzers; AnalyzerActions = analyzerActions; } public ImmutableArray<(DiagnosticAnalyzer analyzer, GroupedAnalyzerActionsForAnalyzer groupedActions)> GroupedActionsByAnalyzer { get; } public AnalyzerActions AnalyzerActions { get; } public bool IsEmpty { get { var isEmpty = ReferenceEquals(this, Empty); Debug.Assert(isEmpty || !GroupedActionsByAnalyzer.IsEmpty); return isEmpty; } } public static GroupedAnalyzerActions Create(DiagnosticAnalyzer analyzer, in AnalyzerActions analyzerActions) { if (analyzerActions.IsEmpty) { return Empty; } var groupedActions = new GroupedAnalyzerActionsForAnalyzer(analyzer, analyzerActions, analyzerActionsNeedFiltering: false); var groupedActionsAndAnalyzers = ImmutableArray<(DiagnosticAnalyzer, GroupedAnalyzerActionsForAnalyzer)>.Empty.Add((analyzer, groupedActions)); return new GroupedAnalyzerActions(groupedActionsAndAnalyzers, in analyzerActions); } public static GroupedAnalyzerActions Create(ImmutableArray<DiagnosticAnalyzer> analyzers, in AnalyzerActions analyzerActions) { Debug.Assert(!analyzers.IsDefaultOrEmpty); var groups = analyzers.SelectAsArray( (analyzer, analyzerActions) => (analyzer, new GroupedAnalyzerActionsForAnalyzer(analyzer, analyzerActions, analyzerActionsNeedFiltering: true)), analyzerActions); return new GroupedAnalyzerActions(groups, in analyzerActions); } IGroupedAnalyzerActions IGroupedAnalyzerActions.Append(IGroupedAnalyzerActions igroupedAnalyzerActions) { var groupedAnalyzerActions = (GroupedAnalyzerActions)igroupedAnalyzerActions; #if DEBUG var inputAnalyzers = groupedAnalyzerActions.GroupedActionsByAnalyzer.Select(a => a.analyzer); var myAnalyzers = GroupedActionsByAnalyzer.Select(a => a.analyzer); var intersected = inputAnalyzers.Intersect(myAnalyzers); Debug.Assert(intersected.IsEmpty()); #endif var newGroupedActions = GroupedActionsByAnalyzer.AddRange(groupedAnalyzerActions.GroupedActionsByAnalyzer); var newAnalyzerActions = AnalyzerActions.Append(groupedAnalyzerActions.AnalyzerActions); return new GroupedAnalyzerActions(newGroupedActions, newAnalyzerActions); } } } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Features/Core/Portable/Completion/Providers/AbstractCrefCompletionProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract class AbstractCrefCompletionProvider : LSPCompletionProvider { protected const string HideAdvancedMembers = nameof(HideAdvancedMembers); protected override async Task<CompletionDescription> GetDescriptionWorkerAsync( Document document, CompletionItem item, CancellationToken cancellationToken) { var position = SymbolCompletionItem.GetContextPosition(item); // What EditorBrowsable settings were we previously passed in (if it mattered)? var hideAdvancedMembers = false; if (item.Properties.TryGetValue(HideAdvancedMembers, out var hideAdvancedMembersString)) { bool.TryParse(hideAdvancedMembersString, out hideAdvancedMembers); } var options = document.Project.Solution.Workspace.Options .WithChangedOption(new OptionKey(CompletionOptions.HideAdvancedMembers, document.Project.Language), hideAdvancedMembers); var (token, semanticModel, symbols) = await GetSymbolsAsync(document, position, options, cancellationToken).ConfigureAwait(false); var name = SymbolCompletionItem.GetSymbolName(item); var kind = SymbolCompletionItem.GetKind(item); var bestSymbols = symbols.WhereAsArray(s => s.Kind == kind && s.Name == name); return await SymbolCompletionItem.GetDescriptionAsync(item, bestSymbols, document, semanticModel, cancellationToken).ConfigureAwait(false); } protected abstract Task<(SyntaxToken, SemanticModel, ImmutableArray<ISymbol>)> GetSymbolsAsync( Document document, int position, OptionSet options, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract class AbstractCrefCompletionProvider : LSPCompletionProvider { protected const string HideAdvancedMembers = nameof(HideAdvancedMembers); protected override async Task<CompletionDescription> GetDescriptionWorkerAsync( Document document, CompletionItem item, CancellationToken cancellationToken) { var position = SymbolCompletionItem.GetContextPosition(item); // What EditorBrowsable settings were we previously passed in (if it mattered)? var hideAdvancedMembers = false; if (item.Properties.TryGetValue(HideAdvancedMembers, out var hideAdvancedMembersString)) { bool.TryParse(hideAdvancedMembersString, out hideAdvancedMembers); } var options = document.Project.Solution.Workspace.Options .WithChangedOption(new OptionKey(CompletionOptions.HideAdvancedMembers, document.Project.Language), hideAdvancedMembers); var (token, semanticModel, symbols) = await GetSymbolsAsync(document, position, options, cancellationToken).ConfigureAwait(false); var name = SymbolCompletionItem.GetSymbolName(item); var kind = SymbolCompletionItem.GetKind(item); var bestSymbols = symbols.WhereAsArray(s => s.Kind == kind && s.Name == name); return await SymbolCompletionItem.GetDescriptionAsync(item, bestSymbols, document, semanticModel, cancellationToken).ConfigureAwait(false); } protected abstract Task<(SyntaxToken, SemanticModel, ImmutableArray<ISymbol>)> GetSymbolsAsync( Document document, int position, OptionSet options, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/Core/Portable/Classification/ClassifiedSpan.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Classification { public struct ClassifiedSpan : IEquatable<ClassifiedSpan> { public string ClassificationType { get; } public TextSpan TextSpan { get; } public ClassifiedSpan(string classificationType, TextSpan textSpan) : this(textSpan, classificationType) { } public ClassifiedSpan(TextSpan textSpan, string classificationType) : this() { this.ClassificationType = classificationType; this.TextSpan = textSpan; } public override int GetHashCode() => Hash.Combine(this.ClassificationType, this.TextSpan.GetHashCode()); public override bool Equals(object? obj) { return obj is ClassifiedSpan && Equals((ClassifiedSpan)obj); } public bool Equals(ClassifiedSpan other) => this.ClassificationType == other.ClassificationType && this.TextSpan == other.TextSpan; } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Classification { public struct ClassifiedSpan : IEquatable<ClassifiedSpan> { public string ClassificationType { get; } public TextSpan TextSpan { get; } public ClassifiedSpan(string classificationType, TextSpan textSpan) : this(textSpan, classificationType) { } public ClassifiedSpan(TextSpan textSpan, string classificationType) : this() { this.ClassificationType = classificationType; this.TextSpan = textSpan; } public override int GetHashCode() => Hash.Combine(this.ClassificationType, this.TextSpan.GetHashCode()); public override bool Equals(object? obj) { return obj is ClassifiedSpan && Equals((ClassifiedSpan)obj); } public bool Equals(ClassifiedSpan other) => this.ClassificationType == other.ClassificationType && this.TextSpan == other.TextSpan; } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/CSharp/Impl/Snippets/SnippetCommandHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using Microsoft.VisualStudio.LanguageServices.Implementation.Snippets; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Snippets { [Export(typeof(ICommandHandler))] [ContentType(Microsoft.CodeAnalysis.Editor.ContentTypeNames.CSharpContentType)] [Name("CSharp Snippets")] [Order(After = PredefinedCompletionNames.CompletionCommandHandler)] [Order(After = Microsoft.CodeAnalysis.Editor.PredefinedCommandHandlerNames.SignatureHelpAfterCompletion)] [Order(Before = Microsoft.CodeAnalysis.Editor.PredefinedCommandHandlerNames.AutomaticLineEnder)] internal sealed class SnippetCommandHandler : AbstractSnippetCommandHandler, ICommandHandler<SurroundWithCommandArgs>, IChainedCommandHandler<TypeCharCommandArgs> { private readonly ImmutableArray<Lazy<ArgumentProvider, OrderableLanguageMetadata>> _argumentProviders; [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public SnippetCommandHandler( IThreadingContext threadingContext, SignatureHelpControllerProvider signatureHelpControllerProvider, IEditorCommandHandlerServiceFactory editorCommandHandlerServiceFactory, IVsEditorAdaptersFactoryService editorAdaptersFactoryService, SVsServiceProvider serviceProvider, [ImportMany] IEnumerable<Lazy<ArgumentProvider, OrderableLanguageMetadata>> argumentProviders) : base(threadingContext, signatureHelpControllerProvider, editorCommandHandlerServiceFactory, editorAdaptersFactoryService, serviceProvider) { _argumentProviders = argumentProviders.ToImmutableArray(); } public bool ExecuteCommand(SurroundWithCommandArgs args, CommandExecutionContext context) { AssertIsForeground(); if (!AreSnippetsEnabled(args)) { return false; } return TryInvokeInsertionUI(args.TextView, args.SubjectBuffer, surroundWith: true); } public CommandState GetCommandState(SurroundWithCommandArgs args) { AssertIsForeground(); if (!AreSnippetsEnabled(args)) { return CommandState.Unspecified; } if (!Workspace.TryGetWorkspace(args.SubjectBuffer.AsTextContainer(), out var workspace)) { return CommandState.Unspecified; } if (!workspace.CanApplyChange(ApplyChangesKind.ChangeDocument)) { return CommandState.Unspecified; } return CommandState.Available; } public CommandState GetCommandState(TypeCharCommandArgs args, Func<CommandState> nextCommandHandler) { return nextCommandHandler(); } public void ExecuteCommand(TypeCharCommandArgs args, Action nextCommandHandler, CommandExecutionContext executionContext) { AssertIsForeground(); if (args.TypedChar == ';' && AreSnippetsEnabled(args) && args.TextView.Properties.TryGetProperty(typeof(AbstractSnippetExpansionClient), out AbstractSnippetExpansionClient snippetExpansionClient) && snippetExpansionClient.IsFullMethodCallSnippet) { // Commit the snippet. Leave the caret in place, but clear the selection. Subsequent handlers in the // chain will handle the remaining Complete Statement (';' insertion) operations only if there is no // active selection. snippetExpansionClient.CommitSnippet(leaveCaret: true); args.TextView.Selection.Clear(); } nextCommandHandler(); } protected override AbstractSnippetExpansionClient GetSnippetExpansionClient(ITextView textView, ITextBuffer subjectBuffer) { if (!textView.Properties.TryGetProperty(typeof(AbstractSnippetExpansionClient), out AbstractSnippetExpansionClient expansionClient)) { expansionClient = new SnippetExpansionClient(ThreadingContext, Guids.CSharpLanguageServiceId, textView, subjectBuffer, SignatureHelpControllerProvider, EditorCommandHandlerServiceFactory, EditorAdaptersFactoryService, _argumentProviders); textView.Properties.AddProperty(typeof(AbstractSnippetExpansionClient), expansionClient); } return expansionClient; } protected override bool TryInvokeInsertionUI(ITextView textView, ITextBuffer subjectBuffer, bool surroundWith = false) { if (!TryGetExpansionManager(out var expansionManager)) { return false; } expansionManager.InvokeInsertionUI( EditorAdaptersFactoryService.GetViewAdapter(textView), GetSnippetExpansionClient(textView, subjectBuffer), Guids.CSharpLanguageServiceId, bstrTypes: surroundWith ? new[] { "SurroundsWith" } : new[] { "Expansion", "SurroundsWith" }, iCountTypes: surroundWith ? 1 : 2, fIncludeNULLType: 1, bstrKinds: null, iCountKinds: 0, fIncludeNULLKind: 0, bstrPrefixText: surroundWith ? CSharpVSResources.Surround_With : CSharpVSResources.Insert_Snippet, bstrCompletionChar: null); return true; } protected override bool IsSnippetExpansionContext(Document document, int startPosition, CancellationToken cancellationToken) { var syntaxTree = document.GetSyntaxTreeSynchronously(cancellationToken); return !syntaxTree.IsEntirelyWithinStringOrCharLiteral(startPosition, cancellationToken) && !syntaxTree.IsEntirelyWithinComment(startPosition, 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.Collections.Immutable; using System.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using Microsoft.VisualStudio.LanguageServices.Implementation.Snippets; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Snippets { [Export(typeof(ICommandHandler))] [ContentType(Microsoft.CodeAnalysis.Editor.ContentTypeNames.CSharpContentType)] [Name("CSharp Snippets")] [Order(After = PredefinedCompletionNames.CompletionCommandHandler)] [Order(After = Microsoft.CodeAnalysis.Editor.PredefinedCommandHandlerNames.SignatureHelpAfterCompletion)] [Order(Before = Microsoft.CodeAnalysis.Editor.PredefinedCommandHandlerNames.AutomaticLineEnder)] internal sealed class SnippetCommandHandler : AbstractSnippetCommandHandler, ICommandHandler<SurroundWithCommandArgs>, IChainedCommandHandler<TypeCharCommandArgs> { private readonly ImmutableArray<Lazy<ArgumentProvider, OrderableLanguageMetadata>> _argumentProviders; [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public SnippetCommandHandler( IThreadingContext threadingContext, SignatureHelpControllerProvider signatureHelpControllerProvider, IEditorCommandHandlerServiceFactory editorCommandHandlerServiceFactory, IVsEditorAdaptersFactoryService editorAdaptersFactoryService, SVsServiceProvider serviceProvider, [ImportMany] IEnumerable<Lazy<ArgumentProvider, OrderableLanguageMetadata>> argumentProviders) : base(threadingContext, signatureHelpControllerProvider, editorCommandHandlerServiceFactory, editorAdaptersFactoryService, serviceProvider) { _argumentProviders = argumentProviders.ToImmutableArray(); } public bool ExecuteCommand(SurroundWithCommandArgs args, CommandExecutionContext context) { AssertIsForeground(); if (!AreSnippetsEnabled(args)) { return false; } return TryInvokeInsertionUI(args.TextView, args.SubjectBuffer, surroundWith: true); } public CommandState GetCommandState(SurroundWithCommandArgs args) { AssertIsForeground(); if (!AreSnippetsEnabled(args)) { return CommandState.Unspecified; } if (!Workspace.TryGetWorkspace(args.SubjectBuffer.AsTextContainer(), out var workspace)) { return CommandState.Unspecified; } if (!workspace.CanApplyChange(ApplyChangesKind.ChangeDocument)) { return CommandState.Unspecified; } return CommandState.Available; } public CommandState GetCommandState(TypeCharCommandArgs args, Func<CommandState> nextCommandHandler) { return nextCommandHandler(); } public void ExecuteCommand(TypeCharCommandArgs args, Action nextCommandHandler, CommandExecutionContext executionContext) { AssertIsForeground(); if (args.TypedChar == ';' && AreSnippetsEnabled(args) && args.TextView.Properties.TryGetProperty(typeof(AbstractSnippetExpansionClient), out AbstractSnippetExpansionClient snippetExpansionClient) && snippetExpansionClient.IsFullMethodCallSnippet) { // Commit the snippet. Leave the caret in place, but clear the selection. Subsequent handlers in the // chain will handle the remaining Complete Statement (';' insertion) operations only if there is no // active selection. snippetExpansionClient.CommitSnippet(leaveCaret: true); args.TextView.Selection.Clear(); } nextCommandHandler(); } protected override AbstractSnippetExpansionClient GetSnippetExpansionClient(ITextView textView, ITextBuffer subjectBuffer) { if (!textView.Properties.TryGetProperty(typeof(AbstractSnippetExpansionClient), out AbstractSnippetExpansionClient expansionClient)) { expansionClient = new SnippetExpansionClient(ThreadingContext, Guids.CSharpLanguageServiceId, textView, subjectBuffer, SignatureHelpControllerProvider, EditorCommandHandlerServiceFactory, EditorAdaptersFactoryService, _argumentProviders); textView.Properties.AddProperty(typeof(AbstractSnippetExpansionClient), expansionClient); } return expansionClient; } protected override bool TryInvokeInsertionUI(ITextView textView, ITextBuffer subjectBuffer, bool surroundWith = false) { if (!TryGetExpansionManager(out var expansionManager)) { return false; } expansionManager.InvokeInsertionUI( EditorAdaptersFactoryService.GetViewAdapter(textView), GetSnippetExpansionClient(textView, subjectBuffer), Guids.CSharpLanguageServiceId, bstrTypes: surroundWith ? new[] { "SurroundsWith" } : new[] { "Expansion", "SurroundsWith" }, iCountTypes: surroundWith ? 1 : 2, fIncludeNULLType: 1, bstrKinds: null, iCountKinds: 0, fIncludeNULLKind: 0, bstrPrefixText: surroundWith ? CSharpVSResources.Surround_With : CSharpVSResources.Insert_Snippet, bstrCompletionChar: null); return true; } protected override bool IsSnippetExpansionContext(Document document, int startPosition, CancellationToken cancellationToken) { var syntaxTree = document.GetSyntaxTreeSynchronously(cancellationToken); return !syntaxTree.IsEntirelyWithinStringOrCharLiteral(startPosition, cancellationToken) && !syntaxTree.IsEntirelyWithinComment(startPosition, cancellationToken); } } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Analyzers/CSharp/Tests/UseCoalesceExpression/UseCoalesceExpressionForNullableTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeFixes; using Microsoft.CodeAnalysis.CSharp.UseCoalesceExpression; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.UseCoalesceExpression; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseCoalesceExpression { public class UseCoalesceExpressionForNullableTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public UseCoalesceExpressionForNullableTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpUseCoalesceExpressionForNullableDiagnosticAnalyzer(), new UseCoalesceExpressionForNullableCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestOnLeft_Equals() { await TestInRegularAndScriptAsync( @"using System; class C { void M(int? x, int? y) { var z = [||]!x.HasValue ? y : x.Value; } }", @"using System; class C { void M(int? x, int? y) { var z = x ?? y ; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestOnLeft_NotEquals() { await TestInRegularAndScriptAsync( @"using System; class C { void M(int? x, int? y) { var z = [||]x.HasValue ? x.Value : y; } }", @"using System; class C { void M(int? x, int? y) { var z = x ?? y; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestComplexExpression() { await TestInRegularAndScriptAsync( @"using System; class C { void M(int? x, int? y) { var z = [||]!(x + y).HasValue ? y : (x + y).Value; } }", @"using System; class C { void M(int? x, int? y) { var z = (x + y) ?? y ; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestParens1() { await TestInRegularAndScriptAsync( @"using System; class C { void M(int? x, int? y) { var z = [||](x.HasValue) ? x.Value : y; } }", @"using System; class C { void M(int? x, int? y) { var z = x ?? y; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestFixAll1() { await TestInRegularAndScriptAsync( @"using System; class C { void M(int? x, int? y) { var z1 = {|FixAllInDocument:x|}.HasValue ? x.Value : y; var z2 = !x.HasValue ? y : x.Value; } }", @"using System; class C { void M(int? x, int? y) { var z1 = x ?? y; var z2 = x ?? y ; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestFixAll2() { await TestInRegularAndScriptAsync( @"using System; class C { void M(int? x, int? y, int? z) { var w = {|FixAllInDocument:x|}.HasValue ? x.Value : y.ToString(z.HasValue ? z.Value : y); } }", @"using System; class C { void M(int? x, int? y, int? z) { var w = x ?? y.ToString(z ?? y); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestFixAll3() { await TestInRegularAndScriptAsync( @"using System; class C { void M(int? x, int? y, int? z) { var w = {|FixAllInDocument:x|}.HasValue ? x.Value : y.HasValue ? y.Value : z; } }", @"using System; class C { void M(int? x, int? y, int? z) { var w = x ?? y ?? z; } }"); } [WorkItem(17028, "https://github.com/dotnet/roslyn/issues/17028")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestInExpressionOfT() { await TestInRegularAndScriptAsync( @"using System; using System.Linq.Expressions; class C { void M(int? x, int? y) { Expression<Func<int>> e = () => [||]!x.HasValue ? y : x.Value; } }", @"using System; using System.Linq.Expressions; class C { void M(int? x, int? y) { Expression<Func<int>> e = () => {|Warning:x ?? y|} ; } }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeFixes; using Microsoft.CodeAnalysis.CSharp.UseCoalesceExpression; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.UseCoalesceExpression; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseCoalesceExpression { public class UseCoalesceExpressionForNullableTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public UseCoalesceExpressionForNullableTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpUseCoalesceExpressionForNullableDiagnosticAnalyzer(), new UseCoalesceExpressionForNullableCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestOnLeft_Equals() { await TestInRegularAndScriptAsync( @"using System; class C { void M(int? x, int? y) { var z = [||]!x.HasValue ? y : x.Value; } }", @"using System; class C { void M(int? x, int? y) { var z = x ?? y ; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestOnLeft_NotEquals() { await TestInRegularAndScriptAsync( @"using System; class C { void M(int? x, int? y) { var z = [||]x.HasValue ? x.Value : y; } }", @"using System; class C { void M(int? x, int? y) { var z = x ?? y; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestComplexExpression() { await TestInRegularAndScriptAsync( @"using System; class C { void M(int? x, int? y) { var z = [||]!(x + y).HasValue ? y : (x + y).Value; } }", @"using System; class C { void M(int? x, int? y) { var z = (x + y) ?? y ; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestParens1() { await TestInRegularAndScriptAsync( @"using System; class C { void M(int? x, int? y) { var z = [||](x.HasValue) ? x.Value : y; } }", @"using System; class C { void M(int? x, int? y) { var z = x ?? y; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestFixAll1() { await TestInRegularAndScriptAsync( @"using System; class C { void M(int? x, int? y) { var z1 = {|FixAllInDocument:x|}.HasValue ? x.Value : y; var z2 = !x.HasValue ? y : x.Value; } }", @"using System; class C { void M(int? x, int? y) { var z1 = x ?? y; var z2 = x ?? y ; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestFixAll2() { await TestInRegularAndScriptAsync( @"using System; class C { void M(int? x, int? y, int? z) { var w = {|FixAllInDocument:x|}.HasValue ? x.Value : y.ToString(z.HasValue ? z.Value : y); } }", @"using System; class C { void M(int? x, int? y, int? z) { var w = x ?? y.ToString(z ?? y); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestFixAll3() { await TestInRegularAndScriptAsync( @"using System; class C { void M(int? x, int? y, int? z) { var w = {|FixAllInDocument:x|}.HasValue ? x.Value : y.HasValue ? y.Value : z; } }", @"using System; class C { void M(int? x, int? y, int? z) { var w = x ?? y ?? z; } }"); } [WorkItem(17028, "https://github.com/dotnet/roslyn/issues/17028")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCoalesceExpression)] public async Task TestInExpressionOfT() { await TestInRegularAndScriptAsync( @"using System; using System.Linq.Expressions; class C { void M(int? x, int? y) { Expression<Func<int>> e = () => [||]!x.HasValue ? y : x.Value; } }", @"using System; using System.Linq.Expressions; class C { void M(int? x, int? y) { Expression<Func<int>> e = () => {|Warning:x ?? y|} ; } }"); } } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Portable/Binder/Binder.QueryTranslationState.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp { internal partial class Binder { private class QueryTranslationState { // Represents the current translation state for a query. Consider a query of the form // from ID in EXPR { clauses } SELECT ... // EXPR, above public BoundExpression fromExpression; // ID, above. This may possibly be the special "transparent" identifier public RangeVariableSymbol rangeVariable; // the clauses, above. The top of the stack is the leftmost clause public readonly Stack<QueryClauseSyntax> clauses = new Stack<QueryClauseSyntax>(); // the SELECT clause above (or a groupby clause in its place) public SelectOrGroupClauseSyntax selectOrGroup; // all query variables in scope, including those visible through transparent identifiers // introduced in previous translation phases. Every query variable in scope is a key in // this dictionary. To compute its value, one consults the list of strings that are the // value in this map. If it is empty, there is a lambda parameter for the variable. If it // is nonempty, one starts with the transparent lambda identifier, and follows fields of the // given names in reverse order. So, for example, if the strings are ["a", "b"], the query // variable is represented by the expression TRANSPARENT.b.a where TRANSPARENT is a parameter // of the current lambda expression. public readonly Dictionary<RangeVariableSymbol, ArrayBuilder<string>> allRangeVariables = new Dictionary<RangeVariableSymbol, ArrayBuilder<string>>(); public static RangeVariableMap RangeVariableMap(params RangeVariableSymbol[] parameters) { var result = new RangeVariableMap(); foreach (var vars in parameters) { result.Add(vars, ImmutableArray<string>.Empty); } return result; } public RangeVariableMap RangeVariableMap() { var result = new RangeVariableMap(); foreach (var vars in allRangeVariables.Keys) { result.Add(vars, allRangeVariables[vars].ToImmutable()); } return result; } internal RangeVariableSymbol AddRangeVariable(Binder binder, SyntaxToken identifier, BindingDiagnosticBag diagnostics) { string name = identifier.ValueText; var result = new RangeVariableSymbol(name, binder.ContainingMemberOrLambda, identifier.GetLocation()); bool error = false; foreach (var existingRangeVariable in allRangeVariables.Keys) { if (existingRangeVariable.Name == name) { diagnostics.Add(ErrorCode.ERR_QueryDuplicateRangeVariable, identifier.GetLocation(), name); error = true; } } if (!error) { var collisionDetector = new LocalScopeBinder(binder); collisionDetector.ValidateDeclarationNameConflictsInScope(result, diagnostics); } allRangeVariables.Add(result, ArrayBuilder<string>.GetInstance()); return result; } // Add a new lambda that is a transparent identifier, by providing the name that is the // field of the new transparent lambda parameter that contains the old variables. internal void AddTransparentIdentifier(string name) { foreach (var b in allRangeVariables.Values) { b.Add(name); } } private int _nextTransparentIdentifierNumber; internal string TransparentRangeVariableName() { return transparentIdentifierPrefix + _nextTransparentIdentifierNumber++; } internal RangeVariableSymbol TransparentRangeVariable(Binder binder) { var transparentIdentifier = TransparentRangeVariableName(); return new RangeVariableSymbol(transparentIdentifier, binder.ContainingMemberOrLambda, null, true); } public void Clear() { fromExpression = null; rangeVariable = null; selectOrGroup = null; foreach (var b in allRangeVariables.Values) b.Free(); allRangeVariables.Clear(); clauses.Clear(); } public void Free() { Clear(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp { internal partial class Binder { private class QueryTranslationState { // Represents the current translation state for a query. Consider a query of the form // from ID in EXPR { clauses } SELECT ... // EXPR, above public BoundExpression fromExpression; // ID, above. This may possibly be the special "transparent" identifier public RangeVariableSymbol rangeVariable; // the clauses, above. The top of the stack is the leftmost clause public readonly Stack<QueryClauseSyntax> clauses = new Stack<QueryClauseSyntax>(); // the SELECT clause above (or a groupby clause in its place) public SelectOrGroupClauseSyntax selectOrGroup; // all query variables in scope, including those visible through transparent identifiers // introduced in previous translation phases. Every query variable in scope is a key in // this dictionary. To compute its value, one consults the list of strings that are the // value in this map. If it is empty, there is a lambda parameter for the variable. If it // is nonempty, one starts with the transparent lambda identifier, and follows fields of the // given names in reverse order. So, for example, if the strings are ["a", "b"], the query // variable is represented by the expression TRANSPARENT.b.a where TRANSPARENT is a parameter // of the current lambda expression. public readonly Dictionary<RangeVariableSymbol, ArrayBuilder<string>> allRangeVariables = new Dictionary<RangeVariableSymbol, ArrayBuilder<string>>(); public static RangeVariableMap RangeVariableMap(params RangeVariableSymbol[] parameters) { var result = new RangeVariableMap(); foreach (var vars in parameters) { result.Add(vars, ImmutableArray<string>.Empty); } return result; } public RangeVariableMap RangeVariableMap() { var result = new RangeVariableMap(); foreach (var vars in allRangeVariables.Keys) { result.Add(vars, allRangeVariables[vars].ToImmutable()); } return result; } internal RangeVariableSymbol AddRangeVariable(Binder binder, SyntaxToken identifier, BindingDiagnosticBag diagnostics) { string name = identifier.ValueText; var result = new RangeVariableSymbol(name, binder.ContainingMemberOrLambda, identifier.GetLocation()); bool error = false; foreach (var existingRangeVariable in allRangeVariables.Keys) { if (existingRangeVariable.Name == name) { diagnostics.Add(ErrorCode.ERR_QueryDuplicateRangeVariable, identifier.GetLocation(), name); error = true; } } if (!error) { var collisionDetector = new LocalScopeBinder(binder); collisionDetector.ValidateDeclarationNameConflictsInScope(result, diagnostics); } allRangeVariables.Add(result, ArrayBuilder<string>.GetInstance()); return result; } // Add a new lambda that is a transparent identifier, by providing the name that is the // field of the new transparent lambda parameter that contains the old variables. internal void AddTransparentIdentifier(string name) { foreach (var b in allRangeVariables.Values) { b.Add(name); } } private int _nextTransparentIdentifierNumber; internal string TransparentRangeVariableName() { return transparentIdentifierPrefix + _nextTransparentIdentifierNumber++; } internal RangeVariableSymbol TransparentRangeVariable(Binder binder) { var transparentIdentifier = TransparentRangeVariableName(); return new RangeVariableSymbol(transparentIdentifier, binder.ContainingMemberOrLambda, null, true); } public void Clear() { fromExpression = null; rangeVariable = null; selectOrGroup = null; foreach (var b in allRangeVariables.Values) b.Free(); allRangeVariables.Clear(); clauses.Clear(); } public void Free() { Clear(); } } } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/xlf/WorkspaceExtensionsResources.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="../WorkspaceExtensionsResources.resx"> <body> <trans-unit id="Compilation_is_required_to_accomplish_the_task_but_is_not_supported_by_project_0"> <source>Compilation is required to accomplish the task but is not supported by project {0}.</source> <target state="translated">K provedení úlohy se vyžaduje kompilace, ale projekt {0} ji nepodporuje.</target> <note /> </trans-unit> <trans-unit id="Fix_all_0"> <source>Fix all '{0}'</source> <target state="translated">Opravit vše ({0})</target> <note /> </trans-unit> <trans-unit id="Fix_all_0_in_1"> <source>Fix all '{0}' in '{1}'</source> <target state="translated">Opravit vše ({0}) v: {1}</target> <note /> </trans-unit> <trans-unit id="Fix_all_0_in_Solution"> <source>Fix all '{0}' in Solution</source> <target state="translated">Opravit vše ({0}) v řešení</target> <note /> </trans-unit> <trans-unit id="Project_of_ID_0_is_required_to_accomplish_the_task_but_is_not_available_from_the_solution"> <source>Project of ID {0} is required to accomplish the task but is not available from the solution</source> <target state="translated">Ke splnění úkolu se vyžaduje projekt s ID {0}, který ale není z řešení dostupný.</target> <note /> </trans-unit> <trans-unit id="Supplied_diagnostic_cannot_be_null"> <source>Supplied diagnostic cannot be null.</source> <target state="translated">Zadaná diagnostika nemůže být null.</target> <note /> </trans-unit> <trans-unit id="SyntaxTree_is_required_to_accomplish_the_task_but_is_not_supported_by_document_0"> <source>Syntax tree is required to accomplish the task but is not supported by document {0}.</source> <target state="translated">K provedení úlohy se vyžaduje strom syntaxe, ale dokument {0} ho nepodporuje.</target> <note /> </trans-unit> <trans-unit id="The_solution_does_not_contain_the_specified_document"> <source>The solution does not contain the specified document.</source> <target state="translated">Řešení neobsahuje zadaný dokument.</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Declaration_changes_scope_and_may_change_meaning"> <source>Warning: Declaration changes scope and may change meaning.</source> <target state="translated">Upozornění: Deklarace mění rozsah a může změnit význam.</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="../WorkspaceExtensionsResources.resx"> <body> <trans-unit id="Compilation_is_required_to_accomplish_the_task_but_is_not_supported_by_project_0"> <source>Compilation is required to accomplish the task but is not supported by project {0}.</source> <target state="translated">K provedení úlohy se vyžaduje kompilace, ale projekt {0} ji nepodporuje.</target> <note /> </trans-unit> <trans-unit id="Fix_all_0"> <source>Fix all '{0}'</source> <target state="translated">Opravit vše ({0})</target> <note /> </trans-unit> <trans-unit id="Fix_all_0_in_1"> <source>Fix all '{0}' in '{1}'</source> <target state="translated">Opravit vše ({0}) v: {1}</target> <note /> </trans-unit> <trans-unit id="Fix_all_0_in_Solution"> <source>Fix all '{0}' in Solution</source> <target state="translated">Opravit vše ({0}) v řešení</target> <note /> </trans-unit> <trans-unit id="Project_of_ID_0_is_required_to_accomplish_the_task_but_is_not_available_from_the_solution"> <source>Project of ID {0} is required to accomplish the task but is not available from the solution</source> <target state="translated">Ke splnění úkolu se vyžaduje projekt s ID {0}, který ale není z řešení dostupný.</target> <note /> </trans-unit> <trans-unit id="Supplied_diagnostic_cannot_be_null"> <source>Supplied diagnostic cannot be null.</source> <target state="translated">Zadaná diagnostika nemůže být null.</target> <note /> </trans-unit> <trans-unit id="SyntaxTree_is_required_to_accomplish_the_task_but_is_not_supported_by_document_0"> <source>Syntax tree is required to accomplish the task but is not supported by document {0}.</source> <target state="translated">K provedení úlohy se vyžaduje strom syntaxe, ale dokument {0} ho nepodporuje.</target> <note /> </trans-unit> <trans-unit id="The_solution_does_not_contain_the_specified_document"> <source>The solution does not contain the specified document.</source> <target state="translated">Řešení neobsahuje zadaný dokument.</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Declaration_changes_scope_and_may_change_meaning"> <source>Warning: Declaration changes scope and may change meaning.</source> <target state="translated">Upozornění: Deklarace mění rozsah a může změnit význam.</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/Core/Portable/Workspace/FileTextLoader.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal static class FileTextLoaderOptions { /// <summary> /// Hidden registry key to control maximum size of a text file we will read into memory. /// we have this option to reduce a chance of OOM when user adds massive size files to the solution. /// Default threshold is 100MB which came from some internal data on big files and some discussion. /// /// User can override default value by setting DWORD value on FileLengthThreshold in /// "[VS HIVE]\Roslyn\Internal\Performance\Text" /// </summary> internal static readonly Option<long> FileLengthThreshold = new(nameof(FileTextLoaderOptions), nameof(FileLengthThreshold), defaultValue: 100 * 1024 * 1024, storageLocations: new LocalUserProfileStorageLocation(@"Roslyn\Internal\Performance\Text\FileLengthThreshold")); } [ExportOptionProvider, Shared] internal class FileTextLoaderOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FileTextLoaderOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( FileTextLoaderOptions.FileLengthThreshold); } [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] public class FileTextLoader : TextLoader { /// <summary> /// Absolute path of the file. /// </summary> public string Path { get; } /// <summary> /// Specifies an encoding to be used if the actual encoding of the file /// can't be determined from the stream content (the stream doesn't start with Byte Order Mark). /// If <c>null</c> auto-detect heuristics are used to determine the encoding. /// Note that if the stream starts with Byte Order Mark the value of <see cref="DefaultEncoding"/> is ignored. /// </summary> public Encoding? DefaultEncoding { get; } /// <summary> /// Creates a content loader for specified file. /// </summary> /// <param name="path">An absolute file path.</param> /// <param name="defaultEncoding"> /// Specifies an encoding to be used if the actual encoding can't be determined from the stream content (the stream doesn't start with Byte Order Mark). /// If not specified auto-detect heuristics are used to determine the encoding. /// Note that if the stream starts with Byte Order Mark the value of <paramref name="defaultEncoding"/> is ignored. /// </param> /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="path"/> is not an absolute path.</exception> public FileTextLoader(string path, Encoding? defaultEncoding) { CompilerPathUtilities.RequireAbsolutePath(path, "path"); Path = path; DefaultEncoding = defaultEncoding; } internal sealed override string FilePath => Path; protected virtual SourceText CreateText(Stream stream, Workspace workspace) { var factory = workspace.Services.GetRequiredService<ITextFactoryService>(); return factory.CreateText(stream, DefaultEncoding); } /// <summary> /// Load a text and a version of the document in the workspace. /// </summary> /// <exception cref="IOException"></exception> /// <exception cref="InvalidDataException"></exception> public override async Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { ValidateFileLength(workspace, Path); var prevLastWriteTime = FileUtilities.GetFileTimeStamp(Path); TextAndVersion textAndVersion; // In many .NET Framework versions (specifically the 4.5.* series, but probably much earlier // and also later) there is this particularly interesting bit in FileStream.BeginReadAsync: // // // [ed: full comment clipped for brevity] // // // // If we did a sync read to fill the buffer, we could avoid the // // problem, and any async read less than 64K gets turned into a // // synchronous read by NT anyways... // if (numBytes < _bufferSize) // { // if (_buffer == null) _buffer = new byte[_bufferSize]; // IAsyncResult bufferRead = BeginReadCore(_buffer, 0, _bufferSize, null, null, 0); // _readLen = EndRead(bufferRead); // // In English, this means that if you do a asynchronous read for smaller than _bufferSize, // this is implemented by the framework by starting an asynchronous read, and then // blocking your thread until that read is completed. The comment implies this is "fine" // because the asynchronous read will actually be synchronous and thus EndRead won't do // any blocking -- it'll be an effective no-op. In theory, everything is fine here. // // In reality, this can end very poorly. That read in fact can be asynchronous, which means the // EndRead will enter a wait and block the thread. If we are running that call to ReadAsync on a // thread pool thread that completed a previous piece of IO, it means there has to be another // thread available to service the completion of that request in order for our thread to make // progress. Why is this worse than the claim about the operating system turning an // asynchronous read into a synchronous one? If the underlying native ReadFile completes // synchronously, that would mean just our thread is being blocked, and will be unblocked once // the kernel gets done with our work. In this case, if the OS does do the read asynchronously // we are now dependent on another thread being available to unblock us. // // So how does ths manifest itself? We have seen dumps from customers reporting hangs where // we have over a hundred thread pool threads all blocked on EndRead() calls as we read this stream. // In these cases, the user had just completed a build that had a bunch of XAML files, and // this resulted in many .g.i.cs files being written and updated. As a result, Roslyn is trying to // re-read them to provide a new compilation to the XAML language service that is asking for it. // Inspecting these dumps and sampling some of the threads made some notable discoveries: // // 1. When there was a read blocked, it was the _last_ chunk that we were reading in the file in // the file that we were reading. This leads me to believe that it isn't simply very slow IO // (like a network drive), because in that case I'd expect to see some threads in different // places than others. // 2. Some stacks were starting by the continuation of a ReadAsync, and some were the first read // of a file from the background parser. In the first case, all of those threads were if the // files were over 4K in size. The ones with the BackgroundParser still on the stack were files // less than 4K in size. // 3. The "time unresponsive" in seconds correlated with roughly the number of threads we had // blocked, which makes me think we were impacted by the once-per-second hill climbing algorithm // used by the thread pool. // // So what's my analysis? When the XAML language service updated all the files, we kicked off // background parses for all of them. If the file was over 4K the asynchronous read actually did // happen (see point #2), but we'd eventually block the thread pool reading the last chunk. // Point #1 confirms that it was always the last chunk. And in small file cases, we'd block on // the first chunk. But in either case, we'd be blocking off a thread pool thread until another // thread pool thread was available. Since we had enough requests going (over a hundred), // sometimes the user got unlucky and all the threads got blocked. At this point, the CLR // started slowly kicking off more threads, but each time it'd start a new thread rather than // starting work that would be needed to unblock a thread, it just handled an IO that resulted // in another file read hitting the end of the file and another thread would get blocked. The // CLR then must kick off another thread, rinse, repeat. Eventually it'll make progress once // there's no more pending IO requests, everything will complete, and life then continues. // // To work around this issue, we set bufferSize to 1, which means that all reads should bypass // this logic. This is tracked by https://github.com/dotnet/corefx/issues/6007, at least in // corefx. We also open the file for reading with FileShare mode read/write/delete so that // we do not lock this file. using (var stream = FileUtilities.RethrowExceptionsAsIOException(() => new FileStream(Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, bufferSize: 1, useAsync: true))) { var version = VersionStamp.Create(prevLastWriteTime); // we do this so that we asynchronously read from file. and this should allocate less for IDE case. // but probably not for command line case where it doesn't use more sophisticated services. using var readStream = await SerializableBytes.CreateReadableStreamAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false); var text = CreateText(readStream, workspace); textAndVersion = TextAndVersion.Create(text, version, Path); } // Check if the file was definitely modified and closed while we were reading. In this case, we know the read we got was // probably invalid, so throw an IOException which indicates to our caller that we should automatically attempt a re-read. // If the file hasn't been closed yet and there's another writer, we will rely on file change notifications to notify us // and reload the file. var newLastWriteTime = FileUtilities.GetFileTimeStamp(Path); if (!newLastWriteTime.Equals(prevLastWriteTime)) { var message = string.Format(WorkspacesResources.File_was_externally_modified_colon_0, Path); throw new IOException(message); } return textAndVersion; } /// <summary> /// Load a text and a version of the document in the workspace. /// </summary> /// <exception cref="IOException"></exception> /// <exception cref="InvalidDataException"></exception> internal override TextAndVersion LoadTextAndVersionSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { ValidateFileLength(workspace, Path); var prevLastWriteTime = FileUtilities.GetFileTimeStamp(Path); TextAndVersion textAndVersion; // Open file for reading with FileShare mode read/write/delete so that we do not lock this file. using (var stream = FileUtilities.RethrowExceptionsAsIOException(() => new FileStream(Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, bufferSize: 4096, useAsync: false))) { var version = VersionStamp.Create(prevLastWriteTime); var text = CreateText(stream, workspace); textAndVersion = TextAndVersion.Create(text, version, Path); } // Check if the file was definitely modified and closed while we were reading. In this case, we know the read we got was // probably invalid, so throw an IOException which indicates to our caller that we should automatically attempt a re-read. // If the file hasn't been closed yet and there's another writer, we will rely on file change notifications to notify us // and reload the file. var newLastWriteTime = FileUtilities.GetFileTimeStamp(Path); if (!newLastWriteTime.Equals(prevLastWriteTime)) { var message = string.Format(WorkspacesResources.File_was_externally_modified_colon_0, Path); throw new IOException(message); } return textAndVersion; } private string GetDebuggerDisplay() => nameof(Path) + " = " + Path; private static void ValidateFileLength(Workspace workspace, string path) { // Validate file length is under our threshold. // Otherwise, rather than reading the content into the memory, we will throw // InvalidDataException to caller of FileTextLoader.LoadText to deal with // the situation. // // check this (http://source.roslyn.io/#Microsoft.CodeAnalysis.Workspaces/Workspace/Solution/TextDocumentState.cs,132) // to see how workspace deal with exception from FileTextLoader. other consumer can handle the exception differently var fileLength = FileUtilities.GetFileLength(path); var threshold = workspace.Options.GetOption(FileTextLoaderOptions.FileLengthThreshold); if (fileLength > threshold) { // log max file length which will log to VS telemetry in VS host Logger.Log(FunctionId.FileTextLoader_FileLengthThresholdExceeded, KeyValueLogMessage.Create(m => { m["FileLength"] = fileLength; m["Ext"] = PathUtilities.GetExtension(path); })); var message = string.Format(WorkspacesResources.File_0_size_of_1_exceeds_maximum_allowed_size_of_2, path, fileLength, threshold); throw new InvalidDataException(message); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal static class FileTextLoaderOptions { /// <summary> /// Hidden registry key to control maximum size of a text file we will read into memory. /// we have this option to reduce a chance of OOM when user adds massive size files to the solution. /// Default threshold is 100MB which came from some internal data on big files and some discussion. /// /// User can override default value by setting DWORD value on FileLengthThreshold in /// "[VS HIVE]\Roslyn\Internal\Performance\Text" /// </summary> internal static readonly Option<long> FileLengthThreshold = new(nameof(FileTextLoaderOptions), nameof(FileLengthThreshold), defaultValue: 100 * 1024 * 1024, storageLocations: new LocalUserProfileStorageLocation(@"Roslyn\Internal\Performance\Text\FileLengthThreshold")); } [ExportOptionProvider, Shared] internal class FileTextLoaderOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FileTextLoaderOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( FileTextLoaderOptions.FileLengthThreshold); } [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] public class FileTextLoader : TextLoader { /// <summary> /// Absolute path of the file. /// </summary> public string Path { get; } /// <summary> /// Specifies an encoding to be used if the actual encoding of the file /// can't be determined from the stream content (the stream doesn't start with Byte Order Mark). /// If <c>null</c> auto-detect heuristics are used to determine the encoding. /// Note that if the stream starts with Byte Order Mark the value of <see cref="DefaultEncoding"/> is ignored. /// </summary> public Encoding? DefaultEncoding { get; } /// <summary> /// Creates a content loader for specified file. /// </summary> /// <param name="path">An absolute file path.</param> /// <param name="defaultEncoding"> /// Specifies an encoding to be used if the actual encoding can't be determined from the stream content (the stream doesn't start with Byte Order Mark). /// If not specified auto-detect heuristics are used to determine the encoding. /// Note that if the stream starts with Byte Order Mark the value of <paramref name="defaultEncoding"/> is ignored. /// </param> /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="path"/> is not an absolute path.</exception> public FileTextLoader(string path, Encoding? defaultEncoding) { CompilerPathUtilities.RequireAbsolutePath(path, "path"); Path = path; DefaultEncoding = defaultEncoding; } internal sealed override string FilePath => Path; protected virtual SourceText CreateText(Stream stream, Workspace workspace) { var factory = workspace.Services.GetRequiredService<ITextFactoryService>(); return factory.CreateText(stream, DefaultEncoding); } /// <summary> /// Load a text and a version of the document in the workspace. /// </summary> /// <exception cref="IOException"></exception> /// <exception cref="InvalidDataException"></exception> public override async Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { ValidateFileLength(workspace, Path); var prevLastWriteTime = FileUtilities.GetFileTimeStamp(Path); TextAndVersion textAndVersion; // In many .NET Framework versions (specifically the 4.5.* series, but probably much earlier // and also later) there is this particularly interesting bit in FileStream.BeginReadAsync: // // // [ed: full comment clipped for brevity] // // // // If we did a sync read to fill the buffer, we could avoid the // // problem, and any async read less than 64K gets turned into a // // synchronous read by NT anyways... // if (numBytes < _bufferSize) // { // if (_buffer == null) _buffer = new byte[_bufferSize]; // IAsyncResult bufferRead = BeginReadCore(_buffer, 0, _bufferSize, null, null, 0); // _readLen = EndRead(bufferRead); // // In English, this means that if you do a asynchronous read for smaller than _bufferSize, // this is implemented by the framework by starting an asynchronous read, and then // blocking your thread until that read is completed. The comment implies this is "fine" // because the asynchronous read will actually be synchronous and thus EndRead won't do // any blocking -- it'll be an effective no-op. In theory, everything is fine here. // // In reality, this can end very poorly. That read in fact can be asynchronous, which means the // EndRead will enter a wait and block the thread. If we are running that call to ReadAsync on a // thread pool thread that completed a previous piece of IO, it means there has to be another // thread available to service the completion of that request in order for our thread to make // progress. Why is this worse than the claim about the operating system turning an // asynchronous read into a synchronous one? If the underlying native ReadFile completes // synchronously, that would mean just our thread is being blocked, and will be unblocked once // the kernel gets done with our work. In this case, if the OS does do the read asynchronously // we are now dependent on another thread being available to unblock us. // // So how does ths manifest itself? We have seen dumps from customers reporting hangs where // we have over a hundred thread pool threads all blocked on EndRead() calls as we read this stream. // In these cases, the user had just completed a build that had a bunch of XAML files, and // this resulted in many .g.i.cs files being written and updated. As a result, Roslyn is trying to // re-read them to provide a new compilation to the XAML language service that is asking for it. // Inspecting these dumps and sampling some of the threads made some notable discoveries: // // 1. When there was a read blocked, it was the _last_ chunk that we were reading in the file in // the file that we were reading. This leads me to believe that it isn't simply very slow IO // (like a network drive), because in that case I'd expect to see some threads in different // places than others. // 2. Some stacks were starting by the continuation of a ReadAsync, and some were the first read // of a file from the background parser. In the first case, all of those threads were if the // files were over 4K in size. The ones with the BackgroundParser still on the stack were files // less than 4K in size. // 3. The "time unresponsive" in seconds correlated with roughly the number of threads we had // blocked, which makes me think we were impacted by the once-per-second hill climbing algorithm // used by the thread pool. // // So what's my analysis? When the XAML language service updated all the files, we kicked off // background parses for all of them. If the file was over 4K the asynchronous read actually did // happen (see point #2), but we'd eventually block the thread pool reading the last chunk. // Point #1 confirms that it was always the last chunk. And in small file cases, we'd block on // the first chunk. But in either case, we'd be blocking off a thread pool thread until another // thread pool thread was available. Since we had enough requests going (over a hundred), // sometimes the user got unlucky and all the threads got blocked. At this point, the CLR // started slowly kicking off more threads, but each time it'd start a new thread rather than // starting work that would be needed to unblock a thread, it just handled an IO that resulted // in another file read hitting the end of the file and another thread would get blocked. The // CLR then must kick off another thread, rinse, repeat. Eventually it'll make progress once // there's no more pending IO requests, everything will complete, and life then continues. // // To work around this issue, we set bufferSize to 1, which means that all reads should bypass // this logic. This is tracked by https://github.com/dotnet/corefx/issues/6007, at least in // corefx. We also open the file for reading with FileShare mode read/write/delete so that // we do not lock this file. using (var stream = FileUtilities.RethrowExceptionsAsIOException(() => new FileStream(Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, bufferSize: 1, useAsync: true))) { var version = VersionStamp.Create(prevLastWriteTime); // we do this so that we asynchronously read from file. and this should allocate less for IDE case. // but probably not for command line case where it doesn't use more sophisticated services. using var readStream = await SerializableBytes.CreateReadableStreamAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false); var text = CreateText(readStream, workspace); textAndVersion = TextAndVersion.Create(text, version, Path); } // Check if the file was definitely modified and closed while we were reading. In this case, we know the read we got was // probably invalid, so throw an IOException which indicates to our caller that we should automatically attempt a re-read. // If the file hasn't been closed yet and there's another writer, we will rely on file change notifications to notify us // and reload the file. var newLastWriteTime = FileUtilities.GetFileTimeStamp(Path); if (!newLastWriteTime.Equals(prevLastWriteTime)) { var message = string.Format(WorkspacesResources.File_was_externally_modified_colon_0, Path); throw new IOException(message); } return textAndVersion; } /// <summary> /// Load a text and a version of the document in the workspace. /// </summary> /// <exception cref="IOException"></exception> /// <exception cref="InvalidDataException"></exception> internal override TextAndVersion LoadTextAndVersionSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { ValidateFileLength(workspace, Path); var prevLastWriteTime = FileUtilities.GetFileTimeStamp(Path); TextAndVersion textAndVersion; // Open file for reading with FileShare mode read/write/delete so that we do not lock this file. using (var stream = FileUtilities.RethrowExceptionsAsIOException(() => new FileStream(Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, bufferSize: 4096, useAsync: false))) { var version = VersionStamp.Create(prevLastWriteTime); var text = CreateText(stream, workspace); textAndVersion = TextAndVersion.Create(text, version, Path); } // Check if the file was definitely modified and closed while we were reading. In this case, we know the read we got was // probably invalid, so throw an IOException which indicates to our caller that we should automatically attempt a re-read. // If the file hasn't been closed yet and there's another writer, we will rely on file change notifications to notify us // and reload the file. var newLastWriteTime = FileUtilities.GetFileTimeStamp(Path); if (!newLastWriteTime.Equals(prevLastWriteTime)) { var message = string.Format(WorkspacesResources.File_was_externally_modified_colon_0, Path); throw new IOException(message); } return textAndVersion; } private string GetDebuggerDisplay() => nameof(Path) + " = " + Path; private static void ValidateFileLength(Workspace workspace, string path) { // Validate file length is under our threshold. // Otherwise, rather than reading the content into the memory, we will throw // InvalidDataException to caller of FileTextLoader.LoadText to deal with // the situation. // // check this (http://source.roslyn.io/#Microsoft.CodeAnalysis.Workspaces/Workspace/Solution/TextDocumentState.cs,132) // to see how workspace deal with exception from FileTextLoader. other consumer can handle the exception differently var fileLength = FileUtilities.GetFileLength(path); var threshold = workspace.Options.GetOption(FileTextLoaderOptions.FileLengthThreshold); if (fileLength > threshold) { // log max file length which will log to VS telemetry in VS host Logger.Log(FunctionId.FileTextLoader_FileLengthThresholdExceeded, KeyValueLogMessage.Create(m => { m["FileLength"] = fileLength; m["Ext"] = PathUtilities.GetExtension(path); })); var message = string.Format(WorkspacesResources.File_0_size_of_1_exceeds_maximum_allowed_size_of_2, path, fileLength, threshold); throw new InvalidDataException(message); } } } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Features/CSharp/Portable/Organizing/Organizers/IndexerDeclarationOrganizer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Organizing.Organizers; namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers { [ExportSyntaxNodeOrganizer(LanguageNames.CSharp), Shared] internal class IndexerDeclarationOrganizer : AbstractSyntaxNodeOrganizer<IndexerDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public IndexerDeclarationOrganizer() { } protected override IndexerDeclarationSyntax Organize( IndexerDeclarationSyntax syntax, CancellationToken cancellationToken) { return syntax.Update( attributeLists: syntax.AttributeLists, modifiers: ModifiersOrganizer.Organize(syntax.Modifiers), type: syntax.Type, explicitInterfaceSpecifier: syntax.ExplicitInterfaceSpecifier, thisKeyword: syntax.ThisKeyword, parameterList: syntax.ParameterList, accessorList: syntax.AccessorList, expressionBody: syntax.ExpressionBody, semicolonToken: syntax.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. #nullable disable using System; using System.Composition; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Organizing.Organizers; namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers { [ExportSyntaxNodeOrganizer(LanguageNames.CSharp), Shared] internal class IndexerDeclarationOrganizer : AbstractSyntaxNodeOrganizer<IndexerDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public IndexerDeclarationOrganizer() { } protected override IndexerDeclarationSyntax Organize( IndexerDeclarationSyntax syntax, CancellationToken cancellationToken) { return syntax.Update( attributeLists: syntax.AttributeLists, modifiers: ModifiersOrganizer.Organize(syntax.Modifiers), type: syntax.Type, explicitInterfaceSpecifier: syntax.ExplicitInterfaceSpecifier, thisKeyword: syntax.ThisKeyword, parameterList: syntax.ParameterList, accessorList: syntax.AccessorList, expressionBody: syntax.ExpressionBody, semicolonToken: syntax.SemicolonToken); } } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Analyzers/VisualBasic/Analyzers/OrderModifiers/VisualBasicOrderModifiersHelper.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.OrderModifiers Namespace Microsoft.CodeAnalysis.VisualBasic.OrderModifiers Friend Class VisualBasicOrderModifiersHelper Inherits AbstractOrderModifiersHelpers Public Shared ReadOnly Instance As New VisualBasicOrderModifiersHelper() Private Sub New() End Sub Protected Overrides Function GetKeywordKind(trimmed As String) As Integer Dim kind = SyntaxFacts.GetKeywordKind(trimmed) Return If(kind = SyntaxKind.None, SyntaxFacts.GetContextualKeywordKind(trimmed), kind) End Function 'Protected Overrides Function TryParse(String value, out Dictionary<int, int> parsed) As Boolean '{ ' If (!base.TryParse(value, out parsed)) ' { ' Return False; ' } ' // 'partial' must always go at the end in C#. ' parsed[(int)SyntaxKind.PartialKeyword] = int.MaxValue; ' Return True; '} End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.OrderModifiers Namespace Microsoft.CodeAnalysis.VisualBasic.OrderModifiers Friend Class VisualBasicOrderModifiersHelper Inherits AbstractOrderModifiersHelpers Public Shared ReadOnly Instance As New VisualBasicOrderModifiersHelper() Private Sub New() End Sub Protected Overrides Function GetKeywordKind(trimmed As String) As Integer Dim kind = SyntaxFacts.GetKeywordKind(trimmed) Return If(kind = SyntaxKind.None, SyntaxFacts.GetContextualKeywordKind(trimmed), kind) End Function 'Protected Overrides Function TryParse(String value, out Dictionary<int, int> parsed) As Boolean '{ ' If (!base.TryParse(value, out parsed)) ' { ' Return False; ' } ' // 'partial' must always go at the end in C#. ' parsed[(int)SyntaxKind.PartialKeyword] = int.MaxValue; ' Return True; '} End Class End Namespace
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationMethodSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.Editing; namespace Microsoft.CodeAnalysis.CodeGeneration { internal partial class CodeGenerationMethodSymbol : CodeGenerationAbstractMethodSymbol { public override ITypeSymbol ReturnType { get; } public override ImmutableArray<ITypeParameterSymbol> TypeParameters { get; } public override ImmutableArray<IParameterSymbol> Parameters { get; } public override ImmutableArray<IMethodSymbol> ExplicitInterfaceImplementations { get; } public override MethodKind MethodKind { get; } public CodeGenerationMethodSymbol( INamedTypeSymbol containingType, ImmutableArray<AttributeData> attributes, Accessibility declaredAccessibility, DeclarationModifiers modifiers, ITypeSymbol returnType, RefKind refKind, ImmutableArray<IMethodSymbol> explicitInterfaceImplementations, string name, ImmutableArray<ITypeParameterSymbol> typeParameters, ImmutableArray<IParameterSymbol> parameters, ImmutableArray<AttributeData> returnTypeAttributes, string documentationCommentXml = null, MethodKind methodKind = MethodKind.Ordinary, bool isInitOnly = false) : base(containingType, attributes, declaredAccessibility, modifiers, name, returnTypeAttributes, documentationCommentXml) { this.ReturnType = returnType; this.RefKind = refKind; Debug.Assert(!isInitOnly || methodKind == MethodKind.PropertySet); this.IsInitOnly = methodKind == MethodKind.PropertySet && isInitOnly; this.TypeParameters = typeParameters.NullToEmpty(); this.Parameters = parameters.NullToEmpty(); this.MethodKind = methodKind; this.ExplicitInterfaceImplementations = explicitInterfaceImplementations.NullToEmpty(); this.OriginalDefinition = this; } protected override CodeGenerationSymbol Clone() { var result = new CodeGenerationMethodSymbol(this.ContainingType, this.GetAttributes(), this.DeclaredAccessibility, this.Modifiers, this.ReturnType, this.RefKind, this.ExplicitInterfaceImplementations, this.Name, this.TypeParameters, this.Parameters, this.GetReturnTypeAttributes(), _documentationCommentXml, this.MethodKind, this.IsInitOnly); CodeGenerationMethodInfo.Attach(result, CodeGenerationMethodInfo.GetIsNew(this), CodeGenerationMethodInfo.GetIsUnsafe(this), CodeGenerationMethodInfo.GetIsPartial(this), CodeGenerationMethodInfo.GetIsAsyncMethod(this), CodeGenerationMethodInfo.GetStatements(this), CodeGenerationMethodInfo.GetHandlesExpressions(this)); return result; } public override int Arity => this.TypeParameters.Length; public override bool ReturnsVoid => this.ReturnType == null || this.ReturnType.SpecialType == SpecialType.System_Void; public override bool ReturnsByRef { get { return RefKind == RefKind.Ref; } } public override bool ReturnsByRefReadonly { get { return RefKind == RefKind.RefReadOnly; } } public override RefKind RefKind { get; } public override ImmutableArray<ITypeSymbol> TypeArguments => this.TypeParameters.As<ITypeSymbol>(); public override IMethodSymbol ConstructedFrom => this; public override bool IsReadOnly => Modifiers.IsReadOnly; public override bool IsInitOnly { get; } public override System.Reflection.MethodImplAttributes MethodImplementationFlags => default; public override IMethodSymbol OverriddenMethod => null; public override IMethodSymbol ReducedFrom => null; public override ITypeSymbol GetTypeInferredDuringReduction(ITypeParameterSymbol reducedFromTypeParameter) => throw new InvalidOperationException(); public override IMethodSymbol ReduceExtensionMethod(ITypeSymbol receiverType) => null; public override IMethodSymbol PartialImplementationPart => null; public override IMethodSymbol PartialDefinitionPart => null; public override bool IsPartialDefinition => false; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.Editing; namespace Microsoft.CodeAnalysis.CodeGeneration { internal partial class CodeGenerationMethodSymbol : CodeGenerationAbstractMethodSymbol { public override ITypeSymbol ReturnType { get; } public override ImmutableArray<ITypeParameterSymbol> TypeParameters { get; } public override ImmutableArray<IParameterSymbol> Parameters { get; } public override ImmutableArray<IMethodSymbol> ExplicitInterfaceImplementations { get; } public override MethodKind MethodKind { get; } public CodeGenerationMethodSymbol( INamedTypeSymbol containingType, ImmutableArray<AttributeData> attributes, Accessibility declaredAccessibility, DeclarationModifiers modifiers, ITypeSymbol returnType, RefKind refKind, ImmutableArray<IMethodSymbol> explicitInterfaceImplementations, string name, ImmutableArray<ITypeParameterSymbol> typeParameters, ImmutableArray<IParameterSymbol> parameters, ImmutableArray<AttributeData> returnTypeAttributes, string documentationCommentXml = null, MethodKind methodKind = MethodKind.Ordinary, bool isInitOnly = false) : base(containingType, attributes, declaredAccessibility, modifiers, name, returnTypeAttributes, documentationCommentXml) { this.ReturnType = returnType; this.RefKind = refKind; Debug.Assert(!isInitOnly || methodKind == MethodKind.PropertySet); this.IsInitOnly = methodKind == MethodKind.PropertySet && isInitOnly; this.TypeParameters = typeParameters.NullToEmpty(); this.Parameters = parameters.NullToEmpty(); this.MethodKind = methodKind; this.ExplicitInterfaceImplementations = explicitInterfaceImplementations.NullToEmpty(); this.OriginalDefinition = this; } protected override CodeGenerationSymbol Clone() { var result = new CodeGenerationMethodSymbol(this.ContainingType, this.GetAttributes(), this.DeclaredAccessibility, this.Modifiers, this.ReturnType, this.RefKind, this.ExplicitInterfaceImplementations, this.Name, this.TypeParameters, this.Parameters, this.GetReturnTypeAttributes(), _documentationCommentXml, this.MethodKind, this.IsInitOnly); CodeGenerationMethodInfo.Attach(result, CodeGenerationMethodInfo.GetIsNew(this), CodeGenerationMethodInfo.GetIsUnsafe(this), CodeGenerationMethodInfo.GetIsPartial(this), CodeGenerationMethodInfo.GetIsAsyncMethod(this), CodeGenerationMethodInfo.GetStatements(this), CodeGenerationMethodInfo.GetHandlesExpressions(this)); return result; } public override int Arity => this.TypeParameters.Length; public override bool ReturnsVoid => this.ReturnType == null || this.ReturnType.SpecialType == SpecialType.System_Void; public override bool ReturnsByRef { get { return RefKind == RefKind.Ref; } } public override bool ReturnsByRefReadonly { get { return RefKind == RefKind.RefReadOnly; } } public override RefKind RefKind { get; } public override ImmutableArray<ITypeSymbol> TypeArguments => this.TypeParameters.As<ITypeSymbol>(); public override IMethodSymbol ConstructedFrom => this; public override bool IsReadOnly => Modifiers.IsReadOnly; public override bool IsInitOnly { get; } public override System.Reflection.MethodImplAttributes MethodImplementationFlags => default; public override IMethodSymbol OverriddenMethod => null; public override IMethodSymbol ReducedFrom => null; public override ITypeSymbol GetTypeInferredDuringReduction(ITypeParameterSymbol reducedFromTypeParameter) => throw new InvalidOperationException(); public override IMethodSymbol ReduceExtensionMethod(ITypeSymbol receiverType) => null; public override IMethodSymbol PartialImplementationPart => null; public override IMethodSymbol PartialDefinitionPart => null; public override bool IsPartialDefinition => false; } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Rename/Annotations/RenameAnnotation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Rename.ConflictEngine { internal class RenameAnnotation { public const string Kind = "Rename"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Rename.ConflictEngine { internal class RenameAnnotation { public const string Kind = "Rename"; } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Tools/ExternalAccess/FSharp/Internal/Editor/FSharpNavigationBarItemService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Navigation; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Notification; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Editor { [Shared] [ExportLanguageService(typeof(INavigationBarItemService), LanguageNames.FSharp)] internal class FSharpNavigationBarItemService : INavigationBarItemService { private readonly IThreadingContext _threadingContext; private readonly IFSharpNavigationBarItemService _service; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FSharpNavigationBarItemService( IThreadingContext threadingContext, IFSharpNavigationBarItemService service) { _threadingContext = threadingContext; _service = service; } public async Task<ImmutableArray<NavigationBarItem>> GetItemsAsync(Document document, ITextVersion textVersion, CancellationToken cancellationToken) { var items = await _service.GetItemsAsync(document, cancellationToken).ConfigureAwait(false); return items == null ? ImmutableArray<NavigationBarItem>.Empty : ConvertItems(items, textVersion); } private static ImmutableArray<NavigationBarItem> ConvertItems(IList<FSharpNavigationBarItem> items, ITextVersion textVersion) => (items ?? SpecializedCollections.EmptyList<FSharpNavigationBarItem>()).Where(x => x.Spans.Any()).SelectAsArray(x => ConvertToNavigationBarItem(x, textVersion)); public async Task<bool> TryNavigateToItemAsync( Document document, NavigationBarItem item, ITextView view, ITextVersion textVersion, CancellationToken cancellationToken) { // The logic here was ported from FSharp's implementation. The main reason was to avoid shimming INotificationService. var navigationSpan = item.TryGetNavigationSpan(textVersion); if (navigationSpan != null) { var span = navigationSpan.Value; var workspace = document.Project.Solution.Workspace; var navigationService = workspace.Services.GetRequiredService<IFSharpDocumentNavigationService>(); await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); if (navigationService.CanNavigateToPosition(workspace, document.Id, span.Start, virtualSpace: 0, cancellationToken)) { navigationService.TryNavigateToPosition(workspace, document.Id, span.Start, virtualSpace: 0, options: null, cancellationToken); } else { var notificationService = workspace.Services.GetRequiredService<INotificationService>(); notificationService.SendNotification(EditorFeaturesResources.The_definition_of_the_object_is_hidden, severity: NotificationSeverity.Error); } } return true; } public bool ShowItemGrayedIfNear(NavigationBarItem item) { return false; } private static NavigationBarItem ConvertToNavigationBarItem(FSharpNavigationBarItem item, ITextVersion textVersion) { var spans = item.Spans.ToImmutableArrayOrEmpty(); return new SimpleNavigationBarItem( textVersion, item.Text, FSharpGlyphHelpers.ConvertTo(item.Glyph), spans, spans.First(), ConvertItems(item.ChildItems, textVersion), item.Indent, item.Bolded, item.Grayed); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Navigation; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Notification; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Editor { [Shared] [ExportLanguageService(typeof(INavigationBarItemService), LanguageNames.FSharp)] internal class FSharpNavigationBarItemService : INavigationBarItemService { private readonly IThreadingContext _threadingContext; private readonly IFSharpNavigationBarItemService _service; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FSharpNavigationBarItemService( IThreadingContext threadingContext, IFSharpNavigationBarItemService service) { _threadingContext = threadingContext; _service = service; } public async Task<ImmutableArray<NavigationBarItem>> GetItemsAsync(Document document, ITextVersion textVersion, CancellationToken cancellationToken) { var items = await _service.GetItemsAsync(document, cancellationToken).ConfigureAwait(false); return items == null ? ImmutableArray<NavigationBarItem>.Empty : ConvertItems(items, textVersion); } private static ImmutableArray<NavigationBarItem> ConvertItems(IList<FSharpNavigationBarItem> items, ITextVersion textVersion) => (items ?? SpecializedCollections.EmptyList<FSharpNavigationBarItem>()).Where(x => x.Spans.Any()).SelectAsArray(x => ConvertToNavigationBarItem(x, textVersion)); public async Task<bool> TryNavigateToItemAsync( Document document, NavigationBarItem item, ITextView view, ITextVersion textVersion, CancellationToken cancellationToken) { // The logic here was ported from FSharp's implementation. The main reason was to avoid shimming INotificationService. var navigationSpan = item.TryGetNavigationSpan(textVersion); if (navigationSpan != null) { var span = navigationSpan.Value; var workspace = document.Project.Solution.Workspace; var navigationService = workspace.Services.GetRequiredService<IFSharpDocumentNavigationService>(); await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); if (navigationService.CanNavigateToPosition(workspace, document.Id, span.Start, virtualSpace: 0, cancellationToken)) { navigationService.TryNavigateToPosition(workspace, document.Id, span.Start, virtualSpace: 0, options: null, cancellationToken); } else { var notificationService = workspace.Services.GetRequiredService<INotificationService>(); notificationService.SendNotification(EditorFeaturesResources.The_definition_of_the_object_is_hidden, severity: NotificationSeverity.Error); } } return true; } public bool ShowItemGrayedIfNear(NavigationBarItem item) { return false; } private static NavigationBarItem ConvertToNavigationBarItem(FSharpNavigationBarItem item, ITextVersion textVersion) { var spans = item.Spans.ToImmutableArrayOrEmpty(); return new SimpleNavigationBarItem( textVersion, item.Text, FSharpGlyphHelpers.ConvertTo(item.Glyph), spans, spans.First(), ConvertItems(item.ChildItems, textVersion), item.Indent, item.Bolded, item.Grayed); } } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/VisualBasicTest/ChangeSignature/AddParameterTests.Delegates.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.ChangeSignature Imports Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities.ChangeSignature Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ChangeSignature Partial Public Class ChangeSignatureTests Inherits AbstractChangeSignatureTests <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Delegates_ImplicitInvokeCalls() As Task Dim markup = <Text><![CDATA[ Delegate Sub $$MySub(x As Integer, y As String, z As Boolean) Class C Sub M() Dim s As MySub = Nothing s(1, "Two", True) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Delegate Sub MySub(z As Boolean, newIntegerParameter As Integer, y As String) Class C Sub M() Dim s As MySub = Nothing s(True, 12345, "Two") End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode, expectedSelectedIndex:=0) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Delegates_ExplicitInvokeCalls() As Task Dim markup = <Text><![CDATA[ Delegate Sub MySub($$x As Integer, y As String, z As Boolean) Class C Sub M() Dim s As MySub = Nothing s.Invoke(1, "Two", True) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Delegate Sub MySub(z As Boolean, newIntegerParameter As Integer, y As String) Class C Sub M() Dim s As MySub = Nothing s.Invoke(True, 12345, "Two") End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode, expectedSelectedIndex:=0) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Delegates_BeginInvokeCalls() As Task Dim markup = <Text><![CDATA[ Delegate Sub MySub(x As Integer$$, y As String, z As Boolean) Class C Sub M() Dim s As MySub = Nothing s.BeginInvoke(1, "Two", True, Nothing, Nothing) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Delegate Sub MySub(z As Boolean, newIntegerParameter As Integer, y As String) Class C Sub M() Dim s As MySub = Nothing s.BeginInvoke(True, 12345, "Two", Nothing, Nothing) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode, expectedSelectedIndex:=0) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Delegates_SubLambdas() As Task Dim markup = <Text><![CDATA[ Delegate Sub MySub(x As Integer, $$y As String, z As Boolean) Class C Sub M() Dim s As MySub = Nothing s = Sub() End Sub s = Sub(a As Integer, b As String, c As Boolean) End Sub s = Sub(a As Integer, b As String, c As Boolean) System.Console.WriteLine("Test") End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Delegate Sub MySub(z As Boolean, newIntegerParameter As Integer, y As String) Class C Sub M() Dim s As MySub = Nothing s = Sub() End Sub s = Sub(c As Boolean, newIntegerParameter As Integer, b As String) End Sub s = Sub(c As Boolean, newIntegerParameter As Integer, b As String) System.Console.WriteLine("Test") End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode, expectedSelectedIndex:=1) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Delegates_FunctionLambdas() As Task Dim markup = <Text><![CDATA[ Delegate Function MyFunc(x As Integer, y As String, $$z As Boolean) As Integer Class C Sub M() Dim f As MyFunc = Nothing f = Function() Return 1 End Function f = Function(a As Integer, b As String, c As Boolean) Return 1 End Function f = Function(a As Integer, b As String, c As Boolean) 1 End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Delegate Function MyFunc(z As Boolean, newIntegerParameter As Integer, y As String) As Integer Class C Sub M() Dim f As MyFunc = Nothing f = Function() Return 1 End Function f = Function(c As Boolean, newIntegerParameter As Integer, b As String) Return 1 End Function f = Function(c As Boolean, newIntegerParameter As Integer, b As String) 1 End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode, expectedSelectedIndex:=2) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Delegates_ReferencingLambdas_MethodArgument() As Task Dim markup = <Text><![CDATA[ Delegate Function $$MyFunc(x As Integer, y As String, z As Boolean) As Integer Class C Sub M(f As MyFunc) M(Function(a As Integer, b As String, c As Boolean) 1) M(Function(a As Integer, b As String, c As Boolean) Return 1 End Function) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Delegate Function MyFunc(z As Boolean, newIntegerParameter As Integer, y As String) As Integer Class C Sub M(f As MyFunc) M(Function(c As Boolean, newIntegerParameter As Integer, b As String) 1) M(Function(c As Boolean, newIntegerParameter As Integer, b As String) Return 1 End Function) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Delegates_ReferencingLambdas_ReturnValue() As Task Dim markup = <Text><![CDATA[ Delegate Sub $$MySub(x As Integer, y As String, z As Boolean) Class C Function M1() As MySub Return Sub(a As Integer, b As String, c As Boolean) End Sub End Function Function M2() As MySub Return Sub(a As Integer, b As String, c As Boolean) System.Console.WriteLine("Test") End Function End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Delegate Sub MySub(z As Boolean, newIntegerParameter As Integer, y As String) Class C Function M1() As MySub Return Sub(c As Boolean, newIntegerParameter As Integer, b As String) End Sub End Function Function M2() As MySub Return Sub(c As Boolean, newIntegerParameter As Integer, b As String) System.Console.WriteLine("Test") End Function End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Delegates_Recursive() As Task Dim markup = <Text><![CDATA[ Delegate Function $$MyFunc(x As Integer, y As String, z As Boolean) As MyFunc Class C Sub M() Dim f As MyFunc = Nothing f(1, "Two", True)(1, "Two", True)(1, "Two", True)(1, "Two", True) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Delegate Function MyFunc(z As Boolean, newIntegerParameter As Integer, y As String) As MyFunc Class C Sub M() Dim f As MyFunc = Nothing f(True, 12345, "Two")(True, 12345, "Two")(True, 12345, "Two")(True, 12345, "Two") End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Delegates_DocComments() As Task Dim markup = <Text><![CDATA[ ''' <summary> ''' This is <see cref="MyFunc"/>, which has these methods: ''' <see cref="MyFunc.New(Object, System.IntPtr)"/> ''' <see cref="MyFunc.Invoke(Integer, String, Boolean)"/> ''' <see cref="MyFunc.EndInvoke(System.IAsyncResult)"/> ''' <see cref="MyFunc.BeginInvoke(Integer, String, Boolean, System.AsyncCallback, Object)"/> ''' </summary> ''' <param name="x">x!</param> ''' <param name="y">y!</param> ''' <param name="z">z!</param> Delegate Sub $$MyFunc(x As Integer, y As String, z As Boolean) Class C Sub M() Dim f As MyFunc = AddressOf Test End Sub ''' <param name="a"></param> ''' <param name="b"></param> ''' <param name="c"></param> Private Sub Test(a As Integer, b As String, c As Boolean) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ ''' <summary> ''' This is <see cref="MyFunc"/>, which has these methods: ''' <see cref="MyFunc.New(Object, System.IntPtr)"/> ''' <see cref="MyFunc.Invoke(Boolean, Integer, String)"/> ''' <see cref="MyFunc.EndInvoke(System.IAsyncResult)"/> ''' <see cref="MyFunc.BeginInvoke(Boolean, Integer, String, System.AsyncCallback, Object)"/> ''' </summary> ''' <param name="z">z!</param> ''' <param name="newIntegerParameter"></param> ''' <param name="y">y!</param> Delegate Sub MyFunc(z As Boolean, newIntegerParameter As Integer, y As String) Class C Sub M() Dim f As MyFunc = AddressOf Test End Sub ''' <param name="c"></param> ''' <param name="newIntegerParameter"></param> ''' <param name="b"></param> Private Sub Test(c As Boolean, newIntegerParameter As Integer, b As String) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Delegates_Relaxation_FunctionToSub() As Task Dim markup = <Text><![CDATA[ Delegate Sub $$MySub(x As Integer, y As String, z As Boolean) Class C Sub M() Dim f As MySub = AddressOf Test End Sub Private Function Test(a As Integer, b As String, c As Boolean) As Integer Return 1 End Function End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Delegate Sub MySub(z As Boolean, newIntegerParameter As Integer, y As String) Class C Sub M() Dim f As MySub = AddressOf Test End Sub Private Function Test(c As Boolean, newIntegerParameter As Integer, b As String) As Integer Return 1 End Function End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Delegates_Relaxation_ParameterlessFunctionToFunction() As Task Dim markup = <Text><![CDATA[ Delegate Function $$MyFunc(x As Integer, y As String, z As Boolean) As Integer Class C Sub M() Dim f As MyFunc = AddressOf Test End Sub Private Function Test() Return 1 End Function End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Delegate Function MyFunc(z As Boolean, newIntegerParameter As Integer, y As String) As Integer Class C Sub M() Dim f As MyFunc = AddressOf Test End Sub Private Function Test() Return 1 End Function End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Delegates_CascadeToEvents() As Task Dim markup = <Text><![CDATA[ Class C Delegate Sub $$MyDelegate(x As Integer, y As String, z As Boolean) Event MyEvent As MyDelegate Custom Event MyEvent2 As MyDelegate AddHandler(value As MyDelegate) End AddHandler RemoveHandler(value As MyDelegate) End RemoveHandler RaiseEvent(x As Integer, y As String, z As Boolean) End RaiseEvent End Event Sub M() RaiseEvent MyEvent(1, "Two", True) RaiseEvent MyEvent2(1, "Two", True) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Sub MyDelegate(z As Boolean, newIntegerParameter As Integer, y As String) Event MyEvent As MyDelegate Custom Event MyEvent2 As MyDelegate AddHandler(value As MyDelegate) End AddHandler RemoveHandler(value As MyDelegate) End RemoveHandler RaiseEvent(z As Boolean, newIntegerParameter As Integer, y As String) End RaiseEvent End Event Sub M() RaiseEvent MyEvent(True, 12345, "Two") RaiseEvent MyEvent2(True, 12345, "Two") End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Events_ReferencedBy_RaiseEvent() As Task Dim markup = <Text><![CDATA[ Class C Event $$MyEvent(x As Integer, y As String, z As Boolean) Sub M() RaiseEvent MyEvent(1, "Two", True) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Event MyEvent(z As Boolean, newIntegerParameter As Integer, y As String) Sub M() RaiseEvent MyEvent(True, 12345, "Two") End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Events_ReferencedBy_AddHandler() As Task Dim markup = <Text><![CDATA[ Class C Event $$MyEvent(x As Integer, y As String, z As Boolean) Sub M() AddHandler MyEvent, AddressOf MyEventHandler End Sub Sub MyEventHandler(a As Integer, b As String, c As Boolean) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Event MyEvent(z As Boolean, newIntegerParameter As Integer, y As String) Sub M() AddHandler MyEvent, AddressOf MyEventHandler End Sub Sub MyEventHandler(c As Boolean, newIntegerParameter As Integer, b As String) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Events_ReferencedBy_GeneratedDelegateTypeInvocations() As Task Dim markup = <Text><![CDATA[ Class C Event $$MyEvent(x As Integer, y As String, z As Boolean) Sub M() Dim e As MyEventEventHandler = Nothing e(1, "Two", True) e.Invoke(1, "Two", True) e.BeginInvoke(1, "Two", True, Nothing, New Object()) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Event MyEvent(z As Boolean, newIntegerParameter As Integer, y As String) Sub M() Dim e As MyEventEventHandler = Nothing e(True, 12345, "Two") e.Invoke(True, 12345, "Two") e.BeginInvoke(True, 12345, "Two", Nothing, New Object()) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Events_ReferencedBy_HandlesClause() As Task Dim markup = <Text><![CDATA[ Class C Event $$MyEvent(x As Integer, y As String, z As Boolean) Sub MyOtherEventHandler(a As Integer, b As String, c As Boolean) Handles Me.MyEvent End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Event MyEvent(z As Boolean, newIntegerParameter As Integer, y As String) Sub MyOtherEventHandler(c As Boolean, newIntegerParameter As Integer, b As String) Handles Me.MyEvent End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_CustomEvents_ReferencedBy_RaiseEvent() As Task Dim markup = <Text><![CDATA[ Class C Delegate Sub MyDelegate(x As Integer, y As String, z As Boolean) Custom Event $$MyEvent As MyDelegate AddHandler(value As MyDelegate) End AddHandler RemoveHandler(value As MyDelegate) End RemoveHandler RaiseEvent(x As Integer, y As String, z As Boolean) End RaiseEvent End Event Sub M() RaiseEvent MyEvent(1, "Two", True) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Sub MyDelegate(z As Boolean, newIntegerParameter As Integer, y As String) Custom Event MyEvent As MyDelegate AddHandler(value As MyDelegate) End AddHandler RemoveHandler(value As MyDelegate) End RemoveHandler RaiseEvent(z As Boolean, newIntegerParameter As Integer, y As String) End RaiseEvent End Event Sub M() RaiseEvent MyEvent(True, 12345, "Two") End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_CustomEvents_ReferencedBy_AddHandler() As Task Dim markup = <Text><![CDATA[ Class C Delegate Sub MyDelegate(x As Integer, y As String, z As Boolean) Custom Event $$MyEvent As MyDelegate AddHandler(value As MyDelegate) End AddHandler RemoveHandler(value As MyDelegate) End RemoveHandler RaiseEvent(x As Integer, y As String, z As Boolean) End RaiseEvent End Event Sub M() AddHandler MyEvent, AddressOf MyEventHandler End Sub Sub MyEventHandler(a As Integer, b As String, c As Boolean) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Sub MyDelegate(z As Boolean, newIntegerParameter As Integer, y As String) Custom Event MyEvent As MyDelegate AddHandler(value As MyDelegate) End AddHandler RemoveHandler(value As MyDelegate) End RemoveHandler RaiseEvent(z As Boolean, newIntegerParameter As Integer, y As String) End RaiseEvent End Event Sub M() AddHandler MyEvent, AddressOf MyEventHandler End Sub Sub MyEventHandler(c As Boolean, newIntegerParameter As Integer, b As String) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_CustomEvents_ReferencedBy_Invocations() As Task Dim markup = <Text><![CDATA[ Class C Delegate Sub MyDelegate(x As Integer, y As String, z As Boolean) Custom Event $$MyEvent As MyDelegate AddHandler(value As MyDelegate) End AddHandler RemoveHandler(value As MyDelegate) End RemoveHandler RaiseEvent(x As Integer, y As String, z As Boolean) End RaiseEvent End Event Sub M() Dim e As MyDelegate = Nothing e(1, "Two", True) e.Invoke(1, "Two", True) e.BeginInvoke(1, "Two", True, Nothing, New Object()) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Sub MyDelegate(z As Boolean, newIntegerParameter As Integer, y As String) Custom Event MyEvent As MyDelegate AddHandler(value As MyDelegate) End AddHandler RemoveHandler(value As MyDelegate) End RemoveHandler RaiseEvent(z As Boolean, newIntegerParameter As Integer, y As String) End RaiseEvent End Event Sub M() Dim e As MyDelegate = Nothing e(True, 12345, "Two") e.Invoke(True, 12345, "Two") e.BeginInvoke(True, 12345, "Two", Nothing, New Object()) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_CustomEvents_ReferencedBy_HandlesClause() As Task Dim markup = <Text><![CDATA[ Class C Delegate Sub MyDelegate(x As Integer, y As String, z As Boolean) Custom Event $$MyEvent As MyDelegate AddHandler(value As MyDelegate) End AddHandler RemoveHandler(value As MyDelegate) End RemoveHandler RaiseEvent(x As Integer, y As String, z As Boolean) End RaiseEvent End Event Sub MyOtherEventHandler(a As Integer, b As String, c As Boolean) Handles Me.MyEvent End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Sub MyDelegate(z As Boolean, newIntegerParameter As Integer, y As String) Custom Event MyEvent As MyDelegate AddHandler(value As MyDelegate) End AddHandler RemoveHandler(value As MyDelegate) End RemoveHandler RaiseEvent(z As Boolean, newIntegerParameter As Integer, y As String) End RaiseEvent End Event Sub MyOtherEventHandler(c As Boolean, newIntegerParameter As Integer, b As String) Handles Me.MyEvent End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Delegates_Generics() As Task Dim markup = <Text><![CDATA[ Delegate Sub $$MyDelegate(Of T)(t As T) Class C Sub B() Dim d = New MyDelegate(Of Integer)(AddressOf M1) End Sub Sub M1(i As Integer) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer")} Dim expectedUpdatedCode = <Text><![CDATA[ Delegate Sub MyDelegate(Of T)(newIntegerParameter As Integer) Class C Sub B() Dim d = New MyDelegate(Of Integer)(AddressOf M1) End Sub Sub M1(newIntegerParameter As Integer) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.ChangeSignature Imports Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities.ChangeSignature Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ChangeSignature Partial Public Class ChangeSignatureTests Inherits AbstractChangeSignatureTests <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Delegates_ImplicitInvokeCalls() As Task Dim markup = <Text><![CDATA[ Delegate Sub $$MySub(x As Integer, y As String, z As Boolean) Class C Sub M() Dim s As MySub = Nothing s(1, "Two", True) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Delegate Sub MySub(z As Boolean, newIntegerParameter As Integer, y As String) Class C Sub M() Dim s As MySub = Nothing s(True, 12345, "Two") End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode, expectedSelectedIndex:=0) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Delegates_ExplicitInvokeCalls() As Task Dim markup = <Text><![CDATA[ Delegate Sub MySub($$x As Integer, y As String, z As Boolean) Class C Sub M() Dim s As MySub = Nothing s.Invoke(1, "Two", True) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Delegate Sub MySub(z As Boolean, newIntegerParameter As Integer, y As String) Class C Sub M() Dim s As MySub = Nothing s.Invoke(True, 12345, "Two") End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode, expectedSelectedIndex:=0) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Delegates_BeginInvokeCalls() As Task Dim markup = <Text><![CDATA[ Delegate Sub MySub(x As Integer$$, y As String, z As Boolean) Class C Sub M() Dim s As MySub = Nothing s.BeginInvoke(1, "Two", True, Nothing, Nothing) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Delegate Sub MySub(z As Boolean, newIntegerParameter As Integer, y As String) Class C Sub M() Dim s As MySub = Nothing s.BeginInvoke(True, 12345, "Two", Nothing, Nothing) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode, expectedSelectedIndex:=0) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Delegates_SubLambdas() As Task Dim markup = <Text><![CDATA[ Delegate Sub MySub(x As Integer, $$y As String, z As Boolean) Class C Sub M() Dim s As MySub = Nothing s = Sub() End Sub s = Sub(a As Integer, b As String, c As Boolean) End Sub s = Sub(a As Integer, b As String, c As Boolean) System.Console.WriteLine("Test") End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Delegate Sub MySub(z As Boolean, newIntegerParameter As Integer, y As String) Class C Sub M() Dim s As MySub = Nothing s = Sub() End Sub s = Sub(c As Boolean, newIntegerParameter As Integer, b As String) End Sub s = Sub(c As Boolean, newIntegerParameter As Integer, b As String) System.Console.WriteLine("Test") End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode, expectedSelectedIndex:=1) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Delegates_FunctionLambdas() As Task Dim markup = <Text><![CDATA[ Delegate Function MyFunc(x As Integer, y As String, $$z As Boolean) As Integer Class C Sub M() Dim f As MyFunc = Nothing f = Function() Return 1 End Function f = Function(a As Integer, b As String, c As Boolean) Return 1 End Function f = Function(a As Integer, b As String, c As Boolean) 1 End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Delegate Function MyFunc(z As Boolean, newIntegerParameter As Integer, y As String) As Integer Class C Sub M() Dim f As MyFunc = Nothing f = Function() Return 1 End Function f = Function(c As Boolean, newIntegerParameter As Integer, b As String) Return 1 End Function f = Function(c As Boolean, newIntegerParameter As Integer, b As String) 1 End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode, expectedSelectedIndex:=2) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Delegates_ReferencingLambdas_MethodArgument() As Task Dim markup = <Text><![CDATA[ Delegate Function $$MyFunc(x As Integer, y As String, z As Boolean) As Integer Class C Sub M(f As MyFunc) M(Function(a As Integer, b As String, c As Boolean) 1) M(Function(a As Integer, b As String, c As Boolean) Return 1 End Function) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Delegate Function MyFunc(z As Boolean, newIntegerParameter As Integer, y As String) As Integer Class C Sub M(f As MyFunc) M(Function(c As Boolean, newIntegerParameter As Integer, b As String) 1) M(Function(c As Boolean, newIntegerParameter As Integer, b As String) Return 1 End Function) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Delegates_ReferencingLambdas_ReturnValue() As Task Dim markup = <Text><![CDATA[ Delegate Sub $$MySub(x As Integer, y As String, z As Boolean) Class C Function M1() As MySub Return Sub(a As Integer, b As String, c As Boolean) End Sub End Function Function M2() As MySub Return Sub(a As Integer, b As String, c As Boolean) System.Console.WriteLine("Test") End Function End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Delegate Sub MySub(z As Boolean, newIntegerParameter As Integer, y As String) Class C Function M1() As MySub Return Sub(c As Boolean, newIntegerParameter As Integer, b As String) End Sub End Function Function M2() As MySub Return Sub(c As Boolean, newIntegerParameter As Integer, b As String) System.Console.WriteLine("Test") End Function End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Delegates_Recursive() As Task Dim markup = <Text><![CDATA[ Delegate Function $$MyFunc(x As Integer, y As String, z As Boolean) As MyFunc Class C Sub M() Dim f As MyFunc = Nothing f(1, "Two", True)(1, "Two", True)(1, "Two", True)(1, "Two", True) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Delegate Function MyFunc(z As Boolean, newIntegerParameter As Integer, y As String) As MyFunc Class C Sub M() Dim f As MyFunc = Nothing f(True, 12345, "Two")(True, 12345, "Two")(True, 12345, "Two")(True, 12345, "Two") End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Delegates_DocComments() As Task Dim markup = <Text><![CDATA[ ''' <summary> ''' This is <see cref="MyFunc"/>, which has these methods: ''' <see cref="MyFunc.New(Object, System.IntPtr)"/> ''' <see cref="MyFunc.Invoke(Integer, String, Boolean)"/> ''' <see cref="MyFunc.EndInvoke(System.IAsyncResult)"/> ''' <see cref="MyFunc.BeginInvoke(Integer, String, Boolean, System.AsyncCallback, Object)"/> ''' </summary> ''' <param name="x">x!</param> ''' <param name="y">y!</param> ''' <param name="z">z!</param> Delegate Sub $$MyFunc(x As Integer, y As String, z As Boolean) Class C Sub M() Dim f As MyFunc = AddressOf Test End Sub ''' <param name="a"></param> ''' <param name="b"></param> ''' <param name="c"></param> Private Sub Test(a As Integer, b As String, c As Boolean) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ ''' <summary> ''' This is <see cref="MyFunc"/>, which has these methods: ''' <see cref="MyFunc.New(Object, System.IntPtr)"/> ''' <see cref="MyFunc.Invoke(Boolean, Integer, String)"/> ''' <see cref="MyFunc.EndInvoke(System.IAsyncResult)"/> ''' <see cref="MyFunc.BeginInvoke(Boolean, Integer, String, System.AsyncCallback, Object)"/> ''' </summary> ''' <param name="z">z!</param> ''' <param name="newIntegerParameter"></param> ''' <param name="y">y!</param> Delegate Sub MyFunc(z As Boolean, newIntegerParameter As Integer, y As String) Class C Sub M() Dim f As MyFunc = AddressOf Test End Sub ''' <param name="c"></param> ''' <param name="newIntegerParameter"></param> ''' <param name="b"></param> Private Sub Test(c As Boolean, newIntegerParameter As Integer, b As String) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Delegates_Relaxation_FunctionToSub() As Task Dim markup = <Text><![CDATA[ Delegate Sub $$MySub(x As Integer, y As String, z As Boolean) Class C Sub M() Dim f As MySub = AddressOf Test End Sub Private Function Test(a As Integer, b As String, c As Boolean) As Integer Return 1 End Function End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Delegate Sub MySub(z As Boolean, newIntegerParameter As Integer, y As String) Class C Sub M() Dim f As MySub = AddressOf Test End Sub Private Function Test(c As Boolean, newIntegerParameter As Integer, b As String) As Integer Return 1 End Function End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Delegates_Relaxation_ParameterlessFunctionToFunction() As Task Dim markup = <Text><![CDATA[ Delegate Function $$MyFunc(x As Integer, y As String, z As Boolean) As Integer Class C Sub M() Dim f As MyFunc = AddressOf Test End Sub Private Function Test() Return 1 End Function End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Delegate Function MyFunc(z As Boolean, newIntegerParameter As Integer, y As String) As Integer Class C Sub M() Dim f As MyFunc = AddressOf Test End Sub Private Function Test() Return 1 End Function End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Delegates_CascadeToEvents() As Task Dim markup = <Text><![CDATA[ Class C Delegate Sub $$MyDelegate(x As Integer, y As String, z As Boolean) Event MyEvent As MyDelegate Custom Event MyEvent2 As MyDelegate AddHandler(value As MyDelegate) End AddHandler RemoveHandler(value As MyDelegate) End RemoveHandler RaiseEvent(x As Integer, y As String, z As Boolean) End RaiseEvent End Event Sub M() RaiseEvent MyEvent(1, "Two", True) RaiseEvent MyEvent2(1, "Two", True) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Sub MyDelegate(z As Boolean, newIntegerParameter As Integer, y As String) Event MyEvent As MyDelegate Custom Event MyEvent2 As MyDelegate AddHandler(value As MyDelegate) End AddHandler RemoveHandler(value As MyDelegate) End RemoveHandler RaiseEvent(z As Boolean, newIntegerParameter As Integer, y As String) End RaiseEvent End Event Sub M() RaiseEvent MyEvent(True, 12345, "Two") RaiseEvent MyEvent2(True, 12345, "Two") End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Events_ReferencedBy_RaiseEvent() As Task Dim markup = <Text><![CDATA[ Class C Event $$MyEvent(x As Integer, y As String, z As Boolean) Sub M() RaiseEvent MyEvent(1, "Two", True) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Event MyEvent(z As Boolean, newIntegerParameter As Integer, y As String) Sub M() RaiseEvent MyEvent(True, 12345, "Two") End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Events_ReferencedBy_AddHandler() As Task Dim markup = <Text><![CDATA[ Class C Event $$MyEvent(x As Integer, y As String, z As Boolean) Sub M() AddHandler MyEvent, AddressOf MyEventHandler End Sub Sub MyEventHandler(a As Integer, b As String, c As Boolean) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Event MyEvent(z As Boolean, newIntegerParameter As Integer, y As String) Sub M() AddHandler MyEvent, AddressOf MyEventHandler End Sub Sub MyEventHandler(c As Boolean, newIntegerParameter As Integer, b As String) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Events_ReferencedBy_GeneratedDelegateTypeInvocations() As Task Dim markup = <Text><![CDATA[ Class C Event $$MyEvent(x As Integer, y As String, z As Boolean) Sub M() Dim e As MyEventEventHandler = Nothing e(1, "Two", True) e.Invoke(1, "Two", True) e.BeginInvoke(1, "Two", True, Nothing, New Object()) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Event MyEvent(z As Boolean, newIntegerParameter As Integer, y As String) Sub M() Dim e As MyEventEventHandler = Nothing e(True, 12345, "Two") e.Invoke(True, 12345, "Two") e.BeginInvoke(True, 12345, "Two", Nothing, New Object()) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Events_ReferencedBy_HandlesClause() As Task Dim markup = <Text><![CDATA[ Class C Event $$MyEvent(x As Integer, y As String, z As Boolean) Sub MyOtherEventHandler(a As Integer, b As String, c As Boolean) Handles Me.MyEvent End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Event MyEvent(z As Boolean, newIntegerParameter As Integer, y As String) Sub MyOtherEventHandler(c As Boolean, newIntegerParameter As Integer, b As String) Handles Me.MyEvent End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_CustomEvents_ReferencedBy_RaiseEvent() As Task Dim markup = <Text><![CDATA[ Class C Delegate Sub MyDelegate(x As Integer, y As String, z As Boolean) Custom Event $$MyEvent As MyDelegate AddHandler(value As MyDelegate) End AddHandler RemoveHandler(value As MyDelegate) End RemoveHandler RaiseEvent(x As Integer, y As String, z As Boolean) End RaiseEvent End Event Sub M() RaiseEvent MyEvent(1, "Two", True) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Sub MyDelegate(z As Boolean, newIntegerParameter As Integer, y As String) Custom Event MyEvent As MyDelegate AddHandler(value As MyDelegate) End AddHandler RemoveHandler(value As MyDelegate) End RemoveHandler RaiseEvent(z As Boolean, newIntegerParameter As Integer, y As String) End RaiseEvent End Event Sub M() RaiseEvent MyEvent(True, 12345, "Two") End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_CustomEvents_ReferencedBy_AddHandler() As Task Dim markup = <Text><![CDATA[ Class C Delegate Sub MyDelegate(x As Integer, y As String, z As Boolean) Custom Event $$MyEvent As MyDelegate AddHandler(value As MyDelegate) End AddHandler RemoveHandler(value As MyDelegate) End RemoveHandler RaiseEvent(x As Integer, y As String, z As Boolean) End RaiseEvent End Event Sub M() AddHandler MyEvent, AddressOf MyEventHandler End Sub Sub MyEventHandler(a As Integer, b As String, c As Boolean) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Sub MyDelegate(z As Boolean, newIntegerParameter As Integer, y As String) Custom Event MyEvent As MyDelegate AddHandler(value As MyDelegate) End AddHandler RemoveHandler(value As MyDelegate) End RemoveHandler RaiseEvent(z As Boolean, newIntegerParameter As Integer, y As String) End RaiseEvent End Event Sub M() AddHandler MyEvent, AddressOf MyEventHandler End Sub Sub MyEventHandler(c As Boolean, newIntegerParameter As Integer, b As String) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_CustomEvents_ReferencedBy_Invocations() As Task Dim markup = <Text><![CDATA[ Class C Delegate Sub MyDelegate(x As Integer, y As String, z As Boolean) Custom Event $$MyEvent As MyDelegate AddHandler(value As MyDelegate) End AddHandler RemoveHandler(value As MyDelegate) End RemoveHandler RaiseEvent(x As Integer, y As String, z As Boolean) End RaiseEvent End Event Sub M() Dim e As MyDelegate = Nothing e(1, "Two", True) e.Invoke(1, "Two", True) e.BeginInvoke(1, "Two", True, Nothing, New Object()) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Sub MyDelegate(z As Boolean, newIntegerParameter As Integer, y As String) Custom Event MyEvent As MyDelegate AddHandler(value As MyDelegate) End AddHandler RemoveHandler(value As MyDelegate) End RemoveHandler RaiseEvent(z As Boolean, newIntegerParameter As Integer, y As String) End RaiseEvent End Event Sub M() Dim e As MyDelegate = Nothing e(True, 12345, "Two") e.Invoke(True, 12345, "Two") e.BeginInvoke(True, 12345, "Two", Nothing, New Object()) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_CustomEvents_ReferencedBy_HandlesClause() As Task Dim markup = <Text><![CDATA[ Class C Delegate Sub MyDelegate(x As Integer, y As String, z As Boolean) Custom Event $$MyEvent As MyDelegate AddHandler(value As MyDelegate) End AddHandler RemoveHandler(value As MyDelegate) End RemoveHandler RaiseEvent(x As Integer, y As String, z As Boolean) End RaiseEvent End Event Sub MyOtherEventHandler(a As Integer, b As String, c As Boolean) Handles Me.MyEvent End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(2), New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer"), New AddedParameterOrExistingIndex(1)} Dim expectedUpdatedCode = <Text><![CDATA[ Class C Delegate Sub MyDelegate(z As Boolean, newIntegerParameter As Integer, y As String) Custom Event MyEvent As MyDelegate AddHandler(value As MyDelegate) End AddHandler RemoveHandler(value As MyDelegate) End RemoveHandler RaiseEvent(z As Boolean, newIntegerParameter As Integer, y As String) End RaiseEvent End Event Sub MyOtherEventHandler(c As Boolean, newIntegerParameter As Integer, b As String) Handles Me.MyEvent End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function <Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function TestAddParameter_Delegates_Generics() As Task Dim markup = <Text><![CDATA[ Delegate Sub $$MyDelegate(Of T)(t As T) Class C Sub B() Dim d = New MyDelegate(Of Integer)(AddressOf M1) End Sub Sub M1(i As Integer) End Sub End Class ]]></Text>.NormalizedValue() Dim updatedSignature = { New AddedParameterOrExistingIndex(New AddedParameter(Nothing, "Integer", "newIntegerParameter", CallSiteKind.Value, "12345"), "Integer")} Dim expectedUpdatedCode = <Text><![CDATA[ Delegate Sub MyDelegate(Of T)(newIntegerParameter As Integer) Class C Sub B() Dim d = New MyDelegate(Of Integer)(AddressOf M1) End Sub Sub M1(newIntegerParameter As Integer) End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=expectedUpdatedCode) End Function End Class End Namespace
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/Remote/ServiceHub/Services/TodoCommentsDiscovery/RemoteTodoCommentsIncrementalAnalyzerProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.SolutionCrawler; using Microsoft.CodeAnalysis.TodoComments; using Microsoft.ServiceHub.Framework; namespace Microsoft.CodeAnalysis.Remote { /// <remarks>Note: this is explicitly <b>not</b> exported. We don't want the <see /// cref="RemoteWorkspace"/> to automatically load this. Instead, VS waits until it is ready /// and then calls into OOP to tell it to start analyzing the solution. At that point we'll get /// created and added to the solution crawler. /// </remarks> internal sealed class RemoteTodoCommentsIncrementalAnalyzerProvider : IIncrementalAnalyzerProvider { private readonly RemoteCallback<IRemoteTodoCommentsDiscoveryService.ICallback> _callback; private readonly RemoteServiceCallbackId _callbackId; public RemoteTodoCommentsIncrementalAnalyzerProvider(RemoteCallback<IRemoteTodoCommentsDiscoveryService.ICallback> callback, RemoteServiceCallbackId callbackId) { _callback = callback; _callbackId = callbackId; } public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) => new RemoteTodoCommentsIncrementalAnalyzer(_callback, _callbackId); } }
// Licensed to the .NET Foundation under one or more agreements. // 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.SolutionCrawler; using Microsoft.CodeAnalysis.TodoComments; using Microsoft.ServiceHub.Framework; namespace Microsoft.CodeAnalysis.Remote { /// <remarks>Note: this is explicitly <b>not</b> exported. We don't want the <see /// cref="RemoteWorkspace"/> to automatically load this. Instead, VS waits until it is ready /// and then calls into OOP to tell it to start analyzing the solution. At that point we'll get /// created and added to the solution crawler. /// </remarks> internal sealed class RemoteTodoCommentsIncrementalAnalyzerProvider : IIncrementalAnalyzerProvider { private readonly RemoteCallback<IRemoteTodoCommentsDiscoveryService.ICallback> _callback; private readonly RemoteServiceCallbackId _callbackId; public RemoteTodoCommentsIncrementalAnalyzerProvider(RemoteCallback<IRemoteTodoCommentsDiscoveryService.ICallback> callback, RemoteServiceCallbackId callbackId) { _callback = callback; _callbackId = callbackId; } public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) => new RemoteTodoCommentsIncrementalAnalyzer(_callback, _callbackId); } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/EvaluationContext.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Threading; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.DiaSymReader; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal sealed class EvaluationContext : EvaluationContextBase { private const string TypeName = "<>x"; private const string MethodName = "<>m0"; internal const bool IsLocalScopeEndInclusive = false; internal readonly MethodContextReuseConstraints? MethodContextReuseConstraints; internal readonly CSharpCompilation Compilation; private readonly MethodSymbol _currentFrame; private readonly MethodSymbol? _currentSourceMethod; private readonly ImmutableArray<LocalSymbol> _locals; private readonly ImmutableSortedSet<int> _inScopeHoistedLocalSlots; private readonly MethodDebugInfo<TypeSymbol, LocalSymbol> _methodDebugInfo; private EvaluationContext( MethodContextReuseConstraints? methodContextReuseConstraints, CSharpCompilation compilation, MethodSymbol currentFrame, MethodSymbol? currentSourceMethod, ImmutableArray<LocalSymbol> locals, ImmutableSortedSet<int> inScopeHoistedLocalSlots, MethodDebugInfo<TypeSymbol, LocalSymbol> methodDebugInfo) { RoslynDebug.AssertNotNull(inScopeHoistedLocalSlots); RoslynDebug.AssertNotNull(methodDebugInfo); MethodContextReuseConstraints = methodContextReuseConstraints; Compilation = compilation; _currentFrame = currentFrame; _currentSourceMethod = currentSourceMethod; _locals = locals; _inScopeHoistedLocalSlots = inScopeHoistedLocalSlots; _methodDebugInfo = methodDebugInfo; } /// <summary> /// Create a context for evaluating expressions at a type scope. /// </summary> /// <param name="compilation">Compilation.</param> /// <param name="moduleVersionId">Module containing type</param> /// <param name="typeToken">Type metadata token</param> /// <returns>Evaluation context</returns> /// <remarks> /// No locals since locals are associated with methods, not types. /// </remarks> internal static EvaluationContext CreateTypeContext( CSharpCompilation compilation, Guid moduleVersionId, int typeToken) { Debug.Assert(MetadataTokens.Handle(typeToken).Kind == HandleKind.TypeDefinition); var currentType = compilation.GetType(moduleVersionId, typeToken); RoslynDebug.Assert(currentType is object); var currentFrame = new SynthesizedContextMethodSymbol(currentType); return new EvaluationContext( null, compilation, currentFrame, currentSourceMethod: null, locals: default, inScopeHoistedLocalSlots: ImmutableSortedSet<int>.Empty, methodDebugInfo: MethodDebugInfo<TypeSymbol, LocalSymbol>.None); } /// <summary> /// Create a context for evaluating expressions within a method scope. /// </summary> /// <param name="metadataBlocks">Module metadata</param> /// <param name="symReader"><see cref="ISymUnmanagedReader"/> for PDB associated with <paramref name="moduleVersionId"/></param> /// <param name="moduleVersionId">Module containing method</param> /// <param name="methodToken">Method metadata token</param> /// <param name="methodVersion">Method version.</param> /// <param name="ilOffset">IL offset of instruction pointer in method</param> /// <param name="localSignatureToken">Method local signature token</param> /// <returns>Evaluation context</returns> internal static EvaluationContext CreateMethodContext( ImmutableArray<MetadataBlock> metadataBlocks, object symReader, Guid moduleVersionId, int methodToken, int methodVersion, uint ilOffset, int localSignatureToken) { var offset = NormalizeILOffset(ilOffset); var compilation = metadataBlocks.ToCompilation(moduleVersionId: default, MakeAssemblyReferencesKind.AllAssemblies); return CreateMethodContext( compilation, symReader, moduleVersionId, methodToken, methodVersion, offset, localSignatureToken); } /// <summary> /// Create a context for evaluating expressions within a method scope. /// </summary> /// <param name="compilation">Compilation.</param> /// <param name="symReader"><see cref="ISymUnmanagedReader"/> for PDB associated with <paramref name="moduleVersionId"/></param> /// <param name="moduleVersionId">Module containing method</param> /// <param name="methodToken">Method metadata token</param> /// <param name="methodVersion">Method version.</param> /// <param name="ilOffset">IL offset of instruction pointer in method</param> /// <param name="localSignatureToken">Method local signature token</param> /// <returns>Evaluation context</returns> internal static EvaluationContext CreateMethodContext( CSharpCompilation compilation, object? symReader, Guid moduleVersionId, int methodToken, int methodVersion, int ilOffset, int localSignatureToken) { var methodHandle = (MethodDefinitionHandle)MetadataTokens.Handle(methodToken); var currentSourceMethod = compilation.GetSourceMethod(moduleVersionId, methodHandle); var localSignatureHandle = (localSignatureToken != 0) ? (StandaloneSignatureHandle)MetadataTokens.Handle(localSignatureToken) : default; var currentFrame = compilation.GetMethod(moduleVersionId, methodHandle); RoslynDebug.AssertNotNull(currentFrame); var symbolProvider = new CSharpEESymbolProvider(compilation.SourceAssembly, (PEModuleSymbol)currentFrame.ContainingModule, currentFrame); var metadataDecoder = new MetadataDecoder((PEModuleSymbol)currentFrame.ContainingModule, currentFrame); var localInfo = metadataDecoder.GetLocalInfo(localSignatureHandle); var typedSymReader = (ISymUnmanagedReader3?)symReader; var debugInfo = MethodDebugInfo<TypeSymbol, LocalSymbol>.ReadMethodDebugInfo(typedSymReader, symbolProvider, methodToken, methodVersion, ilOffset, isVisualBasicMethod: false); var reuseSpan = debugInfo.ReuseSpan; var localsBuilder = ArrayBuilder<LocalSymbol>.GetInstance(); MethodDebugInfo<TypeSymbol, LocalSymbol>.GetLocals( localsBuilder, symbolProvider, debugInfo.LocalVariableNames, localInfo, debugInfo.DynamicLocalMap, debugInfo.TupleLocalMap); var inScopeHoistedLocals = debugInfo.GetInScopeHoistedLocalIndices(ilOffset, ref reuseSpan); localsBuilder.AddRange(debugInfo.LocalConstants); return new EvaluationContext( new MethodContextReuseConstraints(moduleVersionId, methodToken, methodVersion, reuseSpan), compilation, currentFrame, currentSourceMethod, localsBuilder.ToImmutableAndFree(), inScopeHoistedLocals, debugInfo); } internal CompilationContext CreateCompilationContext() { return new CompilationContext( Compilation, _currentFrame, _currentSourceMethod, _locals, _inScopeHoistedLocalSlots, _methodDebugInfo); } /// <summary> /// Compile a collection of expressions at the same location. If all expressions /// compile successfully, a single assembly is returned along with the method /// tokens for the expression evaluation methods. If there are errors compiling /// any expression, null is returned along with the collection of error messages /// for all expressions. /// </summary> /// <remarks> /// Errors are returned as a single collection rather than grouped by expression /// since some errors (such as those detected during emit) are not easily /// attributed to a particular expression. /// </remarks> internal byte[]? CompileExpressions( ImmutableArray<string> expressions, out ImmutableArray<int> methodTokens, out ImmutableArray<string> errorMessages) { var diagnostics = DiagnosticBag.GetInstance(); var syntaxNodes = expressions.SelectAsArray(expr => Parse(expr, treatAsExpression: true, diagnostics, out var formatSpecifiers)); byte[]? assembly = null; if (!diagnostics.HasAnyErrors()) { RoslynDebug.Assert(syntaxNodes.All(s => s != null)); var context = CreateCompilationContext(); if (context.TryCompileExpressions(syntaxNodes!, TypeName, MethodName, diagnostics, out var moduleBuilder)) { using var stream = new MemoryStream(); Cci.PeWriter.WritePeToStream( new EmitContext(moduleBuilder, null, diagnostics, metadataOnly: false, includePrivateMembers: true), context.MessageProvider, () => stream, getPortablePdbStreamOpt: null, nativePdbWriterOpt: null, pdbPathOpt: null, metadataOnly: false, isDeterministic: false, emitTestCoverageData: false, privateKeyOpt: null, CancellationToken.None); if (!diagnostics.HasAnyErrors()) { assembly = stream.ToArray(); } } } if (assembly == null) { methodTokens = ImmutableArray<int>.Empty; errorMessages = ImmutableArray.CreateRange( diagnostics.AsEnumerable(). Where(d => d.Severity == DiagnosticSeverity.Error). Select(d => GetErrorMessage(d, CSharpDiagnosticFormatter.Instance, preferredUICulture: null))); } else { methodTokens = MetadataUtilities.GetSynthesizedMethods(assembly, MethodName); Debug.Assert(methodTokens.Length == expressions.Length); errorMessages = ImmutableArray<string>.Empty; } diagnostics.Free(); return assembly; } internal override CompileResult? CompileExpression( string expr, DkmEvaluationFlags compilationFlags, ImmutableArray<Alias> aliases, DiagnosticBag diagnostics, out ResultProperties resultProperties, CompilationTestData? testData) { var syntax = Parse(expr, (compilationFlags & DkmEvaluationFlags.TreatAsExpression) != 0, diagnostics, out var formatSpecifiers); if (syntax == null) { resultProperties = default; return null; } var context = CreateCompilationContext(); if (!context.TryCompileExpression(syntax, TypeName, MethodName, aliases, testData, diagnostics, out var moduleBuilder, out var synthesizedMethod)) { resultProperties = default; return null; } using var stream = new MemoryStream(); Cci.PeWriter.WritePeToStream( new EmitContext(moduleBuilder, null, diagnostics, metadataOnly: false, includePrivateMembers: true), context.MessageProvider, () => stream, getPortablePdbStreamOpt: null, nativePdbWriterOpt: null, pdbPathOpt: null, metadataOnly: false, isDeterministic: false, emitTestCoverageData: false, privateKeyOpt: null, CancellationToken.None); if (diagnostics.HasAnyErrors()) { resultProperties = default; return null; } Debug.Assert(synthesizedMethod.ContainingType.MetadataName == TypeName); Debug.Assert(synthesizedMethod.MetadataName == MethodName); resultProperties = synthesizedMethod.ResultProperties; return new CSharpCompileResult( stream.ToArray(), synthesizedMethod, formatSpecifiers: formatSpecifiers); } private static CSharpSyntaxNode? Parse( string expr, bool treatAsExpression, DiagnosticBag diagnostics, out ReadOnlyCollection<string>? formatSpecifiers) { if (!treatAsExpression) { // Try to parse as a statement. If that fails, parse as an expression. var statementDiagnostics = DiagnosticBag.GetInstance(); var statementSyntax = expr.ParseStatement(statementDiagnostics); Debug.Assert((statementSyntax == null) || !statementDiagnostics.HasAnyErrors()); statementDiagnostics.Free(); var isExpressionStatement = statementSyntax.IsKind(SyntaxKind.ExpressionStatement); if (statementSyntax != null && !isExpressionStatement) { formatSpecifiers = null; if (statementSyntax.IsKind(SyntaxKind.LocalDeclarationStatement)) { return statementSyntax; } diagnostics.Add(ErrorCode.ERR_ExpressionOrDeclarationExpected, Location.None); return null; } } return expr.ParseExpression(diagnostics, allowFormatSpecifiers: true, out formatSpecifiers); } internal override CompileResult? CompileAssignment( string target, string expr, ImmutableArray<Alias> aliases, DiagnosticBag diagnostics, out ResultProperties resultProperties, CompilationTestData? testData) { var assignment = target.ParseAssignment(expr, diagnostics); if (assignment == null) { resultProperties = default; return null; } var context = CreateCompilationContext(); if (!context.TryCompileAssignment(assignment, TypeName, MethodName, aliases, testData, diagnostics, out var moduleBuilder, out var synthesizedMethod)) { resultProperties = default; return null; } using var stream = new MemoryStream(); Cci.PeWriter.WritePeToStream( new EmitContext(moduleBuilder, null, diagnostics, metadataOnly: false, includePrivateMembers: true), context.MessageProvider, () => stream, getPortablePdbStreamOpt: null, nativePdbWriterOpt: null, pdbPathOpt: null, metadataOnly: false, isDeterministic: false, emitTestCoverageData: false, privateKeyOpt: null, CancellationToken.None); if (diagnostics.HasAnyErrors()) { resultProperties = default; return null; } Debug.Assert(synthesizedMethod.ContainingType.MetadataName == TypeName); Debug.Assert(synthesizedMethod.MetadataName == MethodName); resultProperties = synthesizedMethod.ResultProperties; return new CSharpCompileResult( stream.ToArray(), synthesizedMethod, formatSpecifiers: null); } private static readonly ReadOnlyCollection<byte> s_emptyBytes = new ReadOnlyCollection<byte>(Array.Empty<byte>()); internal override ReadOnlyCollection<byte> CompileGetLocals( ArrayBuilder<LocalAndMethod> locals, bool argumentsOnly, ImmutableArray<Alias> aliases, DiagnosticBag diagnostics, out string typeName, CompilationTestData? testData) { var context = CreateCompilationContext(); var moduleBuilder = context.CompileGetLocals(TypeName, locals, argumentsOnly, aliases, testData, diagnostics); ReadOnlyCollection<byte>? assembly = null; if (moduleBuilder != null && locals.Count > 0) { using var stream = new MemoryStream(); Cci.PeWriter.WritePeToStream( new EmitContext(moduleBuilder, null, diagnostics, metadataOnly: false, includePrivateMembers: true), context.MessageProvider, () => stream, getPortablePdbStreamOpt: null, nativePdbWriterOpt: null, pdbPathOpt: null, metadataOnly: false, isDeterministic: false, emitTestCoverageData: false, privateKeyOpt: null, CancellationToken.None); if (!diagnostics.HasAnyErrors()) { assembly = new ReadOnlyCollection<byte>(stream.ToArray()); } } if (assembly == null) { locals.Clear(); assembly = s_emptyBytes; } typeName = TypeName; return assembly; } internal override bool HasDuplicateTypesOrAssemblies(Diagnostic diagnostic) { switch ((ErrorCode)diagnostic.Code) { case ErrorCode.ERR_DuplicateImport: case ErrorCode.ERR_DuplicateImportSimple: case ErrorCode.ERR_SameFullNameAggAgg: case ErrorCode.ERR_AmbigCall: return true; default: return false; } } internal override ImmutableArray<AssemblyIdentity> GetMissingAssemblyIdentities(Diagnostic diagnostic, AssemblyIdentity linqLibrary) { return GetMissingAssemblyIdentitiesHelper((ErrorCode)diagnostic.Code, diagnostic.Arguments, linqLibrary); } /// <remarks> /// Internal for testing. /// </remarks> internal static ImmutableArray<AssemblyIdentity> GetMissingAssemblyIdentitiesHelper(ErrorCode code, IReadOnlyList<object?> arguments, AssemblyIdentity linqLibrary) { RoslynDebug.AssertNotNull(linqLibrary); switch (code) { case ErrorCode.ERR_NoTypeDef: case ErrorCode.ERR_GlobalSingleTypeNameNotFoundFwd: case ErrorCode.ERR_DottedTypeNameNotFoundInNSFwd: case ErrorCode.ERR_SingleTypeNameNotFoundFwd: case ErrorCode.ERR_NameNotInContextPossibleMissingReference: // Probably can't happen. foreach (var argument in arguments) { var identity = (argument as AssemblyIdentity) ?? (argument as AssemblySymbol)?.Identity; if (identity != null && !identity.Equals(MissingCorLibrarySymbol.Instance.Identity)) { return ImmutableArray.Create(identity); } } break; case ErrorCode.ERR_DottedTypeNameNotFoundInNS: if (arguments.Count == 2 && arguments[0] is string namespaceName && arguments[1] is NamespaceSymbol containingNamespace && containingNamespace.ConstituentNamespaces.Any(n => n.ContainingAssembly.Identity.IsWindowsAssemblyIdentity())) { // This is just a heuristic, but it has the advantage of being portable, particularly // across different versions of (desktop) windows. var identity = new AssemblyIdentity($"{containingNamespace.ToDisplayString()}.{namespaceName}", contentType: System.Reflection.AssemblyContentType.WindowsRuntime); return ImmutableArray.Create(identity); } break; case ErrorCode.ERR_NoSuchMemberOrExtension: // Commonly, but not always, caused by absence of System.Core. case ErrorCode.ERR_DynamicAttributeMissing: case ErrorCode.ERR_DynamicRequiredTypesMissing: // MSDN says these might come from System.Dynamic.Runtime case ErrorCode.ERR_QueryNoProviderStandard: case ErrorCode.ERR_ExtensionAttrNotFound: // Probably can't happen. return ImmutableArray.Create(linqLibrary); case ErrorCode.ERR_BadAwaitArg_NeedSystem: Debug.Assert(false, "Roslyn no longer produces ERR_BadAwaitArg_NeedSystem"); break; } return 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; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Threading; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.DiaSymReader; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal sealed class EvaluationContext : EvaluationContextBase { private const string TypeName = "<>x"; private const string MethodName = "<>m0"; internal const bool IsLocalScopeEndInclusive = false; internal readonly MethodContextReuseConstraints? MethodContextReuseConstraints; internal readonly CSharpCompilation Compilation; private readonly MethodSymbol _currentFrame; private readonly MethodSymbol? _currentSourceMethod; private readonly ImmutableArray<LocalSymbol> _locals; private readonly ImmutableSortedSet<int> _inScopeHoistedLocalSlots; private readonly MethodDebugInfo<TypeSymbol, LocalSymbol> _methodDebugInfo; private EvaluationContext( MethodContextReuseConstraints? methodContextReuseConstraints, CSharpCompilation compilation, MethodSymbol currentFrame, MethodSymbol? currentSourceMethod, ImmutableArray<LocalSymbol> locals, ImmutableSortedSet<int> inScopeHoistedLocalSlots, MethodDebugInfo<TypeSymbol, LocalSymbol> methodDebugInfo) { RoslynDebug.AssertNotNull(inScopeHoistedLocalSlots); RoslynDebug.AssertNotNull(methodDebugInfo); MethodContextReuseConstraints = methodContextReuseConstraints; Compilation = compilation; _currentFrame = currentFrame; _currentSourceMethod = currentSourceMethod; _locals = locals; _inScopeHoistedLocalSlots = inScopeHoistedLocalSlots; _methodDebugInfo = methodDebugInfo; } /// <summary> /// Create a context for evaluating expressions at a type scope. /// </summary> /// <param name="compilation">Compilation.</param> /// <param name="moduleVersionId">Module containing type</param> /// <param name="typeToken">Type metadata token</param> /// <returns>Evaluation context</returns> /// <remarks> /// No locals since locals are associated with methods, not types. /// </remarks> internal static EvaluationContext CreateTypeContext( CSharpCompilation compilation, Guid moduleVersionId, int typeToken) { Debug.Assert(MetadataTokens.Handle(typeToken).Kind == HandleKind.TypeDefinition); var currentType = compilation.GetType(moduleVersionId, typeToken); RoslynDebug.Assert(currentType is object); var currentFrame = new SynthesizedContextMethodSymbol(currentType); return new EvaluationContext( null, compilation, currentFrame, currentSourceMethod: null, locals: default, inScopeHoistedLocalSlots: ImmutableSortedSet<int>.Empty, methodDebugInfo: MethodDebugInfo<TypeSymbol, LocalSymbol>.None); } /// <summary> /// Create a context for evaluating expressions within a method scope. /// </summary> /// <param name="metadataBlocks">Module metadata</param> /// <param name="symReader"><see cref="ISymUnmanagedReader"/> for PDB associated with <paramref name="moduleVersionId"/></param> /// <param name="moduleVersionId">Module containing method</param> /// <param name="methodToken">Method metadata token</param> /// <param name="methodVersion">Method version.</param> /// <param name="ilOffset">IL offset of instruction pointer in method</param> /// <param name="localSignatureToken">Method local signature token</param> /// <returns>Evaluation context</returns> internal static EvaluationContext CreateMethodContext( ImmutableArray<MetadataBlock> metadataBlocks, object symReader, Guid moduleVersionId, int methodToken, int methodVersion, uint ilOffset, int localSignatureToken) { var offset = NormalizeILOffset(ilOffset); var compilation = metadataBlocks.ToCompilation(moduleVersionId: default, MakeAssemblyReferencesKind.AllAssemblies); return CreateMethodContext( compilation, symReader, moduleVersionId, methodToken, methodVersion, offset, localSignatureToken); } /// <summary> /// Create a context for evaluating expressions within a method scope. /// </summary> /// <param name="compilation">Compilation.</param> /// <param name="symReader"><see cref="ISymUnmanagedReader"/> for PDB associated with <paramref name="moduleVersionId"/></param> /// <param name="moduleVersionId">Module containing method</param> /// <param name="methodToken">Method metadata token</param> /// <param name="methodVersion">Method version.</param> /// <param name="ilOffset">IL offset of instruction pointer in method</param> /// <param name="localSignatureToken">Method local signature token</param> /// <returns>Evaluation context</returns> internal static EvaluationContext CreateMethodContext( CSharpCompilation compilation, object? symReader, Guid moduleVersionId, int methodToken, int methodVersion, int ilOffset, int localSignatureToken) { var methodHandle = (MethodDefinitionHandle)MetadataTokens.Handle(methodToken); var currentSourceMethod = compilation.GetSourceMethod(moduleVersionId, methodHandle); var localSignatureHandle = (localSignatureToken != 0) ? (StandaloneSignatureHandle)MetadataTokens.Handle(localSignatureToken) : default; var currentFrame = compilation.GetMethod(moduleVersionId, methodHandle); RoslynDebug.AssertNotNull(currentFrame); var symbolProvider = new CSharpEESymbolProvider(compilation.SourceAssembly, (PEModuleSymbol)currentFrame.ContainingModule, currentFrame); var metadataDecoder = new MetadataDecoder((PEModuleSymbol)currentFrame.ContainingModule, currentFrame); var localInfo = metadataDecoder.GetLocalInfo(localSignatureHandle); var typedSymReader = (ISymUnmanagedReader3?)symReader; var debugInfo = MethodDebugInfo<TypeSymbol, LocalSymbol>.ReadMethodDebugInfo(typedSymReader, symbolProvider, methodToken, methodVersion, ilOffset, isVisualBasicMethod: false); var reuseSpan = debugInfo.ReuseSpan; var localsBuilder = ArrayBuilder<LocalSymbol>.GetInstance(); MethodDebugInfo<TypeSymbol, LocalSymbol>.GetLocals( localsBuilder, symbolProvider, debugInfo.LocalVariableNames, localInfo, debugInfo.DynamicLocalMap, debugInfo.TupleLocalMap); var inScopeHoistedLocals = debugInfo.GetInScopeHoistedLocalIndices(ilOffset, ref reuseSpan); localsBuilder.AddRange(debugInfo.LocalConstants); return new EvaluationContext( new MethodContextReuseConstraints(moduleVersionId, methodToken, methodVersion, reuseSpan), compilation, currentFrame, currentSourceMethod, localsBuilder.ToImmutableAndFree(), inScopeHoistedLocals, debugInfo); } internal CompilationContext CreateCompilationContext() { return new CompilationContext( Compilation, _currentFrame, _currentSourceMethod, _locals, _inScopeHoistedLocalSlots, _methodDebugInfo); } /// <summary> /// Compile a collection of expressions at the same location. If all expressions /// compile successfully, a single assembly is returned along with the method /// tokens for the expression evaluation methods. If there are errors compiling /// any expression, null is returned along with the collection of error messages /// for all expressions. /// </summary> /// <remarks> /// Errors are returned as a single collection rather than grouped by expression /// since some errors (such as those detected during emit) are not easily /// attributed to a particular expression. /// </remarks> internal byte[]? CompileExpressions( ImmutableArray<string> expressions, out ImmutableArray<int> methodTokens, out ImmutableArray<string> errorMessages) { var diagnostics = DiagnosticBag.GetInstance(); var syntaxNodes = expressions.SelectAsArray(expr => Parse(expr, treatAsExpression: true, diagnostics, out var formatSpecifiers)); byte[]? assembly = null; if (!diagnostics.HasAnyErrors()) { RoslynDebug.Assert(syntaxNodes.All(s => s != null)); var context = CreateCompilationContext(); if (context.TryCompileExpressions(syntaxNodes!, TypeName, MethodName, diagnostics, out var moduleBuilder)) { using var stream = new MemoryStream(); Cci.PeWriter.WritePeToStream( new EmitContext(moduleBuilder, null, diagnostics, metadataOnly: false, includePrivateMembers: true), context.MessageProvider, () => stream, getPortablePdbStreamOpt: null, nativePdbWriterOpt: null, pdbPathOpt: null, metadataOnly: false, isDeterministic: false, emitTestCoverageData: false, privateKeyOpt: null, CancellationToken.None); if (!diagnostics.HasAnyErrors()) { assembly = stream.ToArray(); } } } if (assembly == null) { methodTokens = ImmutableArray<int>.Empty; errorMessages = ImmutableArray.CreateRange( diagnostics.AsEnumerable(). Where(d => d.Severity == DiagnosticSeverity.Error). Select(d => GetErrorMessage(d, CSharpDiagnosticFormatter.Instance, preferredUICulture: null))); } else { methodTokens = MetadataUtilities.GetSynthesizedMethods(assembly, MethodName); Debug.Assert(methodTokens.Length == expressions.Length); errorMessages = ImmutableArray<string>.Empty; } diagnostics.Free(); return assembly; } internal override CompileResult? CompileExpression( string expr, DkmEvaluationFlags compilationFlags, ImmutableArray<Alias> aliases, DiagnosticBag diagnostics, out ResultProperties resultProperties, CompilationTestData? testData) { var syntax = Parse(expr, (compilationFlags & DkmEvaluationFlags.TreatAsExpression) != 0, diagnostics, out var formatSpecifiers); if (syntax == null) { resultProperties = default; return null; } var context = CreateCompilationContext(); if (!context.TryCompileExpression(syntax, TypeName, MethodName, aliases, testData, diagnostics, out var moduleBuilder, out var synthesizedMethod)) { resultProperties = default; return null; } using var stream = new MemoryStream(); Cci.PeWriter.WritePeToStream( new EmitContext(moduleBuilder, null, diagnostics, metadataOnly: false, includePrivateMembers: true), context.MessageProvider, () => stream, getPortablePdbStreamOpt: null, nativePdbWriterOpt: null, pdbPathOpt: null, metadataOnly: false, isDeterministic: false, emitTestCoverageData: false, privateKeyOpt: null, CancellationToken.None); if (diagnostics.HasAnyErrors()) { resultProperties = default; return null; } Debug.Assert(synthesizedMethod.ContainingType.MetadataName == TypeName); Debug.Assert(synthesizedMethod.MetadataName == MethodName); resultProperties = synthesizedMethod.ResultProperties; return new CSharpCompileResult( stream.ToArray(), synthesizedMethod, formatSpecifiers: formatSpecifiers); } private static CSharpSyntaxNode? Parse( string expr, bool treatAsExpression, DiagnosticBag diagnostics, out ReadOnlyCollection<string>? formatSpecifiers) { if (!treatAsExpression) { // Try to parse as a statement. If that fails, parse as an expression. var statementDiagnostics = DiagnosticBag.GetInstance(); var statementSyntax = expr.ParseStatement(statementDiagnostics); Debug.Assert((statementSyntax == null) || !statementDiagnostics.HasAnyErrors()); statementDiagnostics.Free(); var isExpressionStatement = statementSyntax.IsKind(SyntaxKind.ExpressionStatement); if (statementSyntax != null && !isExpressionStatement) { formatSpecifiers = null; if (statementSyntax.IsKind(SyntaxKind.LocalDeclarationStatement)) { return statementSyntax; } diagnostics.Add(ErrorCode.ERR_ExpressionOrDeclarationExpected, Location.None); return null; } } return expr.ParseExpression(diagnostics, allowFormatSpecifiers: true, out formatSpecifiers); } internal override CompileResult? CompileAssignment( string target, string expr, ImmutableArray<Alias> aliases, DiagnosticBag diagnostics, out ResultProperties resultProperties, CompilationTestData? testData) { var assignment = target.ParseAssignment(expr, diagnostics); if (assignment == null) { resultProperties = default; return null; } var context = CreateCompilationContext(); if (!context.TryCompileAssignment(assignment, TypeName, MethodName, aliases, testData, diagnostics, out var moduleBuilder, out var synthesizedMethod)) { resultProperties = default; return null; } using var stream = new MemoryStream(); Cci.PeWriter.WritePeToStream( new EmitContext(moduleBuilder, null, diagnostics, metadataOnly: false, includePrivateMembers: true), context.MessageProvider, () => stream, getPortablePdbStreamOpt: null, nativePdbWriterOpt: null, pdbPathOpt: null, metadataOnly: false, isDeterministic: false, emitTestCoverageData: false, privateKeyOpt: null, CancellationToken.None); if (diagnostics.HasAnyErrors()) { resultProperties = default; return null; } Debug.Assert(synthesizedMethod.ContainingType.MetadataName == TypeName); Debug.Assert(synthesizedMethod.MetadataName == MethodName); resultProperties = synthesizedMethod.ResultProperties; return new CSharpCompileResult( stream.ToArray(), synthesizedMethod, formatSpecifiers: null); } private static readonly ReadOnlyCollection<byte> s_emptyBytes = new ReadOnlyCollection<byte>(Array.Empty<byte>()); internal override ReadOnlyCollection<byte> CompileGetLocals( ArrayBuilder<LocalAndMethod> locals, bool argumentsOnly, ImmutableArray<Alias> aliases, DiagnosticBag diagnostics, out string typeName, CompilationTestData? testData) { var context = CreateCompilationContext(); var moduleBuilder = context.CompileGetLocals(TypeName, locals, argumentsOnly, aliases, testData, diagnostics); ReadOnlyCollection<byte>? assembly = null; if (moduleBuilder != null && locals.Count > 0) { using var stream = new MemoryStream(); Cci.PeWriter.WritePeToStream( new EmitContext(moduleBuilder, null, diagnostics, metadataOnly: false, includePrivateMembers: true), context.MessageProvider, () => stream, getPortablePdbStreamOpt: null, nativePdbWriterOpt: null, pdbPathOpt: null, metadataOnly: false, isDeterministic: false, emitTestCoverageData: false, privateKeyOpt: null, CancellationToken.None); if (!diagnostics.HasAnyErrors()) { assembly = new ReadOnlyCollection<byte>(stream.ToArray()); } } if (assembly == null) { locals.Clear(); assembly = s_emptyBytes; } typeName = TypeName; return assembly; } internal override bool HasDuplicateTypesOrAssemblies(Diagnostic diagnostic) { switch ((ErrorCode)diagnostic.Code) { case ErrorCode.ERR_DuplicateImport: case ErrorCode.ERR_DuplicateImportSimple: case ErrorCode.ERR_SameFullNameAggAgg: case ErrorCode.ERR_AmbigCall: return true; default: return false; } } internal override ImmutableArray<AssemblyIdentity> GetMissingAssemblyIdentities(Diagnostic diagnostic, AssemblyIdentity linqLibrary) { return GetMissingAssemblyIdentitiesHelper((ErrorCode)diagnostic.Code, diagnostic.Arguments, linqLibrary); } /// <remarks> /// Internal for testing. /// </remarks> internal static ImmutableArray<AssemblyIdentity> GetMissingAssemblyIdentitiesHelper(ErrorCode code, IReadOnlyList<object?> arguments, AssemblyIdentity linqLibrary) { RoslynDebug.AssertNotNull(linqLibrary); switch (code) { case ErrorCode.ERR_NoTypeDef: case ErrorCode.ERR_GlobalSingleTypeNameNotFoundFwd: case ErrorCode.ERR_DottedTypeNameNotFoundInNSFwd: case ErrorCode.ERR_SingleTypeNameNotFoundFwd: case ErrorCode.ERR_NameNotInContextPossibleMissingReference: // Probably can't happen. foreach (var argument in arguments) { var identity = (argument as AssemblyIdentity) ?? (argument as AssemblySymbol)?.Identity; if (identity != null && !identity.Equals(MissingCorLibrarySymbol.Instance.Identity)) { return ImmutableArray.Create(identity); } } break; case ErrorCode.ERR_DottedTypeNameNotFoundInNS: if (arguments.Count == 2 && arguments[0] is string namespaceName && arguments[1] is NamespaceSymbol containingNamespace && containingNamespace.ConstituentNamespaces.Any(n => n.ContainingAssembly.Identity.IsWindowsAssemblyIdentity())) { // This is just a heuristic, but it has the advantage of being portable, particularly // across different versions of (desktop) windows. var identity = new AssemblyIdentity($"{containingNamespace.ToDisplayString()}.{namespaceName}", contentType: System.Reflection.AssemblyContentType.WindowsRuntime); return ImmutableArray.Create(identity); } break; case ErrorCode.ERR_NoSuchMemberOrExtension: // Commonly, but not always, caused by absence of System.Core. case ErrorCode.ERR_DynamicAttributeMissing: case ErrorCode.ERR_DynamicRequiredTypesMissing: // MSDN says these might come from System.Dynamic.Runtime case ErrorCode.ERR_QueryNoProviderStandard: case ErrorCode.ERR_ExtensionAttrNotFound: // Probably can't happen. return ImmutableArray.Create(linqLibrary); case ErrorCode.ERR_BadAwaitArg_NeedSystem: Debug.Assert(false, "Roslyn no longer produces ERR_BadAwaitArg_NeedSystem"); break; } return default; } } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Analyzers/CSharp/CodeFixes/UseIsNullCheck/CSharpUseIsNullCheckForReferenceEqualsCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Shared.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.UseIsNullCheck; namespace Microsoft.CodeAnalysis.CSharp.UseIsNullCheck { using static SyntaxFactory; [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseIsNullCheckForReferenceEquals), Shared] internal class CSharpUseIsNullCheckForReferenceEqualsCodeFixProvider : AbstractUseIsNullCheckForReferenceEqualsCodeFixProvider<ExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpUseIsNullCheckForReferenceEqualsCodeFixProvider() { } protected override string GetIsNullTitle() => CSharpAnalyzersResources.Use_is_null_check; protected override string GetIsNotNullTitle() => GetIsNullTitle(); private static readonly LiteralExpressionSyntax s_nullLiteralExpression = LiteralExpression(SyntaxKind.NullLiteralExpression); private static readonly ConstantPatternSyntax s_nullLiteralPattern = ConstantPattern(s_nullLiteralExpression); private static SyntaxNode CreateEqualsNullCheck(ExpressionSyntax argument) => BinaryExpression(SyntaxKind.EqualsExpression, argument, s_nullLiteralExpression).Parenthesize(); private static SyntaxNode CreateIsNullCheck(ExpressionSyntax argument) => IsPatternExpression(argument, s_nullLiteralPattern).Parenthesize(); private static SyntaxNode CreateIsNotNullCheck(ExpressionSyntax argument) { var parseOptions = (CSharpParseOptions)argument.SyntaxTree.Options; if (parseOptions.LanguageVersion.IsCSharp9OrAbove()) { return IsPatternExpression( argument, UnaryPattern( Token(SyntaxKind.NotKeyword), s_nullLiteralPattern)).Parenthesize(); } return BinaryExpression( SyntaxKind.IsExpression, argument, PredefinedType(Token(SyntaxKind.ObjectKeyword))).Parenthesize(); } protected override SyntaxNode CreateNullCheck(ExpressionSyntax argument, bool isUnconstrainedGeneric) => isUnconstrainedGeneric ? CreateEqualsNullCheck(argument) : CreateIsNullCheck(argument); protected override SyntaxNode CreateNotNullCheck(ExpressionSyntax argument) => CreateIsNotNullCheck(argument); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Shared.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.UseIsNullCheck; namespace Microsoft.CodeAnalysis.CSharp.UseIsNullCheck { using static SyntaxFactory; [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseIsNullCheckForReferenceEquals), Shared] internal class CSharpUseIsNullCheckForReferenceEqualsCodeFixProvider : AbstractUseIsNullCheckForReferenceEqualsCodeFixProvider<ExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpUseIsNullCheckForReferenceEqualsCodeFixProvider() { } protected override string GetIsNullTitle() => CSharpAnalyzersResources.Use_is_null_check; protected override string GetIsNotNullTitle() => GetIsNullTitle(); private static readonly LiteralExpressionSyntax s_nullLiteralExpression = LiteralExpression(SyntaxKind.NullLiteralExpression); private static readonly ConstantPatternSyntax s_nullLiteralPattern = ConstantPattern(s_nullLiteralExpression); private static SyntaxNode CreateEqualsNullCheck(ExpressionSyntax argument) => BinaryExpression(SyntaxKind.EqualsExpression, argument, s_nullLiteralExpression).Parenthesize(); private static SyntaxNode CreateIsNullCheck(ExpressionSyntax argument) => IsPatternExpression(argument, s_nullLiteralPattern).Parenthesize(); private static SyntaxNode CreateIsNotNullCheck(ExpressionSyntax argument) { var parseOptions = (CSharpParseOptions)argument.SyntaxTree.Options; if (parseOptions.LanguageVersion.IsCSharp9OrAbove()) { return IsPatternExpression( argument, UnaryPattern( Token(SyntaxKind.NotKeyword), s_nullLiteralPattern)).Parenthesize(); } return BinaryExpression( SyntaxKind.IsExpression, argument, PredefinedType(Token(SyntaxKind.ObjectKeyword))).Parenthesize(); } protected override SyntaxNode CreateNullCheck(ExpressionSyntax argument, bool isUnconstrainedGeneric) => isUnconstrainedGeneric ? CreateEqualsNullCheck(argument) : CreateIsNullCheck(argument); protected override SyntaxNode CreateNotNullCheck(ExpressionSyntax argument) => CreateIsNotNullCheck(argument); } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Test/CommandLine/CommandLineTestBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests { public abstract class CommandLineTestBase : CSharpTestBase { public string WorkingDirectory { get; } public string SdkDirectory { get; } public string MscorlibFullPath { get; } public CommandLineTestBase() { WorkingDirectory = TempRoot.Root; SdkDirectory = getSdkDirectory(Temp); MscorlibFullPath = Path.Combine(SdkDirectory, "mscorlib.dll"); // This will return a directory which contains mscorlib for use in the compiler instances created for // this set of tests string getSdkDirectory(TempRoot temp) { if (ExecutionConditionUtil.IsCoreClr) { var dir = temp.CreateDirectory(); File.WriteAllBytes(Path.Combine(dir.Path, "mscorlib.dll"), ResourcesNet461.mscorlib); return dir.Path; } return RuntimeEnvironment.GetRuntimeDirectory(); } } internal CSharpCommandLineArguments DefaultParse(IEnumerable<string> args, string baseDirectory, string sdkDirectory = null, string additionalReferenceDirectories = null) { sdkDirectory = sdkDirectory ?? SdkDirectory; return CSharpCommandLineParser.Default.Parse(args, baseDirectory, sdkDirectory, additionalReferenceDirectories); } internal MockCSharpCompiler CreateCSharpCompiler(string[] args, ImmutableArray<DiagnosticAnalyzer> analyzers = default, ImmutableArray<ISourceGenerator> generators = default, AnalyzerAssemblyLoader loader = null) { return CreateCSharpCompiler(null, WorkingDirectory, args, analyzers, generators, loader); } internal MockCSharpCompiler CreateCSharpCompiler(string responseFile, string workingDirectory, string[] args, ImmutableArray<DiagnosticAnalyzer> analyzers = default, ImmutableArray<ISourceGenerator> generators = default, AnalyzerAssemblyLoader loader = null) { var buildPaths = RuntimeUtilities.CreateBuildPaths(workingDirectory, sdkDirectory: SdkDirectory); return new MockCSharpCompiler(responseFile, buildPaths, args, analyzers, generators, loader); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests { public abstract class CommandLineTestBase : CSharpTestBase { public string WorkingDirectory { get; } public string SdkDirectory { get; } public string MscorlibFullPath { get; } public CommandLineTestBase() { WorkingDirectory = TempRoot.Root; SdkDirectory = getSdkDirectory(Temp); MscorlibFullPath = Path.Combine(SdkDirectory, "mscorlib.dll"); // This will return a directory which contains mscorlib for use in the compiler instances created for // this set of tests string getSdkDirectory(TempRoot temp) { if (ExecutionConditionUtil.IsCoreClr) { var dir = temp.CreateDirectory(); File.WriteAllBytes(Path.Combine(dir.Path, "mscorlib.dll"), ResourcesNet461.mscorlib); return dir.Path; } return RuntimeEnvironment.GetRuntimeDirectory(); } } internal CSharpCommandLineArguments DefaultParse(IEnumerable<string> args, string baseDirectory, string sdkDirectory = null, string additionalReferenceDirectories = null) { sdkDirectory = sdkDirectory ?? SdkDirectory; return CSharpCommandLineParser.Default.Parse(args, baseDirectory, sdkDirectory, additionalReferenceDirectories); } internal MockCSharpCompiler CreateCSharpCompiler(string[] args, ImmutableArray<DiagnosticAnalyzer> analyzers = default, ImmutableArray<ISourceGenerator> generators = default, AnalyzerAssemblyLoader loader = null) { return CreateCSharpCompiler(null, WorkingDirectory, args, analyzers, generators, loader); } internal MockCSharpCompiler CreateCSharpCompiler(string responseFile, string workingDirectory, string[] args, ImmutableArray<DiagnosticAnalyzer> analyzers = default, ImmutableArray<ISourceGenerator> generators = default, AnalyzerAssemblyLoader loader = null) { var buildPaths = RuntimeUtilities.CreateBuildPaths(workingDirectory, sdkDirectory: SdkDirectory); return new MockCSharpCompiler(responseFile, buildPaths, args, analyzers, generators, loader); } } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/RuleSets/VisualStudioRuleSetManager.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.TestHooks; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal sealed partial class VisualStudioRuleSetManager : IWorkspaceService { private readonly IThreadingContext _threadingContext; private readonly FileChangeWatcher _fileChangeWatcher; private readonly IAsynchronousOperationListener _listener; private readonly ReferenceCountedDisposableCache<string, RuleSetFile> _ruleSetFileMap = new(); public VisualStudioRuleSetManager( IThreadingContext threadingContext, FileChangeWatcher fileChangeWatcher, IAsynchronousOperationListener listener) { _threadingContext = threadingContext; _fileChangeWatcher = fileChangeWatcher; _listener = listener; } public IReferenceCountedDisposable<ICacheEntry<string, IRuleSetFile>> GetOrCreateRuleSet(string ruleSetFileFullPath) { var cacheEntry = _ruleSetFileMap.GetOrCreate(ruleSetFileFullPath, static (ruleSetFileFullPath, self) => new RuleSetFile(ruleSetFileFullPath, self), this); // Call InitializeFileTracking outside the lock inside ReferenceCountedDisposableCache, so we don't have requests // for other files blocking behind the initialization of this one. RuleSetFile itself will ensure InitializeFileTracking is locked as appropriate. cacheEntry.Target.Value.InitializeFileTracking(_fileChangeWatcher); return cacheEntry; } private void StopTrackingRuleSetFile(RuleSetFile ruleSetFile) { // We can arrive here in one of two situations: // // 1. The underlying RuleSetFile was disposed by all consumers, and we can try cleaning up our weak reference. This is purely an optimization // to avoid the key/value pair being unnecessarily held. // 2. The RuleSetFile was modified, and we want to get rid of our cache now. Anybody still holding onto the values will dispose at their leaisure, // but it won't really matter anyways since the Dispose() that cleans up file trackers is already done. // // In either case, we can just be lazy and remove the key/value pair. It's possible in the mean time that the rule set had already been removed // (perhaps by a file change), and we're removing a live instance. This is fine, as this doesn't affect correctness: we consider this to be a cache // and if two callers got different copies that's fine. We *could* fetch the item out of the dictionary, check if the item is strong and then compare, // but that seems overkill. _ruleSetFileMap.Evict(ruleSetFile.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. #nullable disable using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.TestHooks; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal sealed partial class VisualStudioRuleSetManager : IWorkspaceService { private readonly IThreadingContext _threadingContext; private readonly FileChangeWatcher _fileChangeWatcher; private readonly IAsynchronousOperationListener _listener; private readonly ReferenceCountedDisposableCache<string, RuleSetFile> _ruleSetFileMap = new(); public VisualStudioRuleSetManager( IThreadingContext threadingContext, FileChangeWatcher fileChangeWatcher, IAsynchronousOperationListener listener) { _threadingContext = threadingContext; _fileChangeWatcher = fileChangeWatcher; _listener = listener; } public IReferenceCountedDisposable<ICacheEntry<string, IRuleSetFile>> GetOrCreateRuleSet(string ruleSetFileFullPath) { var cacheEntry = _ruleSetFileMap.GetOrCreate(ruleSetFileFullPath, static (ruleSetFileFullPath, self) => new RuleSetFile(ruleSetFileFullPath, self), this); // Call InitializeFileTracking outside the lock inside ReferenceCountedDisposableCache, so we don't have requests // for other files blocking behind the initialization of this one. RuleSetFile itself will ensure InitializeFileTracking is locked as appropriate. cacheEntry.Target.Value.InitializeFileTracking(_fileChangeWatcher); return cacheEntry; } private void StopTrackingRuleSetFile(RuleSetFile ruleSetFile) { // We can arrive here in one of two situations: // // 1. The underlying RuleSetFile was disposed by all consumers, and we can try cleaning up our weak reference. This is purely an optimization // to avoid the key/value pair being unnecessarily held. // 2. The RuleSetFile was modified, and we want to get rid of our cache now. Anybody still holding onto the values will dispose at their leaisure, // but it won't really matter anyways since the Dispose() that cleans up file trackers is already done. // // In either case, we can just be lazy and remove the key/value pair. It's possible in the mean time that the rule set had already been removed // (perhaps by a file change), and we're removing a live instance. This is fine, as this doesn't affect correctness: we consider this to be a cache // and if two callers got different copies that's fine. We *could* fetch the item out of the dictionary, check if the item is strong and then compare, // but that seems overkill. _ruleSetFileMap.Evict(ruleSetFile.FilePath); } } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Portable/Errors/CSharpDiagnosticFormatter.cs
// Licensed to the .NET Foundation under one or more 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 { public class CSharpDiagnosticFormatter : DiagnosticFormatter { internal CSharpDiagnosticFormatter() { } public static new CSharpDiagnosticFormatter Instance { get; } = new CSharpDiagnosticFormatter(); } }
// Licensed to the .NET Foundation under one or more 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 { public class CSharpDiagnosticFormatter : DiagnosticFormatter { internal CSharpDiagnosticFormatter() { } public static new CSharpDiagnosticFormatter Instance { get; } = new CSharpDiagnosticFormatter(); } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./docs/analyzers/Using Additional Files.md
Introduction ============ This document covers the following: * Uses of Additional Files * Passing Additional Files on the command line * Specifying an individual item as an `AdditionalFile` in an MSBuild project * Specifying an entire set of items as `AdditionalFile`s in an MSBuild project * Accessing and reading additional files through the `AnalyzerOptions` type * Includes sample analyzers that read additional files Uses ==== Sometimes an analyzer needs access to information that is not available through normal compiler inputs--source files, references, and options. To support these scenarios the C# and Visual Basic compilers can accept additional, non-source text files as inputs. For example, an analyzer may enforce that a set of banned terms is not used within a project, or that every source file has a certain copyright header. The terms or copyright header could be passed to the analyzer as an additional file, rather than being hard-coded in the analyzer itself. On the Command Line =================== On the command line, additional files can be passed using the `/additionalfile` option. For example: ``` csc.exe alpha.cs /additionalfile:terms.txt ``` In a Project File ================= Passing an Individual File -------------------------- To specify an individual project item as an additional file, set the item type to `AdditionalFiles`: ``` XML <ItemGroup> <AdditionalFiles Include="terms.txt" /> </ItemGroup> ``` Passing a Group of Files ------------------------ Sometimes it isn't possible to change the item type, or a whole set of items need to be passed as additional files. In this situation you can update the `AdditionalFileItemNames` property to specify which item types to include. For example, if your analyzer needs access to all .resx files in the project, you can do the following: ``` XML <PropertyGroup> <!-- Update the property to include all EmbeddedResource files --> <AdditionalFileItemNames>$(AdditionalFileItemNames);EmbeddedResource</AdditionalFileItemNames> </PropertyGroup> <ItemGroup> <!-- Existing resource file --> <EmbeddedResource Include="Terms.resx"> ... </EmbeddedResource> </ItemGroup> ``` Accessing Additional Files ========================== The set of additional files can be accessed via the `Options` property of the context object passed to a diagnostic action. For example: ```C# CompilationAnalysisContext context = ...; ImmutableArray<AdditionalText> additionFiles = context.Options.AdditionalFiles; ``` From an `AdditionalText` instance, you can access the path to the file or the contents as a `SourceText`: ``` C# AdditionText additionalFile = ...; string path = additionalFile.Path; SourceText contents = additionalFile.GetText(); ``` Samples ======= Reading a File Line-by-Line --------------------------- This sample reads a simple text file for a set of terms--one per line--that should not be used in type names. ``` C# using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class CheckTermsAnalyzer : DiagnosticAnalyzer { public const string DiagnosticId = "CheckTerms001"; private const string Title = "Type name contains invalid term"; private const string MessageFormat = "The term '{0}' is not allowed in a type name."; private const string Category = "Policy"; private static DiagnosticDescriptor Rule = new DiagnosticDescriptor( DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Error, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } } public override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction(compilationStartContext => { // Find the file with the invalid terms. ImmutableArray<AdditionalText> additionalFiles = compilationStartContext.Options.AdditionalFiles; AdditionalText termsFile = additionalFiles.FirstOrDefault(file => Path.GetFileName(file.Path).Equals("Terms.txt")); if (termsFile != null) { HashSet<string> terms = new HashSet<string>(); // Read the file line-by-line to get the terms. SourceText fileText = termsFile.GetText(compilationStartContext.CancellationToken); foreach (TextLine line in fileText.Lines) { terms.Add(line.ToString()); } // Check every named type for the invalid terms. compilationStartContext.RegisterSymbolAction(symbolAnalysisContext => { INamedTypeSymbol namedTypeSymbol = (INamedTypeSymbol)symbolAnalysisContext.Symbol; string symbolName = namedTypeSymbol.Name; foreach (string term in terms) { if (symbolName.Contains(term)) { symbolAnalysisContext.ReportDiagnostic(Diagnostic.Create(Rule, namedTypeSymbol.Locations[0], term)); } } }, SymbolKind.NamedType); } }); } } ``` Converting a File to a Stream ----------------------------- In cases where an additional file contains structured data (e.g., XML or JSON) the line-by-line access provided by the `SourceText` may not be desirable. One alternative is to convert a `SourceText` to a `string`, by calling `ToString()` on it. This sample demonstrates another alternative: converting a `SourceText` to a `Stream` for consumption by other libraries. The terms file is assumed to have the following format: ``` XML <Terms> <Term>frob</Term> <Term>wizbang</Term> <Term>orange</Term> </Terms> ``` ``` C# using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class CheckTermsXMLAnalyzer : DiagnosticAnalyzer { public const string DiagnosticId = "CheckTerms001"; private const string Title = "Type name contains invalid term"; private const string MessageFormat = "The term '{0}' is not allowed in a type name."; private const string Category = "Policy"; private static DiagnosticDescriptor Rule = new DiagnosticDescriptor( DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Error, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } } public override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction(compilationStartContext => { // Find the file with the invalid terms. ImmutableArray<AdditionalText> additionalFiles = compilationStartContext.Options.AdditionalFiles; AdditionalText termsFile = additionalFiles.FirstOrDefault(file => Path.GetFileName(file.Path).Equals("Terms.xml")); if (termsFile != null) { HashSet<string> terms = new HashSet<string>(); SourceText fileText = termsFile.GetText(compilationStartContext.CancellationToken); MemoryStream stream = new MemoryStream(); using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8, 1024, true)) { fileText.Write(writer); } stream.Position = 0; // Read all the <Term> elements to get the terms. XDocument document = XDocument.Load(stream); foreach (XElement termElement in document.Descendants("Term")) { terms.Add(termElement.Value); } // Check every named type for the invalid terms. compilationStartContext.RegisterSymbolAction(symbolAnalysisContext => { INamedTypeSymbol namedTypeSymbol = (INamedTypeSymbol)symbolAnalysisContext.Symbol; string symbolName = namedTypeSymbol.Name; foreach (string term in terms) { if (symbolName.Contains(term)) { symbolAnalysisContext.ReportDiagnostic(Diagnostic.Create(Rule, namedTypeSymbol.Locations[0], term)); } } }, SymbolKind.NamedType); } }); } } ```
Introduction ============ This document covers the following: * Uses of Additional Files * Passing Additional Files on the command line * Specifying an individual item as an `AdditionalFile` in an MSBuild project * Specifying an entire set of items as `AdditionalFile`s in an MSBuild project * Accessing and reading additional files through the `AnalyzerOptions` type * Includes sample analyzers that read additional files Uses ==== Sometimes an analyzer needs access to information that is not available through normal compiler inputs--source files, references, and options. To support these scenarios the C# and Visual Basic compilers can accept additional, non-source text files as inputs. For example, an analyzer may enforce that a set of banned terms is not used within a project, or that every source file has a certain copyright header. The terms or copyright header could be passed to the analyzer as an additional file, rather than being hard-coded in the analyzer itself. On the Command Line =================== On the command line, additional files can be passed using the `/additionalfile` option. For example: ``` csc.exe alpha.cs /additionalfile:terms.txt ``` In a Project File ================= Passing an Individual File -------------------------- To specify an individual project item as an additional file, set the item type to `AdditionalFiles`: ``` XML <ItemGroup> <AdditionalFiles Include="terms.txt" /> </ItemGroup> ``` Passing a Group of Files ------------------------ Sometimes it isn't possible to change the item type, or a whole set of items need to be passed as additional files. In this situation you can update the `AdditionalFileItemNames` property to specify which item types to include. For example, if your analyzer needs access to all .resx files in the project, you can do the following: ``` XML <PropertyGroup> <!-- Update the property to include all EmbeddedResource files --> <AdditionalFileItemNames>$(AdditionalFileItemNames);EmbeddedResource</AdditionalFileItemNames> </PropertyGroup> <ItemGroup> <!-- Existing resource file --> <EmbeddedResource Include="Terms.resx"> ... </EmbeddedResource> </ItemGroup> ``` Accessing Additional Files ========================== The set of additional files can be accessed via the `Options` property of the context object passed to a diagnostic action. For example: ```C# CompilationAnalysisContext context = ...; ImmutableArray<AdditionalText> additionFiles = context.Options.AdditionalFiles; ``` From an `AdditionalText` instance, you can access the path to the file or the contents as a `SourceText`: ``` C# AdditionText additionalFile = ...; string path = additionalFile.Path; SourceText contents = additionalFile.GetText(); ``` Samples ======= Reading a File Line-by-Line --------------------------- This sample reads a simple text file for a set of terms--one per line--that should not be used in type names. ``` C# using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class CheckTermsAnalyzer : DiagnosticAnalyzer { public const string DiagnosticId = "CheckTerms001"; private const string Title = "Type name contains invalid term"; private const string MessageFormat = "The term '{0}' is not allowed in a type name."; private const string Category = "Policy"; private static DiagnosticDescriptor Rule = new DiagnosticDescriptor( DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Error, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } } public override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction(compilationStartContext => { // Find the file with the invalid terms. ImmutableArray<AdditionalText> additionalFiles = compilationStartContext.Options.AdditionalFiles; AdditionalText termsFile = additionalFiles.FirstOrDefault(file => Path.GetFileName(file.Path).Equals("Terms.txt")); if (termsFile != null) { HashSet<string> terms = new HashSet<string>(); // Read the file line-by-line to get the terms. SourceText fileText = termsFile.GetText(compilationStartContext.CancellationToken); foreach (TextLine line in fileText.Lines) { terms.Add(line.ToString()); } // Check every named type for the invalid terms. compilationStartContext.RegisterSymbolAction(symbolAnalysisContext => { INamedTypeSymbol namedTypeSymbol = (INamedTypeSymbol)symbolAnalysisContext.Symbol; string symbolName = namedTypeSymbol.Name; foreach (string term in terms) { if (symbolName.Contains(term)) { symbolAnalysisContext.ReportDiagnostic(Diagnostic.Create(Rule, namedTypeSymbol.Locations[0], term)); } } }, SymbolKind.NamedType); } }); } } ``` Converting a File to a Stream ----------------------------- In cases where an additional file contains structured data (e.g., XML or JSON) the line-by-line access provided by the `SourceText` may not be desirable. One alternative is to convert a `SourceText` to a `string`, by calling `ToString()` on it. This sample demonstrates another alternative: converting a `SourceText` to a `Stream` for consumption by other libraries. The terms file is assumed to have the following format: ``` XML <Terms> <Term>frob</Term> <Term>wizbang</Term> <Term>orange</Term> </Terms> ``` ``` C# using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class CheckTermsXMLAnalyzer : DiagnosticAnalyzer { public const string DiagnosticId = "CheckTerms001"; private const string Title = "Type name contains invalid term"; private const string MessageFormat = "The term '{0}' is not allowed in a type name."; private const string Category = "Policy"; private static DiagnosticDescriptor Rule = new DiagnosticDescriptor( DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Error, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } } public override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction(compilationStartContext => { // Find the file with the invalid terms. ImmutableArray<AdditionalText> additionalFiles = compilationStartContext.Options.AdditionalFiles; AdditionalText termsFile = additionalFiles.FirstOrDefault(file => Path.GetFileName(file.Path).Equals("Terms.xml")); if (termsFile != null) { HashSet<string> terms = new HashSet<string>(); SourceText fileText = termsFile.GetText(compilationStartContext.CancellationToken); MemoryStream stream = new MemoryStream(); using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8, 1024, true)) { fileText.Write(writer); } stream.Position = 0; // Read all the <Term> elements to get the terms. XDocument document = XDocument.Load(stream); foreach (XElement termElement in document.Descendants("Term")) { terms.Add(termElement.Value); } // Check every named type for the invalid terms. compilationStartContext.RegisterSymbolAction(symbolAnalysisContext => { INamedTypeSymbol namedTypeSymbol = (INamedTypeSymbol)symbolAnalysisContext.Symbol; string symbolName = namedTypeSymbol.Name; foreach (string term in terms) { if (symbolName.Contains(term)) { symbolAnalysisContext.ReportDiagnostic(Diagnostic.Create(Rule, namedTypeSymbol.Locations[0], term)); } } }, SymbolKind.NamedType); } }); } } ```
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/CSharpTest/SignatureHelp/ElementAccessExpressionSignatureHelpProviderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp { public class ElementAccessExpressionSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests { internal override Type GetSignatureHelpProviderType() => typeof(ElementAccessExpressionSignatureHelpProvider); #region "Regular tests" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersOn1() { var markup = @" class C { public string this[int a] { get { return null; } set { } } } class D { void Goo() { var c = new C(); var x = [|c[$$|]]; } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] [WorkItem(24311, "https://github.com/dotnet/roslyn/issues/24311")] public async Task TestInvocationWithParametersOn1_WithRefReturn() { var markup = @" class C { public ref int this[int a] { get { throw null; } } void Goo(C c) { [|c[$$]|] } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("ref int C[int a]", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] [WorkItem(24311, "https://github.com/dotnet/roslyn/issues/24311")] public async Task TestInvocationWithParametersOn1_WithRefReadonlyReturn() { var markup = @" class C { public ref readonly int this[int a] { get { throw null; } } void Goo(C c) { [|c[$$]|] } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("ref readonly int C[int a]", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(636117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636117")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnExpression() { var markup = @" class C { public string this[int a] { get { return null; } set { } } } class D { void Goo() { C[] c = new C[1]; c[0][$$ } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersXmlCommentsOn1() { var markup = @" class C { /// <summary> /// Summary for this. /// </summary> /// <param name=""a"">Param a</param> public string this[int a] { get { return null; } set { } } } class D { void Goo() { var c = new C(); var x = [|c[$$|]]; } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", "Summary for this.", "Param a", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersOn2() { var markup = @" class C { public string this[int a, bool b] { get { return null; } set { } } } class D { void Goo() { var c = new C(); var x = [|c[22, $$|]]; } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a, bool b]", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersXmlComentsOn2() { var markup = @" class C { /// <summary> /// Summary for this. /// </summary> /// <param name=""a"">Param a</param> /// <param name=""b"">Param b</param> public string this[int a, bool b] { get { return null; } set { } } } class D { void Goo() { var c = new C(); var x = [|c[22, $$|]]; } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a, bool b]", "Summary for this.", "Param b", currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutClosingBracketWithParameters() { var markup = @"class C { public string this[int a] { get { return null; } set { } } } class D { void Goo() { var c = new C(); var x = [|c[$$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutClosingBracketWithParametersOn2() { var markup = @" class C { public string this[int a, bool b] { get { return null; } set { } } } class D { void Goo() { var c = new C(); var x = [|c[22, $$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a, bool b]", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } #endregion #region "Current Parameter Name" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestCurrentParameterName() { var markup = @" class C { public string this[int a, bool b] { get { return null; } set { } } } class D { void Goo() { var c = new C(); var x = [|c[b: false, a: $$42|]]; } }"; await VerifyCurrentParameterNameAsync(markup, "a"); } #endregion #region "Trigger tests" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnTriggerBracket() { var markup = @" class C { public string this[int a] { get { return null; } set { } } } class D { void Goo() { var c = new C(); var x = [|c[$$|]]; } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnTriggerComma() { var markup = @" class C { public string this[int a, bool b] { get { return null; } set { } } } class D { void Goo() { var c = new C(); var x = [|c[42,$$|]]; } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a, bool b]", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestNoInvocationOnSpace() { var markup = @" class C { public string this[int a, bool b] { get { return null; } set { } } } class D { void Goo() { var c = new C(); var x = [|c[42, $$|]]; } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestTriggerCharacters() { char[] expectedCharacters = { ',', '[' }; char[] unexpectedCharacters = { ' ', '(', '<' }; VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters); } #endregion #region "EditorBrowsable tests" [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Indexer_PropertyAlways() { var markup = @" class Program { void M() { new Goo()[$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public int this[int x] { get { return 5; } set { } } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("int Goo[int x]", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Indexer_PropertyNever() { var markup = @" class Program { void M() { new Goo()[$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public int this[int x] { get { return 5; } set { } } }"; var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>(); expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("int Goo[int x]", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItemsMetadataReference, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Indexer_PropertyAdvanced() { var markup = @" class Program { void M() { new Goo()[$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public int this[int x] { get { return 5; } set { } } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("int Goo[int x]", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Indexer_PropertyNeverOnOneOfTwoOverloads() { var markup = @" class Program { void M() { new Goo()[$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public int this[int x] { get { return 5; } set { } } public int this[double d] { get { return 5; } set { } } }"; var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>(); expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("int Goo[double d]", string.Empty, string.Empty, currentParameterIndex: 0)); var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("int Goo[double d]", string.Empty, string.Empty, currentParameterIndex: 0), new SignatureHelpTestItem("int Goo[int x]", string.Empty, string.Empty, currentParameterIndex: 0), }; await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference, expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Indexer_GetBrowsableNeverIgnored() { var markup = @" class Program { void M() { new Goo()[$$ } }"; var referencedCode = @" public class Goo { public int this[int x] { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] get { return 5; } set { } } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("int Goo[int x]", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Indexer_SetBrowsableNeverIgnored() { var markup = @" class Program { void M() { new Goo()[$$ } }"; var referencedCode = @" public class Goo { public int this[int x] { get { return 5; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] set { } } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("int Goo[int x]", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Indexer_GetSetBrowsableNeverIgnored() { var markup = @" class Program { void M() { new Goo()[$$ } }"; var referencedCode = @" public class Goo { public int this[int x] { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] get { return 5; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] set { } } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("int Goo[int x]", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } #endregion #region Indexed Property tests [WorkItem(530811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530811")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task IndexedProperty() { var markup = @"class Program { void M() { CCC c = new CCC(); c.IndexProp[$$ } }"; // Note that <COMImport> is required by compiler. Bug 17013 tracks enabling indexed property for non-COM types. var referencedCode = @"Imports System.Runtime.InteropServices <ComImport()> <GuidAttribute(CCC.ClassId)> Public Class CCC #Region ""COM GUIDs"" Public Const ClassId As String = ""9d965fd2-1514-44f6-accd-257ce77c46b0"" Public Const InterfaceId As String = ""a9415060-fdf0-47e3-bc80-9c18f7f39cf6"" Public Const EventsId As String = ""c6a866a5-5f97-4b53-a5df-3739dc8ff1bb"" # End Region ''' <summary> ''' An index property from VB ''' </summary> ''' <param name=""p1"">p1 is an integer index</param> ''' <returns>A string</returns> Public Property IndexProp(ByVal p1 As Integer) As String Get Return Nothing End Get Set(ByVal value As String) End Set End Property End Class"; var metadataItems = new List<SignatureHelpTestItem>(); metadataItems.Add(new SignatureHelpTestItem("string CCC.IndexProp[int p1]", string.Empty, string.Empty, currentParameterIndex: 0)); var projectReferenceItems = new List<SignatureHelpTestItem>(); projectReferenceItems.Add(new SignatureHelpTestItem("string CCC.IndexProp[int p1]", "An index property from VB", "p1 is an integer index", currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: metadataItems, expectedOrderedItemsSameSolution: projectReferenceItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.VisualBasic); } #endregion [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task FieldUnavailableInOneLinkedFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if GOO public int this[int z] { get { return 0; } } #endif void goo() { var x = this[$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"int C[int z]\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", currentParameterIndex: 0); await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task ExcludeFilesWithInactiveRegions() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO,BAR""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if GOO public int this[int z] { get { return 0; } } #endif #if BAR void goo() { var x = this[$$ } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" /> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"int C[int z]\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", currentParameterIndex: 0); await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false); } public class IncompleteElementAccessExpressionSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests { internal override Type GetSignatureHelpProviderType() => typeof(ElementAccessExpressionSignatureHelpProvider); [WorkItem(636117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636117")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocation() { var markup = @" class C { public string this[int a] { get { return null; } set { } } } class D { void Goo() { var c = new C(); c[$$] } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(939417, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939417")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task ConditionalIndexer() { var markup = @" public class P { public int this[int z] { get { return 0; } } public void goo() { P p = null; p?[$$] } } "; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("int P[int z]", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(32, "https://github.com/dotnet/roslyn/issues/32")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task NonIdentifierConditionalIndexer() { var expected = new[] { new SignatureHelpTestItem("char string[int index]") }; await TestAsync( @"class C { void M() { """"?[$$ } }", expected); // inline with a string literal await TestAsync( @"class C { void M() { """"?[/**/$$ } }", expected); // inline with a string literal and multiline comment await TestAsync( @"class C { void M() { ("""")?[$$ } }", expected); // parenthesized expression await TestAsync( @"class C { void M() { new System.String(' ', 1)?[$$ } }", expected); // new object expression // more complicated parenthesized expression await TestAsync( @"class C { void M() { (null as System.Collections.Generic.List<int>)?[$$ } }", new[] { new SignatureHelpTestItem("int System.Collections.Generic.List<int>[int index]") }); } [WorkItem(1067933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067933")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokedWithNoToken() { var markup = @" // goo[$$"; await TestAsync(markup); } [WorkItem(2482, "https://github.com/dotnet/roslyn/issues/2482")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task WhereExpressionLooksLikeArrayTypeSyntaxOfQualifiedName() { var markup = @" class WithIndexer { public int this[int index] { get { return 0; } } } class TestClass { public WithIndexer Item { get; set; } public void Method(TestClass tc) { // `tc.Item[]` parses as ArrayTypeSyntax with an ElementType of QualifiedNameSyntax tc.Item[$$] } } "; await TestAsync(markup, new[] { new SignatureHelpTestItem("int WithIndexer[int index]") }, usePreviousCharAsTrigger: true); } [WorkItem(20507, "https://github.com/dotnet/roslyn/issues/20507")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InConditionalIndexingFollowedByMemberAccess() { var markup = @" class Indexable { public Indexable this[int x] { get => null; } Indexable Count; static void Main(string[] args) { Indexable x; x?[$$].Count; } } "; await TestAsync(markup, new[] { new SignatureHelpTestItem("Indexable Indexable[int x]") }, usePreviousCharAsTrigger: false); } [WorkItem(20507, "https://github.com/dotnet/roslyn/issues/20507")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InConditionalIndexingFollowedByConditionalAccess() { var markup = @" class Indexable { public Indexable this[int x] { get => null; } Indexable Count; static void Main(string[] args) { Indexable x; x?[$$].Count?.Count; } } "; await TestAsync(markup, new[] { new SignatureHelpTestItem("Indexable Indexable[int x]") }, usePreviousCharAsTrigger: 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.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp { public class ElementAccessExpressionSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests { internal override Type GetSignatureHelpProviderType() => typeof(ElementAccessExpressionSignatureHelpProvider); #region "Regular tests" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersOn1() { var markup = @" class C { public string this[int a] { get { return null; } set { } } } class D { void Goo() { var c = new C(); var x = [|c[$$|]]; } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] [WorkItem(24311, "https://github.com/dotnet/roslyn/issues/24311")] public async Task TestInvocationWithParametersOn1_WithRefReturn() { var markup = @" class C { public ref int this[int a] { get { throw null; } } void Goo(C c) { [|c[$$]|] } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("ref int C[int a]", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] [WorkItem(24311, "https://github.com/dotnet/roslyn/issues/24311")] public async Task TestInvocationWithParametersOn1_WithRefReadonlyReturn() { var markup = @" class C { public ref readonly int this[int a] { get { throw null; } } void Goo(C c) { [|c[$$]|] } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("ref readonly int C[int a]", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(636117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636117")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnExpression() { var markup = @" class C { public string this[int a] { get { return null; } set { } } } class D { void Goo() { C[] c = new C[1]; c[0][$$ } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersXmlCommentsOn1() { var markup = @" class C { /// <summary> /// Summary for this. /// </summary> /// <param name=""a"">Param a</param> public string this[int a] { get { return null; } set { } } } class D { void Goo() { var c = new C(); var x = [|c[$$|]]; } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", "Summary for this.", "Param a", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersOn2() { var markup = @" class C { public string this[int a, bool b] { get { return null; } set { } } } class D { void Goo() { var c = new C(); var x = [|c[22, $$|]]; } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a, bool b]", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersXmlComentsOn2() { var markup = @" class C { /// <summary> /// Summary for this. /// </summary> /// <param name=""a"">Param a</param> /// <param name=""b"">Param b</param> public string this[int a, bool b] { get { return null; } set { } } } class D { void Goo() { var c = new C(); var x = [|c[22, $$|]]; } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a, bool b]", "Summary for this.", "Param b", currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutClosingBracketWithParameters() { var markup = @"class C { public string this[int a] { get { return null; } set { } } } class D { void Goo() { var c = new C(); var x = [|c[$$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutClosingBracketWithParametersOn2() { var markup = @" class C { public string this[int a, bool b] { get { return null; } set { } } } class D { void Goo() { var c = new C(); var x = [|c[22, $$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a, bool b]", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } #endregion #region "Current Parameter Name" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestCurrentParameterName() { var markup = @" class C { public string this[int a, bool b] { get { return null; } set { } } } class D { void Goo() { var c = new C(); var x = [|c[b: false, a: $$42|]]; } }"; await VerifyCurrentParameterNameAsync(markup, "a"); } #endregion #region "Trigger tests" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnTriggerBracket() { var markup = @" class C { public string this[int a] { get { return null; } set { } } } class D { void Goo() { var c = new C(); var x = [|c[$$|]]; } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnTriggerComma() { var markup = @" class C { public string this[int a, bool b] { get { return null; } set { } } } class D { void Goo() { var c = new C(); var x = [|c[42,$$|]]; } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a, bool b]", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestNoInvocationOnSpace() { var markup = @" class C { public string this[int a, bool b] { get { return null; } set { } } } class D { void Goo() { var c = new C(); var x = [|c[42, $$|]]; } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestTriggerCharacters() { char[] expectedCharacters = { ',', '[' }; char[] unexpectedCharacters = { ' ', '(', '<' }; VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters); } #endregion #region "EditorBrowsable tests" [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Indexer_PropertyAlways() { var markup = @" class Program { void M() { new Goo()[$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public int this[int x] { get { return 5; } set { } } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("int Goo[int x]", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Indexer_PropertyNever() { var markup = @" class Program { void M() { new Goo()[$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public int this[int x] { get { return 5; } set { } } }"; var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>(); expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("int Goo[int x]", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItemsMetadataReference, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Indexer_PropertyAdvanced() { var markup = @" class Program { void M() { new Goo()[$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public int this[int x] { get { return 5; } set { } } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("int Goo[int x]", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Indexer_PropertyNeverOnOneOfTwoOverloads() { var markup = @" class Program { void M() { new Goo()[$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public int this[int x] { get { return 5; } set { } } public int this[double d] { get { return 5; } set { } } }"; var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>(); expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("int Goo[double d]", string.Empty, string.Empty, currentParameterIndex: 0)); var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("int Goo[double d]", string.Empty, string.Empty, currentParameterIndex: 0), new SignatureHelpTestItem("int Goo[int x]", string.Empty, string.Empty, currentParameterIndex: 0), }; await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference, expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Indexer_GetBrowsableNeverIgnored() { var markup = @" class Program { void M() { new Goo()[$$ } }"; var referencedCode = @" public class Goo { public int this[int x] { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] get { return 5; } set { } } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("int Goo[int x]", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Indexer_SetBrowsableNeverIgnored() { var markup = @" class Program { void M() { new Goo()[$$ } }"; var referencedCode = @" public class Goo { public int this[int x] { get { return 5; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] set { } } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("int Goo[int x]", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Indexer_GetSetBrowsableNeverIgnored() { var markup = @" class Program { void M() { new Goo()[$$ } }"; var referencedCode = @" public class Goo { public int this[int x] { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] get { return 5; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] set { } } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("int Goo[int x]", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } #endregion #region Indexed Property tests [WorkItem(530811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530811")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task IndexedProperty() { var markup = @"class Program { void M() { CCC c = new CCC(); c.IndexProp[$$ } }"; // Note that <COMImport> is required by compiler. Bug 17013 tracks enabling indexed property for non-COM types. var referencedCode = @"Imports System.Runtime.InteropServices <ComImport()> <GuidAttribute(CCC.ClassId)> Public Class CCC #Region ""COM GUIDs"" Public Const ClassId As String = ""9d965fd2-1514-44f6-accd-257ce77c46b0"" Public Const InterfaceId As String = ""a9415060-fdf0-47e3-bc80-9c18f7f39cf6"" Public Const EventsId As String = ""c6a866a5-5f97-4b53-a5df-3739dc8ff1bb"" # End Region ''' <summary> ''' An index property from VB ''' </summary> ''' <param name=""p1"">p1 is an integer index</param> ''' <returns>A string</returns> Public Property IndexProp(ByVal p1 As Integer) As String Get Return Nothing End Get Set(ByVal value As String) End Set End Property End Class"; var metadataItems = new List<SignatureHelpTestItem>(); metadataItems.Add(new SignatureHelpTestItem("string CCC.IndexProp[int p1]", string.Empty, string.Empty, currentParameterIndex: 0)); var projectReferenceItems = new List<SignatureHelpTestItem>(); projectReferenceItems.Add(new SignatureHelpTestItem("string CCC.IndexProp[int p1]", "An index property from VB", "p1 is an integer index", currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: metadataItems, expectedOrderedItemsSameSolution: projectReferenceItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.VisualBasic); } #endregion [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task FieldUnavailableInOneLinkedFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if GOO public int this[int z] { get { return 0; } } #endif void goo() { var x = this[$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"int C[int z]\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", currentParameterIndex: 0); await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task ExcludeFilesWithInactiveRegions() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO,BAR""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if GOO public int this[int z] { get { return 0; } } #endif #if BAR void goo() { var x = this[$$ } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" /> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"int C[int z]\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", currentParameterIndex: 0); await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false); } public class IncompleteElementAccessExpressionSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests { internal override Type GetSignatureHelpProviderType() => typeof(ElementAccessExpressionSignatureHelpProvider); [WorkItem(636117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636117")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocation() { var markup = @" class C { public string this[int a] { get { return null; } set { } } } class D { void Goo() { var c = new C(); c[$$] } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(939417, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939417")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task ConditionalIndexer() { var markup = @" public class P { public int this[int z] { get { return 0; } } public void goo() { P p = null; p?[$$] } } "; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("int P[int z]", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(32, "https://github.com/dotnet/roslyn/issues/32")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task NonIdentifierConditionalIndexer() { var expected = new[] { new SignatureHelpTestItem("char string[int index]") }; await TestAsync( @"class C { void M() { """"?[$$ } }", expected); // inline with a string literal await TestAsync( @"class C { void M() { """"?[/**/$$ } }", expected); // inline with a string literal and multiline comment await TestAsync( @"class C { void M() { ("""")?[$$ } }", expected); // parenthesized expression await TestAsync( @"class C { void M() { new System.String(' ', 1)?[$$ } }", expected); // new object expression // more complicated parenthesized expression await TestAsync( @"class C { void M() { (null as System.Collections.Generic.List<int>)?[$$ } }", new[] { new SignatureHelpTestItem("int System.Collections.Generic.List<int>[int index]") }); } [WorkItem(1067933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067933")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokedWithNoToken() { var markup = @" // goo[$$"; await TestAsync(markup); } [WorkItem(2482, "https://github.com/dotnet/roslyn/issues/2482")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task WhereExpressionLooksLikeArrayTypeSyntaxOfQualifiedName() { var markup = @" class WithIndexer { public int this[int index] { get { return 0; } } } class TestClass { public WithIndexer Item { get; set; } public void Method(TestClass tc) { // `tc.Item[]` parses as ArrayTypeSyntax with an ElementType of QualifiedNameSyntax tc.Item[$$] } } "; await TestAsync(markup, new[] { new SignatureHelpTestItem("int WithIndexer[int index]") }, usePreviousCharAsTrigger: true); } [WorkItem(20507, "https://github.com/dotnet/roslyn/issues/20507")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InConditionalIndexingFollowedByMemberAccess() { var markup = @" class Indexable { public Indexable this[int x] { get => null; } Indexable Count; static void Main(string[] args) { Indexable x; x?[$$].Count; } } "; await TestAsync(markup, new[] { new SignatureHelpTestItem("Indexable Indexable[int x]") }, usePreviousCharAsTrigger: false); } [WorkItem(20507, "https://github.com/dotnet/roslyn/issues/20507")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InConditionalIndexingFollowedByConditionalAccess() { var markup = @" class Indexable { public Indexable this[int x] { get => null; } Indexable Count; static void Main(string[] args) { Indexable x; x?[$$].Count?.Count; } } "; await TestAsync(markup, new[] { new SignatureHelpTestItem("Indexable Indexable[int x]") }, usePreviousCharAsTrigger: false); } } } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Test/Resources/Core/SymbolsTests/NoPia/C.dll
MZ@ !L!This program cannot be run in DOS mode. $PELnL! >$ @@ @#K@`  H.textD  `.rsrc@@@.reloc ` @B $HP BSJB v4.0.30319lL#~#Strings#US#GUID#BlobG %3   E&\&s&&&F F#m)m#1mR9mVAmRIm#.#[.+d..3C C( <Module>mscorlibICAIAF1BIBF2System.Runtime.InteropServicesInterfaceTypeAttributeComInterfaceType.ctorGuidAttributeComImportAttributeSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeImportedFromTypeLibAttributeCC.dll Mr ߡz\V4     )$27e3e649-994b-4f58-b3c6-f8089a5f200C  TWrapNonExceptionThrows C.dll)$f9c2d51d-4f44-45f0-9eda-c9d599b5826C$.$ $_CorDllMainmscoree.dll% @0HX@,,4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfoh000004b0,FileDescription 0FileVersion0.0.0.0,InternalNameC.dll(LegalCopyright 4OriginalFilenameC.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 @4
MZ@ !L!This program cannot be run in DOS mode. $PELnL! >$ @@ @#K@`  H.textD  `.rsrc@@@.reloc ` @B $HP BSJB v4.0.30319lL#~#Strings#US#GUID#BlobG %3   E&\&s&&&F F#m)m#1mR9mVAmRIm#.#[.+d..3C C( <Module>mscorlibICAIAF1BIBF2System.Runtime.InteropServicesInterfaceTypeAttributeComInterfaceType.ctorGuidAttributeComImportAttributeSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeImportedFromTypeLibAttributeCC.dll Mr ߡz\V4     )$27e3e649-994b-4f58-b3c6-f8089a5f200C  TWrapNonExceptionThrows C.dll)$f9c2d51d-4f44-45f0-9eda-c9d599b5826C$.$ $_CorDllMainmscoree.dll% @0HX@,,4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfoh000004b0,FileDescription 0FileVersion0.0.0.0,InternalNameC.dll(LegalCopyright 4OriginalFilenameC.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 @4
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/CSharp/Test/Properties/launchSettings.json
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
-1
dotnet/roslyn
55,357
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred
Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
cston
2021-08-03T00:08:10Z
2021-08-18T00:26:12Z
d773edf3f3b6e6596c2bc5eb4c852dadc5f6c6bd
dc1399254b76c72b6b13ee9188781a4ac51afe1d
Treat overload with Delegate parameter as not applicable if lambda delegate type cannot be inferred. Fixes #55319 Relates to test plan https://github.com/dotnet/roslyn/issues/52192
./src/Features/LanguageServer/ProtocolUnitTests/Highlights/DocumentHighlightTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Threading; using System.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Highlights { public class DocumentHighlightTests : AbstractLanguageServerProtocolTests { [Fact] public async Task TestGetDocumentHighlightAsync() { var markup = @"class B { } class A { B {|text:classB|}; void M() { var someVar = {|read:classB|}; {|caret:|}{|write:classB|} = new B(); } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var expected = new LSP.DocumentHighlight[] { CreateDocumentHighlight(LSP.DocumentHighlightKind.Text, locations["text"].Single()), CreateDocumentHighlight(LSP.DocumentHighlightKind.Read, locations["read"].Single()), CreateDocumentHighlight(LSP.DocumentHighlightKind.Write, locations["write"].Single()) }; var results = await RunGetDocumentHighlightAsync(testLspServer, locations["caret"].Single()); AssertJsonEquals(expected, results); } [Fact] public async Task TestGetDocumentHighlightAsync_InvalidLocation() { var markup = @"class A { void M() { {|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var results = await RunGetDocumentHighlightAsync(testLspServer, locations["caret"].Single()); Assert.Empty(results); } private static async Task<LSP.DocumentHighlight[]> RunGetDocumentHighlightAsync(TestLspServer testLspServer, LSP.Location caret) { var results = await testLspServer.ExecuteRequestAsync<LSP.TextDocumentPositionParams, LSP.DocumentHighlight[]>(LSP.Methods.TextDocumentDocumentHighlightName, CreateTextDocumentPositionParams(caret), new LSP.ClientCapabilities(), null, CancellationToken.None); Array.Sort(results, (h1, h2) => { var compareKind = h1.Kind.CompareTo(h2.Kind); var compareRange = CompareRange(h1.Range, h2.Range); return compareKind != 0 ? compareKind : compareRange; }); return results; } private static LSP.DocumentHighlight CreateDocumentHighlight(LSP.DocumentHighlightKind kind, LSP.Location location) => new LSP.DocumentHighlight() { Kind = kind, Range = location.Range }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Threading; using System.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Highlights { public class DocumentHighlightTests : AbstractLanguageServerProtocolTests { [Fact] public async Task TestGetDocumentHighlightAsync() { var markup = @"class B { } class A { B {|text:classB|}; void M() { var someVar = {|read:classB|}; {|caret:|}{|write:classB|} = new B(); } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var expected = new LSP.DocumentHighlight[] { CreateDocumentHighlight(LSP.DocumentHighlightKind.Text, locations["text"].Single()), CreateDocumentHighlight(LSP.DocumentHighlightKind.Read, locations["read"].Single()), CreateDocumentHighlight(LSP.DocumentHighlightKind.Write, locations["write"].Single()) }; var results = await RunGetDocumentHighlightAsync(testLspServer, locations["caret"].Single()); AssertJsonEquals(expected, results); } [Fact] public async Task TestGetDocumentHighlightAsync_InvalidLocation() { var markup = @"class A { void M() { {|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var results = await RunGetDocumentHighlightAsync(testLspServer, locations["caret"].Single()); Assert.Empty(results); } private static async Task<LSP.DocumentHighlight[]> RunGetDocumentHighlightAsync(TestLspServer testLspServer, LSP.Location caret) { var results = await testLspServer.ExecuteRequestAsync<LSP.TextDocumentPositionParams, LSP.DocumentHighlight[]>(LSP.Methods.TextDocumentDocumentHighlightName, CreateTextDocumentPositionParams(caret), new LSP.ClientCapabilities(), null, CancellationToken.None); Array.Sort(results, (h1, h2) => { var compareKind = h1.Kind.CompareTo(h2.Kind); var compareRange = CompareRange(h1.Range, h2.Range); return compareKind != 0 ? compareKind : compareRange; }); return results; } private static LSP.DocumentHighlight CreateDocumentHighlight(LSP.DocumentHighlightKind kind, LSP.Location location) => new LSP.DocumentHighlight() { Kind = kind, Range = location.Range }; } }
-1
dotnet/roslyn
55,354
Add IFieldSymbol.FixedSize API
Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
333fred
2021-08-02T22:15:12Z
2021-08-03T21:43:37Z
76bdda7fe502a74f91aee0feb2fe251039be4e82
a81b07d0d5a6b5c5430443fc843e4a730399c946
Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
./src/Compilers/CSharp/Portable/Symbols/PublicModel/FieldSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Diagnostics; using System.Threading; namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel { internal sealed class FieldSymbol : Symbol, IFieldSymbol { private readonly Symbols.FieldSymbol _underlying; private ITypeSymbol _lazyType; public FieldSymbol(Symbols.FieldSymbol underlying) { Debug.Assert(underlying is object); _underlying = underlying; } internal override CSharp.Symbol UnderlyingSymbol => _underlying; ISymbol IFieldSymbol.AssociatedSymbol { get { return _underlying.AssociatedSymbol.GetPublicSymbol(); } } ITypeSymbol IFieldSymbol.Type { get { if (_lazyType is null) { Interlocked.CompareExchange(ref _lazyType, _underlying.TypeWithAnnotations.GetPublicSymbol(), null); } return _lazyType; } } CodeAnalysis.NullableAnnotation IFieldSymbol.NullableAnnotation => _underlying.TypeWithAnnotations.ToPublicAnnotation(); ImmutableArray<CustomModifier> IFieldSymbol.CustomModifiers { get { return _underlying.TypeWithAnnotations.CustomModifiers; } } IFieldSymbol IFieldSymbol.OriginalDefinition { get { return _underlying.OriginalDefinition.GetPublicSymbol(); } } IFieldSymbol IFieldSymbol.CorrespondingTupleField { get { return _underlying.CorrespondingTupleField.GetPublicSymbol(); } } bool IFieldSymbol.IsExplicitlyNamedTupleElement { get { return _underlying.IsExplicitlyNamedTupleElement; } } bool IFieldSymbol.IsConst => _underlying.IsConst; bool IFieldSymbol.IsReadOnly => _underlying.IsReadOnly; bool IFieldSymbol.IsVolatile => _underlying.IsVolatile; bool IFieldSymbol.IsFixedSizeBuffer => _underlying.IsFixedSizeBuffer; bool IFieldSymbol.HasConstantValue => _underlying.HasConstantValue; object IFieldSymbol.ConstantValue => _underlying.ConstantValue; #region ISymbol Members protected override void Accept(SymbolVisitor visitor) { visitor.VisitField(this); } protected override TResult Accept<TResult>(SymbolVisitor<TResult> visitor) { return visitor.VisitField(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. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using System.Threading; namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel { internal sealed class FieldSymbol : Symbol, IFieldSymbol { private readonly Symbols.FieldSymbol _underlying; private ITypeSymbol _lazyType; public FieldSymbol(Symbols.FieldSymbol underlying) { Debug.Assert(underlying is object); _underlying = underlying; } internal override CSharp.Symbol UnderlyingSymbol => _underlying; ISymbol IFieldSymbol.AssociatedSymbol { get { return _underlying.AssociatedSymbol.GetPublicSymbol(); } } ITypeSymbol IFieldSymbol.Type { get { if (_lazyType is null) { Interlocked.CompareExchange(ref _lazyType, _underlying.TypeWithAnnotations.GetPublicSymbol(), null); } return _lazyType; } } CodeAnalysis.NullableAnnotation IFieldSymbol.NullableAnnotation => _underlying.TypeWithAnnotations.ToPublicAnnotation(); ImmutableArray<CustomModifier> IFieldSymbol.CustomModifiers { get { return _underlying.TypeWithAnnotations.CustomModifiers; } } IFieldSymbol IFieldSymbol.OriginalDefinition { get { return _underlying.OriginalDefinition.GetPublicSymbol(); } } IFieldSymbol IFieldSymbol.CorrespondingTupleField { get { return _underlying.CorrespondingTupleField.GetPublicSymbol(); } } bool IFieldSymbol.IsExplicitlyNamedTupleElement { get { return _underlying.IsExplicitlyNamedTupleElement; } } bool IFieldSymbol.IsConst => _underlying.IsConst; bool IFieldSymbol.IsReadOnly => _underlying.IsReadOnly; bool IFieldSymbol.IsVolatile => _underlying.IsVolatile; bool IFieldSymbol.IsFixedSizeBuffer => _underlying.IsFixedSizeBuffer; int IFieldSymbol.FixedSize => _underlying.FixedSize; bool IFieldSymbol.HasConstantValue => _underlying.HasConstantValue; object IFieldSymbol.ConstantValue => _underlying.ConstantValue; #region ISymbol Members protected override void Accept(SymbolVisitor visitor) { visitor.VisitField(this); } protected override TResult Accept<TResult>(SymbolVisitor<TResult> visitor) { return visitor.VisitField(this); } #endregion } }
1
dotnet/roslyn
55,354
Add IFieldSymbol.FixedSize API
Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
333fred
2021-08-02T22:15:12Z
2021-08-03T21:43:37Z
76bdda7fe502a74f91aee0feb2fe251039be4e82
a81b07d0d5a6b5c5430443fc843e4a730399c946
Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
./src/Compilers/CSharp/Test/Symbol/Symbols/Source/FieldTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class FieldTests : CSharpTestBase { [Fact] public void InitializerInStruct() { var text = @"struct S { public int I = 9; public S(int i) {} }"; CreateCompilation(text, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (3,16): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // public int I = 9; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "I").WithArguments("struct field initializers", "10.0").WithLocation(3, 16)); } [Fact] public void InitializerInStruct2() { var text = @"struct S { public int I = 9; public S(int i) : this() {} }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (3,16): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // public int I = 9; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "I").WithArguments("struct field initializers", "10.0").WithLocation(3, 16)); } [Fact] public void Simple1() { var text = @" class A { A F; } "; var comp = CreateEmptyCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var sym = a.GetMembers("F").Single() as FieldSymbol; Assert.Equal(TypeKind.Class, sym.Type.TypeKind); Assert.Equal<TypeSymbol>(a, sym.Type); Assert.Equal(Accessibility.Private, sym.DeclaredAccessibility); Assert.Equal(SymbolKind.Field, sym.Kind); Assert.False(sym.IsStatic); Assert.False(sym.IsAbstract); Assert.False(sym.IsSealed); Assert.False(sym.IsVirtual); Assert.False(sym.IsOverride); // Assert.Equal(0, sym.GetAttributes().Count()); } [Fact] public void Simple2() { var text = @" class A { A F, G; A G; } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var f = a.GetMembers("F").Single() as FieldSymbol; Assert.Equal(TypeKind.Class, f.Type.TypeKind); Assert.Equal<TypeSymbol>(a, f.Type); Assert.Equal(Accessibility.Private, f.DeclaredAccessibility); var gs = a.GetMembers("G"); Assert.Equal(2, gs.Length); foreach (var g in gs) { Assert.Equal(a, (g as FieldSymbol).Type); // duplicate, but all the same. } var errors = comp.GetDeclarationDiagnostics(); var one = errors.Single(); Assert.Equal(ErrorCode.ERR_DuplicateNameInClass, (ErrorCode)one.Code); } [Fact] public void Ambig1() { var text = @" class A { A F; A F; } "; var comp = CreateEmptyCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var fs = a.GetMembers("F"); Assert.Equal(2, fs.Length); foreach (var f in fs) { Assert.Equal(a, (f as FieldSymbol).Type); } } [WorkItem(537237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537237")] [Fact] public void FieldModifiers() { var text = @" class A { internal protected const long N1 = 0; public volatile byte N2 = 0; private static char N3 = ' '; } "; var comp = CreateEmptyCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var n1 = a.GetMembers("N1").Single() as FieldSymbol; Assert.True(n1.IsConst); Assert.False(n1.IsVolatile); Assert.True(n1.IsStatic); Assert.Equal(0, n1.TypeWithAnnotations.CustomModifiers.Length); var n2 = a.GetMembers("N2").Single() as FieldSymbol; Assert.False(n2.IsConst); Assert.True(n2.IsVolatile); Assert.False(n2.IsStatic); Assert.Equal(1, n2.TypeWithAnnotations.CustomModifiers.Length); CustomModifier mod = n2.TypeWithAnnotations.CustomModifiers[0]; Assert.False(mod.IsOptional); Assert.Equal("System.Runtime.CompilerServices.IsVolatile[missing]", mod.Modifier.ToTestDisplayString()); var n3 = a.GetMembers("N3").Single() as FieldSymbol; Assert.False(n3.IsConst); Assert.False(n3.IsVolatile); Assert.True(n3.IsStatic); Assert.Equal(0, n3.TypeWithAnnotations.CustomModifiers.Length); } [Fact] public void Nullable() { var text = @" class A { int? F = null; } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var sym = a.GetMembers("F").Single() as FieldSymbol; Assert.Equal("System.Int32? A.F", sym.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, sym.Type.TypeKind); Assert.Equal("System.Int32?", sym.Type.ToTestDisplayString()); } [Fact] public void Generic01() { var text = @"public class C<T> { internal struct S<V> { public System.Collections.Generic.List<T> M<V>(V p) { return null; } private System.Collections.Generic.List<T> field1; internal System.Collections.Generic.IList<V> field2; public S<string> field3; } } "; var comp = CreateCompilation(text); var type1 = comp.GlobalNamespace.GetTypeMembers("C", 1).Single(); var type2 = type1.GetTypeMembers("S").Single(); var s = type2.GetMembers("M").Single() as MethodSymbol; Assert.Equal("M", s.Name); Assert.Equal("System.Collections.Generic.List<T> C<T>.S<V>.M<V>(V p)", s.ToTestDisplayString()); var sym = type2.GetMembers("field1").Single() as FieldSymbol; Assert.Equal("System.Collections.Generic.List<T> C<T>.S<V>.field1", sym.ToTestDisplayString()); Assert.Equal(TypeKind.Class, sym.Type.TypeKind); Assert.Equal("System.Collections.Generic.List<T>", sym.Type.ToTestDisplayString()); sym = type2.GetMembers("field2").Single() as FieldSymbol; Assert.Equal("System.Collections.Generic.IList<V> C<T>.S<V>.field2", sym.ToTestDisplayString()); Assert.Equal(TypeKind.Interface, sym.Type.TypeKind); Assert.Equal("System.Collections.Generic.IList<V>", sym.Type.ToTestDisplayString()); sym = type2.GetMembers("field3").Single() as FieldSymbol; Assert.Equal("C<T>.S<System.String> C<T>.S<V>.field3", sym.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, sym.Type.TypeKind); Assert.Equal("C<T>.S<System.String>", sym.Type.ToTestDisplayString()); } [WorkItem(537401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537401")] [Fact] public void EventEscapedIdentifier() { var text = @" delegate void @out(); class C1 { @out @in; } "; var comp = CreateCompilation(Parse(text)); NamedTypeSymbol c1 = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("C1").Single(); FieldSymbol ein = (FieldSymbol)c1.GetMembers("in").Single(); Assert.Equal("in", ein.Name); Assert.Equal("C1.@in", ein.ToString()); NamedTypeSymbol dout = (NamedTypeSymbol)ein.Type; Assert.Equal("out", dout.Name); Assert.Equal("@out", dout.ToString()); } [WorkItem(539653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539653")] [Fact] public void ConstFieldWithoutValueErr() { var text = @" class C { const int x; } "; var comp = CreateCompilation(Parse(text)); NamedTypeSymbol type1 = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("C").Single(); FieldSymbol mem = (FieldSymbol)type1.GetMembers("x").Single(); Assert.Equal("x", mem.Name); Assert.True(mem.IsConst); Assert.False(mem.HasConstantValue); Assert.Null(mem.ConstantValue); } [WorkItem(543538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543538")] [Fact] public void Error_InvalidConst() { var source = @" class A { const delegate void D(); protected virtual void Finalize const () { } } "; // CONSIDER: Roslyn's cascading errors are much uglier than Dev10's. CreateCompilationWithMscorlib46(source, parseOptions: TestOptions.Regular).VerifyDiagnostics( // (4,11): error CS1031: Type expected // const delegate void D(); Diagnostic(ErrorCode.ERR_TypeExpected, "delegate").WithLocation(4, 11), // (4,11): error CS1001: Identifier expected // const delegate void D(); Diagnostic(ErrorCode.ERR_IdentifierExpected, "delegate").WithLocation(4, 11), // (4,11): error CS0145: A const field requires a value to be provided // const delegate void D(); Diagnostic(ErrorCode.ERR_ConstValueRequired, "delegate").WithLocation(4, 11), // (4,11): error CS1002: ; expected // const delegate void D(); Diagnostic(ErrorCode.ERR_SemicolonExpected, "delegate").WithLocation(4, 11), // (5,37): error CS1002: ; expected // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_SemicolonExpected, "const").WithLocation(5, 37), // (5,44): error CS8124: Tuple must contain at least two elements. // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(5, 44), // (5,46): error CS1001: Identifier expected // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_IdentifierExpected, "{").WithLocation(5, 46), // (5,46): error CS0145: A const field requires a value to be provided // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_ConstValueRequired, "{").WithLocation(5, 46), // (5,46): error CS1003: Syntax error, ',' expected // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_SyntaxError, "{").WithArguments(",", "{").WithLocation(5, 46), // (5,48): error CS1002: ; expected // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(5, 48), // (6,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(6, 1), // (5,28): error CS0106: The modifier 'virtual' is not valid for this item // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Finalize").WithArguments("virtual").WithLocation(5, 28), // (5,43): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "()").WithArguments("System.ValueTuple`2").WithLocation(5, 43), // (5,23): error CS0670: Field cannot have void type // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void").WithLocation(5, 23), // (5,46): error CS0102: The type 'A' already contains a definition for '' // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("A", "").WithLocation(5, 46), // (5,28): warning CS0649: Field 'A.Finalize' is never assigned to, and will always have its default value // protected virtual void Finalize const () { } Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Finalize").WithArguments("A.Finalize", "").WithLocation(5, 28) ); } [WorkItem(543538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543538")] [Fact] public void Error_InvalidConstWithCSharp6() { var source = @" class A { const delegate void D(); protected virtual void Finalize const () { } } "; // CONSIDER: Roslyn's cascading errors are much uglier than Dev10's. CreateCompilationWithMscorlib46(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)).VerifyDiagnostics( // (4,11): error CS1031: Type expected // const delegate void D(); Diagnostic(ErrorCode.ERR_TypeExpected, "delegate").WithLocation(4, 11), // (4,11): error CS1001: Identifier expected // const delegate void D(); Diagnostic(ErrorCode.ERR_IdentifierExpected, "delegate").WithLocation(4, 11), // (4,11): error CS0145: A const field requires a value to be provided // const delegate void D(); Diagnostic(ErrorCode.ERR_ConstValueRequired, "delegate").WithLocation(4, 11), // (4,11): error CS1002: ; expected // const delegate void D(); Diagnostic(ErrorCode.ERR_SemicolonExpected, "delegate").WithLocation(4, 11), // (5,37): error CS1002: ; expected // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_SemicolonExpected, "const").WithLocation(5, 37), // (5,43): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater. // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "()").WithArguments("tuples", "7.0").WithLocation(5, 43), // (5,44): error CS8124: Tuple must contain at least two elements. // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(5, 44), // (5,46): error CS1001: Identifier expected // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_IdentifierExpected, "{").WithLocation(5, 46), // (5,46): error CS0145: A const field requires a value to be provided // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_ConstValueRequired, "{").WithLocation(5, 46), // (5,46): error CS1003: Syntax error, ',' expected // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_SyntaxError, "{").WithArguments(",", "{").WithLocation(5, 46), // (5,48): error CS1002: ; expected // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(5, 48), // (6,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(6, 1), // (5,28): error CS0106: The modifier 'virtual' is not valid for this item // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Finalize").WithArguments("virtual").WithLocation(5, 28), // (5,43): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "()").WithArguments("System.ValueTuple`2").WithLocation(5, 43), // (5,23): error CS0670: Field cannot have void type // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void").WithLocation(5, 23), // (5,46): error CS0102: The type 'A' already contains a definition for '' // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("A", "").WithLocation(5, 46), // (5,28): warning CS0649: Field 'A.Finalize' is never assigned to, and will always have its default value // protected virtual void Finalize const () { } Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Finalize").WithArguments("A.Finalize", "").WithLocation(5, 28) ); } [WorkItem(543791, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543791")] [Fact] public void MultipleDeclaratorsOneError() { var source = @" class A { Unknown a, b; } "; CreateCompilation(source).VerifyDiagnostics( // (4,5): error CS0246: The type or namespace name 'Unknown' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unknown").WithArguments("Unknown"), // (4,13): warning CS0169: The field 'A.a' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "a").WithArguments("A.a"), // (4,16): warning CS0169: The field 'A.b' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "b").WithArguments("A.b")); } /// <summary> /// Fields named "value__" should be marked rtspecialname. /// </summary> [WorkItem(546185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546185")] [ClrOnlyFact(ClrOnlyReason.Unknown, Skip = "https://github.com/dotnet/roslyn/issues/6190")] public void RTSpecialName() { var source = @"class A { object value__ = null; } class B { object VALUE__ = null; } class C { void value__() { } } class D { object value__ { get; set; } } class E { event System.Action value__; } class F { event System.Action value__ { add { } remove { } } } class G { interface value__ { } } class H { class value__ { } } class K { static System.Action<object> F() { object value__; return v => { value__ = v; }; } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (19,25): warning CS0067: The event 'E.value__' is never used // event System.Action value__; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "value__").WithArguments("E.value__"), // (7,12): warning CS0414: The field 'B.VALUE__' is assigned but its value is never used // object VALUE__ = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "VALUE__").WithArguments("B.VALUE__"), // (3,12): warning CS0414: The field 'A.value__' is assigned but its value is never used // object value__ = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "value__").WithArguments("A.value__")); // PEVerify should not report "Field value__ ... is not marked RTSpecialName". var verifier = new CompilationVerifier(compilation); verifier.EmitAndVerify( "Error: Field name value__ is reserved for Enums only.", "Error: Field name value__ is reserved for Enums only.", "Error: Field name value__ is reserved for Enums only."); } [WorkItem(26364, "https://github.com/dotnet/roslyn/issues/26364")] [Fact] public void FixedSizeBufferTrue() { var text = @" unsafe struct S { private fixed byte goo[10]; } "; var comp = CreateEmptyCompilation(text); var global = comp.GlobalNamespace; var s = global.GetTypeMember("S"); var goo = s.GetMember<FieldSymbol>("goo"); Assert.True(goo.IsFixedSizeBuffer); } [WorkItem(26364, "https://github.com/dotnet/roslyn/issues/26364")] [Fact] public void FixedSizeBufferFalse() { var text = @" unsafe struct S { private byte goo; } "; var comp = CreateEmptyCompilation(text); var global = comp.GlobalNamespace; var s = global.GetTypeMember("S"); var goo = s.GetMember<FieldSymbol>("goo"); Assert.False(goo.IsFixedSizeBuffer); } [Fact] public void StaticFieldDoesNotRequireInstanceReceiver() { var source = @" class C { public static int F = 42; }"; var compilation = CreateCompilation(source).VerifyDiagnostics(); var field = compilation.GetMember<FieldSymbol>("C.F"); Assert.False(field.RequiresInstanceReceiver); } [Fact] public void InstanceFieldRequiresInstanceReceiver() { var source = @" class C { public int F = 42; }"; var compilation = CreateCompilation(source).VerifyDiagnostics(); var field = compilation.GetMember<FieldSymbol>("C.F"); Assert.True(field.RequiresInstanceReceiver); } [Fact] public void UnreferencedInterpolatedStringConstants() { var comp = CreateCompilation(@" class C { private static string s1 = $""""; private static readonly string s2 = $""""; private string s3 = $""""; private readonly string s4 = $""""; } struct S { private static string s1 = $""""; private static readonly string s2 = $""""; } "); comp.VerifyDiagnostics(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class FieldTests : CSharpTestBase { [Fact] public void InitializerInStruct() { var text = @"struct S { public int I = 9; public S(int i) {} }"; CreateCompilation(text, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (3,16): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // public int I = 9; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "I").WithArguments("struct field initializers", "10.0").WithLocation(3, 16)); } [Fact] public void InitializerInStruct2() { var text = @"struct S { public int I = 9; public S(int i) : this() {} }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (3,16): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // public int I = 9; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "I").WithArguments("struct field initializers", "10.0").WithLocation(3, 16)); } [Fact] public void Simple1() { var text = @" class A { A F; } "; var comp = CreateEmptyCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var sym = a.GetMembers("F").Single() as FieldSymbol; Assert.Equal(TypeKind.Class, sym.Type.TypeKind); Assert.Equal<TypeSymbol>(a, sym.Type); Assert.Equal(Accessibility.Private, sym.DeclaredAccessibility); Assert.Equal(SymbolKind.Field, sym.Kind); Assert.False(sym.IsStatic); Assert.False(sym.IsAbstract); Assert.False(sym.IsSealed); Assert.False(sym.IsVirtual); Assert.False(sym.IsOverride); // Assert.Equal(0, sym.GetAttributes().Count()); } [Fact] public void Simple2() { var text = @" class A { A F, G; A G; } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var f = a.GetMembers("F").Single() as FieldSymbol; Assert.Equal(TypeKind.Class, f.Type.TypeKind); Assert.Equal<TypeSymbol>(a, f.Type); Assert.Equal(Accessibility.Private, f.DeclaredAccessibility); var gs = a.GetMembers("G"); Assert.Equal(2, gs.Length); foreach (var g in gs) { Assert.Equal(a, (g as FieldSymbol).Type); // duplicate, but all the same. } var errors = comp.GetDeclarationDiagnostics(); var one = errors.Single(); Assert.Equal(ErrorCode.ERR_DuplicateNameInClass, (ErrorCode)one.Code); } [Fact] public void Ambig1() { var text = @" class A { A F; A F; } "; var comp = CreateEmptyCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var fs = a.GetMembers("F"); Assert.Equal(2, fs.Length); foreach (var f in fs) { Assert.Equal(a, (f as FieldSymbol).Type); } } [WorkItem(537237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537237")] [Fact] public void FieldModifiers() { var text = @" class A { internal protected const long N1 = 0; public volatile byte N2 = 0; private static char N3 = ' '; } "; var comp = CreateEmptyCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var n1 = a.GetMembers("N1").Single() as FieldSymbol; Assert.True(n1.IsConst); Assert.False(n1.IsVolatile); Assert.True(n1.IsStatic); Assert.Equal(0, n1.TypeWithAnnotations.CustomModifiers.Length); var n2 = a.GetMembers("N2").Single() as FieldSymbol; Assert.False(n2.IsConst); Assert.True(n2.IsVolatile); Assert.False(n2.IsStatic); Assert.Equal(1, n2.TypeWithAnnotations.CustomModifiers.Length); CustomModifier mod = n2.TypeWithAnnotations.CustomModifiers[0]; Assert.False(mod.IsOptional); Assert.Equal("System.Runtime.CompilerServices.IsVolatile[missing]", mod.Modifier.ToTestDisplayString()); var n3 = a.GetMembers("N3").Single() as FieldSymbol; Assert.False(n3.IsConst); Assert.False(n3.IsVolatile); Assert.True(n3.IsStatic); Assert.Equal(0, n3.TypeWithAnnotations.CustomModifiers.Length); } [Fact] public void Nullable() { var text = @" class A { int? F = null; } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var a = global.GetTypeMembers("A", 0).Single(); var sym = a.GetMembers("F").Single() as FieldSymbol; Assert.Equal("System.Int32? A.F", sym.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, sym.Type.TypeKind); Assert.Equal("System.Int32?", sym.Type.ToTestDisplayString()); } [Fact] public void Generic01() { var text = @"public class C<T> { internal struct S<V> { public System.Collections.Generic.List<T> M<V>(V p) { return null; } private System.Collections.Generic.List<T> field1; internal System.Collections.Generic.IList<V> field2; public S<string> field3; } } "; var comp = CreateCompilation(text); var type1 = comp.GlobalNamespace.GetTypeMembers("C", 1).Single(); var type2 = type1.GetTypeMembers("S").Single(); var s = type2.GetMembers("M").Single() as MethodSymbol; Assert.Equal("M", s.Name); Assert.Equal("System.Collections.Generic.List<T> C<T>.S<V>.M<V>(V p)", s.ToTestDisplayString()); var sym = type2.GetMembers("field1").Single() as FieldSymbol; Assert.Equal("System.Collections.Generic.List<T> C<T>.S<V>.field1", sym.ToTestDisplayString()); Assert.Equal(TypeKind.Class, sym.Type.TypeKind); Assert.Equal("System.Collections.Generic.List<T>", sym.Type.ToTestDisplayString()); sym = type2.GetMembers("field2").Single() as FieldSymbol; Assert.Equal("System.Collections.Generic.IList<V> C<T>.S<V>.field2", sym.ToTestDisplayString()); Assert.Equal(TypeKind.Interface, sym.Type.TypeKind); Assert.Equal("System.Collections.Generic.IList<V>", sym.Type.ToTestDisplayString()); sym = type2.GetMembers("field3").Single() as FieldSymbol; Assert.Equal("C<T>.S<System.String> C<T>.S<V>.field3", sym.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, sym.Type.TypeKind); Assert.Equal("C<T>.S<System.String>", sym.Type.ToTestDisplayString()); } [WorkItem(537401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537401")] [Fact] public void EventEscapedIdentifier() { var text = @" delegate void @out(); class C1 { @out @in; } "; var comp = CreateCompilation(Parse(text)); NamedTypeSymbol c1 = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("C1").Single(); FieldSymbol ein = (FieldSymbol)c1.GetMembers("in").Single(); Assert.Equal("in", ein.Name); Assert.Equal("C1.@in", ein.ToString()); NamedTypeSymbol dout = (NamedTypeSymbol)ein.Type; Assert.Equal("out", dout.Name); Assert.Equal("@out", dout.ToString()); } [WorkItem(539653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539653")] [Fact] public void ConstFieldWithoutValueErr() { var text = @" class C { const int x; } "; var comp = CreateCompilation(Parse(text)); NamedTypeSymbol type1 = (NamedTypeSymbol)comp.SourceModule.GlobalNamespace.GetMembers("C").Single(); FieldSymbol mem = (FieldSymbol)type1.GetMembers("x").Single(); Assert.Equal("x", mem.Name); Assert.True(mem.IsConst); Assert.False(mem.HasConstantValue); Assert.Null(mem.ConstantValue); } [WorkItem(543538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543538")] [Fact] public void Error_InvalidConst() { var source = @" class A { const delegate void D(); protected virtual void Finalize const () { } } "; // CONSIDER: Roslyn's cascading errors are much uglier than Dev10's. CreateCompilationWithMscorlib46(source, parseOptions: TestOptions.Regular).VerifyDiagnostics( // (4,11): error CS1031: Type expected // const delegate void D(); Diagnostic(ErrorCode.ERR_TypeExpected, "delegate").WithLocation(4, 11), // (4,11): error CS1001: Identifier expected // const delegate void D(); Diagnostic(ErrorCode.ERR_IdentifierExpected, "delegate").WithLocation(4, 11), // (4,11): error CS0145: A const field requires a value to be provided // const delegate void D(); Diagnostic(ErrorCode.ERR_ConstValueRequired, "delegate").WithLocation(4, 11), // (4,11): error CS1002: ; expected // const delegate void D(); Diagnostic(ErrorCode.ERR_SemicolonExpected, "delegate").WithLocation(4, 11), // (5,37): error CS1002: ; expected // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_SemicolonExpected, "const").WithLocation(5, 37), // (5,44): error CS8124: Tuple must contain at least two elements. // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(5, 44), // (5,46): error CS1001: Identifier expected // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_IdentifierExpected, "{").WithLocation(5, 46), // (5,46): error CS0145: A const field requires a value to be provided // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_ConstValueRequired, "{").WithLocation(5, 46), // (5,46): error CS1003: Syntax error, ',' expected // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_SyntaxError, "{").WithArguments(",", "{").WithLocation(5, 46), // (5,48): error CS1002: ; expected // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(5, 48), // (6,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(6, 1), // (5,28): error CS0106: The modifier 'virtual' is not valid for this item // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Finalize").WithArguments("virtual").WithLocation(5, 28), // (5,43): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "()").WithArguments("System.ValueTuple`2").WithLocation(5, 43), // (5,23): error CS0670: Field cannot have void type // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void").WithLocation(5, 23), // (5,46): error CS0102: The type 'A' already contains a definition for '' // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("A", "").WithLocation(5, 46), // (5,28): warning CS0649: Field 'A.Finalize' is never assigned to, and will always have its default value // protected virtual void Finalize const () { } Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Finalize").WithArguments("A.Finalize", "").WithLocation(5, 28) ); } [WorkItem(543538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543538")] [Fact] public void Error_InvalidConstWithCSharp6() { var source = @" class A { const delegate void D(); protected virtual void Finalize const () { } } "; // CONSIDER: Roslyn's cascading errors are much uglier than Dev10's. CreateCompilationWithMscorlib46(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)).VerifyDiagnostics( // (4,11): error CS1031: Type expected // const delegate void D(); Diagnostic(ErrorCode.ERR_TypeExpected, "delegate").WithLocation(4, 11), // (4,11): error CS1001: Identifier expected // const delegate void D(); Diagnostic(ErrorCode.ERR_IdentifierExpected, "delegate").WithLocation(4, 11), // (4,11): error CS0145: A const field requires a value to be provided // const delegate void D(); Diagnostic(ErrorCode.ERR_ConstValueRequired, "delegate").WithLocation(4, 11), // (4,11): error CS1002: ; expected // const delegate void D(); Diagnostic(ErrorCode.ERR_SemicolonExpected, "delegate").WithLocation(4, 11), // (5,37): error CS1002: ; expected // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_SemicolonExpected, "const").WithLocation(5, 37), // (5,43): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater. // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "()").WithArguments("tuples", "7.0").WithLocation(5, 43), // (5,44): error CS8124: Tuple must contain at least two elements. // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(5, 44), // (5,46): error CS1001: Identifier expected // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_IdentifierExpected, "{").WithLocation(5, 46), // (5,46): error CS0145: A const field requires a value to be provided // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_ConstValueRequired, "{").WithLocation(5, 46), // (5,46): error CS1003: Syntax error, ',' expected // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_SyntaxError, "{").WithArguments(",", "{").WithLocation(5, 46), // (5,48): error CS1002: ; expected // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(5, 48), // (6,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(6, 1), // (5,28): error CS0106: The modifier 'virtual' is not valid for this item // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Finalize").WithArguments("virtual").WithLocation(5, 28), // (5,43): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "()").WithArguments("System.ValueTuple`2").WithLocation(5, 43), // (5,23): error CS0670: Field cannot have void type // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void").WithLocation(5, 23), // (5,46): error CS0102: The type 'A' already contains a definition for '' // protected virtual void Finalize const () { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("A", "").WithLocation(5, 46), // (5,28): warning CS0649: Field 'A.Finalize' is never assigned to, and will always have its default value // protected virtual void Finalize const () { } Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Finalize").WithArguments("A.Finalize", "").WithLocation(5, 28) ); } [WorkItem(543791, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543791")] [Fact] public void MultipleDeclaratorsOneError() { var source = @" class A { Unknown a, b; } "; CreateCompilation(source).VerifyDiagnostics( // (4,5): error CS0246: The type or namespace name 'Unknown' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unknown").WithArguments("Unknown"), // (4,13): warning CS0169: The field 'A.a' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "a").WithArguments("A.a"), // (4,16): warning CS0169: The field 'A.b' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "b").WithArguments("A.b")); } /// <summary> /// Fields named "value__" should be marked rtspecialname. /// </summary> [WorkItem(546185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546185")] [ClrOnlyFact(ClrOnlyReason.Unknown, Skip = "https://github.com/dotnet/roslyn/issues/6190")] public void RTSpecialName() { var source = @"class A { object value__ = null; } class B { object VALUE__ = null; } class C { void value__() { } } class D { object value__ { get; set; } } class E { event System.Action value__; } class F { event System.Action value__ { add { } remove { } } } class G { interface value__ { } } class H { class value__ { } } class K { static System.Action<object> F() { object value__; return v => { value__ = v; }; } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (19,25): warning CS0067: The event 'E.value__' is never used // event System.Action value__; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "value__").WithArguments("E.value__"), // (7,12): warning CS0414: The field 'B.VALUE__' is assigned but its value is never used // object VALUE__ = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "VALUE__").WithArguments("B.VALUE__"), // (3,12): warning CS0414: The field 'A.value__' is assigned but its value is never used // object value__ = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "value__").WithArguments("A.value__")); // PEVerify should not report "Field value__ ... is not marked RTSpecialName". var verifier = new CompilationVerifier(compilation); verifier.EmitAndVerify( "Error: Field name value__ is reserved for Enums only.", "Error: Field name value__ is reserved for Enums only.", "Error: Field name value__ is reserved for Enums only."); } [WorkItem(26364, "https://github.com/dotnet/roslyn/issues/26364"), WorkItem(54799, "https://github.com/dotnet/roslyn/issues/54799")] [Fact] public void FixedSizeBufferTrue() { var text = @" unsafe struct S { private fixed byte goo[10]; } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var s = global.GetTypeMember("S"); var goo = (IFieldSymbol)s.GetMember("goo").GetPublicSymbol(); Assert.True(goo.IsFixedSizeBuffer); Assert.Equal(10, goo.FixedSize); } [WorkItem(26364, "https://github.com/dotnet/roslyn/issues/26364"), WorkItem(54799, "https://github.com/dotnet/roslyn/issues/54799")] [Fact] public void FixedSizeBufferFalse() { var text = @" unsafe struct S { private byte goo; } "; var comp = CreateCompilation(text); var global = comp.GlobalNamespace; var s = global.GetTypeMember("S"); var goo = (IFieldSymbol)s.GetMember("goo").GetPublicSymbol(); Assert.False(goo.IsFixedSizeBuffer); Assert.Equal(0, goo.FixedSize); } [Fact] public void StaticFieldDoesNotRequireInstanceReceiver() { var source = @" class C { public static int F = 42; }"; var compilation = CreateCompilation(source).VerifyDiagnostics(); var field = compilation.GetMember<FieldSymbol>("C.F"); Assert.False(field.RequiresInstanceReceiver); } [Fact] public void InstanceFieldRequiresInstanceReceiver() { var source = @" class C { public int F = 42; }"; var compilation = CreateCompilation(source).VerifyDiagnostics(); var field = compilation.GetMember<FieldSymbol>("C.F"); Assert.True(field.RequiresInstanceReceiver); } [Fact] public void UnreferencedInterpolatedStringConstants() { var comp = CreateCompilation(@" class C { private static string s1 = $""""; private static readonly string s2 = $""""; private string s3 = $""""; private readonly string s4 = $""""; } struct S { private static string s1 = $""""; private static readonly string s2 = $""""; } "); comp.VerifyDiagnostics(); } } }
1
dotnet/roslyn
55,354
Add IFieldSymbol.FixedSize API
Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
333fred
2021-08-02T22:15:12Z
2021-08-03T21:43:37Z
76bdda7fe502a74f91aee0feb2fe251039be4e82
a81b07d0d5a6b5c5430443fc843e4a730399c946
Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
./src/Compilers/Core/Portable/PublicAPI.Unshipped.txt
*REMOVED*Microsoft.CodeAnalysis.SyntaxNode.IsEquivalentTo(Microsoft.CodeAnalysis.SyntaxNode! other) -> bool abstract Microsoft.CodeAnalysis.SyntaxTree.GetLineMappings(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.LineMapping>! const Microsoft.CodeAnalysis.WellKnownMemberNames.PrintMembersMethodName = "PrintMembers" -> string! Microsoft.CodeAnalysis.Compilation.EmitDifference(Microsoft.CodeAnalysis.Emit.EmitBaseline! baseline, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Emit.SemanticEdit>! edits, System.Func<Microsoft.CodeAnalysis.ISymbol!, bool>! isAddedSymbol, System.IO.Stream! metadataStream, System.IO.Stream! ilStream, System.IO.Stream! pdbStream, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> Microsoft.CodeAnalysis.Emit.EmitDifferenceResult! Microsoft.CodeAnalysis.Emit.EmitDifferenceResult.ChangedTypes.get -> System.Collections.Immutable.ImmutableArray<System.Reflection.Metadata.TypeDefinitionHandle> Microsoft.CodeAnalysis.Emit.EmitDifferenceResult.UpdatedMethods.get -> System.Collections.Immutable.ImmutableArray<System.Reflection.Metadata.MethodDefinitionHandle> Microsoft.CodeAnalysis.Emit.SemanticEditKind.Replace = 4 -> Microsoft.CodeAnalysis.Emit.SemanticEditKind Microsoft.CodeAnalysis.GeneratorAttribute.GeneratorAttribute(string! firstLanguage, params string![]! additionalLanguages) -> void Microsoft.CodeAnalysis.GeneratorAttribute.Languages.get -> string![]! Microsoft.CodeAnalysis.GeneratorDriver.ReplaceAdditionalText(Microsoft.CodeAnalysis.AdditionalText! oldText, Microsoft.CodeAnalysis.AdditionalText! newText) -> Microsoft.CodeAnalysis.GeneratorDriver! Microsoft.CodeAnalysis.GeneratorDriver.WithUpdatedAnalyzerConfigOptions(Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider! newOptions) -> Microsoft.CodeAnalysis.GeneratorDriver! Microsoft.CodeAnalysis.GeneratorDriver.WithUpdatedParseOptions(Microsoft.CodeAnalysis.ParseOptions! newOptions) -> Microsoft.CodeAnalysis.GeneratorDriver! Microsoft.CodeAnalysis.GeneratorDriverOptions Microsoft.CodeAnalysis.GeneratorDriverOptions.GeneratorDriverOptions() -> void Microsoft.CodeAnalysis.GeneratorDriverOptions.GeneratorDriverOptions(Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind disabledOutputs) -> void Microsoft.CodeAnalysis.GeneratorExtensions Microsoft.CodeAnalysis.IFieldSymbol.IsExplicitlyNamedTupleElement.get -> bool Microsoft.CodeAnalysis.GeneratorExecutionContext.SyntaxContextReceiver.get -> Microsoft.CodeAnalysis.ISyntaxContextReceiver? Microsoft.CodeAnalysis.GeneratorInitializationContext.RegisterForSyntaxNotifications(Microsoft.CodeAnalysis.SyntaxContextReceiverCreator! receiverCreator) -> void Microsoft.CodeAnalysis.GeneratorSyntaxContext Microsoft.CodeAnalysis.GeneratorSyntaxContext.GeneratorSyntaxContext() -> void Microsoft.CodeAnalysis.GeneratorSyntaxContext.Node.get -> Microsoft.CodeAnalysis.SyntaxNode! Microsoft.CodeAnalysis.GeneratorSyntaxContext.SemanticModel.get -> Microsoft.CodeAnalysis.SemanticModel! Microsoft.CodeAnalysis.IIncrementalGenerator Microsoft.CodeAnalysis.IIncrementalGenerator.Initialize(Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext context) -> void Microsoft.CodeAnalysis.IMethodSymbol.IsPartialDefinition.get -> bool Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.AdditionalTextsProvider.get -> Microsoft.CodeAnalysis.IncrementalValuesProvider<Microsoft.CodeAnalysis.AdditionalText!> Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.AnalyzerConfigOptionsProvider.get -> Microsoft.CodeAnalysis.IncrementalValueProvider<Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider!> Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.CompilationProvider.get -> Microsoft.CodeAnalysis.IncrementalValueProvider<Microsoft.CodeAnalysis.Compilation!> Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.IncrementalGeneratorInitializationContext() -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.ParseOptionsProvider.get -> Microsoft.CodeAnalysis.IncrementalValueProvider<Microsoft.CodeAnalysis.ParseOptions!> Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterImplementationSourceOutput<TSource>(Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Action<Microsoft.CodeAnalysis.SourceProductionContext, TSource>! action) -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterImplementationSourceOutput<TSource>(Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Action<Microsoft.CodeAnalysis.SourceProductionContext, TSource>! action) -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterPostInitializationOutput(System.Action<Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext>! callback) -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterSourceOutput<TSource>(Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Action<Microsoft.CodeAnalysis.SourceProductionContext, TSource>! action) -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterSourceOutput<TSource>(Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Action<Microsoft.CodeAnalysis.SourceProductionContext, TSource>! action) -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.SyntaxProvider.get -> Microsoft.CodeAnalysis.SyntaxValueProvider Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind.Implementation = 4 -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind.None = 0 -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind.PostInit = 2 -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind.Source = 1 -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext.AddSource(string! hintName, Microsoft.CodeAnalysis.Text.SourceText! sourceText) -> void Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext.AddSource(string! hintName, string! source) -> void Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext.CancellationToken.get -> System.Threading.CancellationToken Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext.IncrementalGeneratorPostInitializationContext() -> void Microsoft.CodeAnalysis.IncrementalValueProvider<TValue> Microsoft.CodeAnalysis.IncrementalValueProvider<TValue>.IncrementalValueProvider() -> void Microsoft.CodeAnalysis.IncrementalValueProviderExtensions Microsoft.CodeAnalysis.IncrementalValuesProvider<TValues> Microsoft.CodeAnalysis.IncrementalValuesProvider<TValues>.IncrementalValuesProvider() -> void Microsoft.CodeAnalysis.ISyntaxContextReceiver Microsoft.CodeAnalysis.ISyntaxContextReceiver.OnVisitSyntaxNode(Microsoft.CodeAnalysis.GeneratorSyntaxContext context) -> void Microsoft.CodeAnalysis.GeneratorInitializationContext.RegisterForPostInitialization(System.Action<Microsoft.CodeAnalysis.GeneratorPostInitializationContext>! callback) -> void Microsoft.CodeAnalysis.GeneratorPostInitializationContext Microsoft.CodeAnalysis.GeneratorPostInitializationContext.AddSource(string! hintName, Microsoft.CodeAnalysis.Text.SourceText! sourceText) -> void Microsoft.CodeAnalysis.GeneratorPostInitializationContext.AddSource(string! hintName, string! source) -> void Microsoft.CodeAnalysis.GeneratorPostInitializationContext.CancellationToken.get -> System.Threading.CancellationToken Microsoft.CodeAnalysis.GeneratorPostInitializationContext.GeneratorPostInitializationContext() -> void Microsoft.CodeAnalysis.IMethodSymbol.MethodImplementationFlags.get -> System.Reflection.MethodImplAttributes Microsoft.CodeAnalysis.ITypeSymbol.IsRecord.get -> bool Microsoft.CodeAnalysis.LineMapping Microsoft.CodeAnalysis.LineMapping.CharacterOffset.get -> int? Microsoft.CodeAnalysis.LineMapping.Equals(Microsoft.CodeAnalysis.LineMapping other) -> bool Microsoft.CodeAnalysis.LineMapping.IsHidden.get -> bool Microsoft.CodeAnalysis.LineMapping.LineMapping() -> void Microsoft.CodeAnalysis.LineMapping.LineMapping(Microsoft.CodeAnalysis.Text.LinePositionSpan span, int? characterOffset, Microsoft.CodeAnalysis.FileLinePositionSpan mappedSpan) -> void Microsoft.CodeAnalysis.LineMapping.MappedSpan.get -> Microsoft.CodeAnalysis.FileLinePositionSpan Microsoft.CodeAnalysis.LineMapping.Span.get -> Microsoft.CodeAnalysis.Text.LinePositionSpan override Microsoft.CodeAnalysis.LineMapping.Equals(object? obj) -> bool override Microsoft.CodeAnalysis.LineMapping.GetHashCode() -> int override Microsoft.CodeAnalysis.LineMapping.ToString() -> string? Microsoft.CodeAnalysis.Operations.ISwitchExpressionOperation.IsExhaustive.get -> bool Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument> Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument>.OperationWalker() -> void Microsoft.CodeAnalysis.SourceProductionContext Microsoft.CodeAnalysis.SourceProductionContext.AddSource(string! hintName, Microsoft.CodeAnalysis.Text.SourceText! sourceText) -> void Microsoft.CodeAnalysis.SourceProductionContext.AddSource(string! hintName, string! source) -> void Microsoft.CodeAnalysis.SourceProductionContext.CancellationToken.get -> System.Threading.CancellationToken Microsoft.CodeAnalysis.SourceProductionContext.ReportDiagnostic(Microsoft.CodeAnalysis.Diagnostic! diagnostic) -> void Microsoft.CodeAnalysis.SourceProductionContext.SourceProductionContext() -> void Microsoft.CodeAnalysis.SymbolDisplayPartKind.RecordClassName = 31 -> Microsoft.CodeAnalysis.SymbolDisplayPartKind const Microsoft.CodeAnalysis.WellKnownDiagnosticTags.CompilationEnd = "CompilationEnd" -> string! Microsoft.CodeAnalysis.SymbolDisplayPartKind.RecordStructName = 32 -> Microsoft.CodeAnalysis.SymbolDisplayPartKind Microsoft.CodeAnalysis.SyntaxContextReceiverCreator Microsoft.CodeAnalysis.SyntaxNode.IsEquivalentTo(Microsoft.CodeAnalysis.SyntaxNode? other) -> bool Microsoft.CodeAnalysis.SyntaxNode.IsIncrementallyIdenticalTo(Microsoft.CodeAnalysis.SyntaxNode? other) -> bool Microsoft.CodeAnalysis.SyntaxNodeOrToken.IsIncrementallyIdenticalTo(Microsoft.CodeAnalysis.SyntaxNodeOrToken other) -> bool Microsoft.CodeAnalysis.SyntaxToken.IsIncrementallyIdenticalTo(Microsoft.CodeAnalysis.SyntaxToken token) -> bool Microsoft.CodeAnalysis.SyntaxValueProvider Microsoft.CodeAnalysis.SyntaxValueProvider.CreateSyntaxProvider<T>(System.Func<Microsoft.CodeAnalysis.SyntaxNode!, System.Threading.CancellationToken, bool>! predicate, System.Func<Microsoft.CodeAnalysis.GeneratorSyntaxContext, System.Threading.CancellationToken, T>! transform) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<T> Microsoft.CodeAnalysis.SyntaxValueProvider.SyntaxValueProvider() -> void override Microsoft.CodeAnalysis.Text.TextChangeRange.ToString() -> string! readonly Microsoft.CodeAnalysis.GeneratorDriverOptions.DisabledOutputs -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind static Microsoft.CodeAnalysis.CaseInsensitiveComparison.Compare(System.ReadOnlySpan<char> left, System.ReadOnlySpan<char> right) -> int static Microsoft.CodeAnalysis.CaseInsensitiveComparison.Equals(System.ReadOnlySpan<char> left, System.ReadOnlySpan<char> right) -> bool override Microsoft.CodeAnalysis.Diagnostics.AnalyzerFileReference.GetGenerators(string! language) -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ISourceGenerator!> override Microsoft.CodeAnalysis.Diagnostics.AnalyzerFileReference.GetGeneratorsForAllLanguages() -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ISourceGenerator!> override Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument>.DefaultVisit(Microsoft.CodeAnalysis.IOperation! operation, TArgument argument) -> object? override Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument>.Visit(Microsoft.CodeAnalysis.IOperation? operation, TArgument argument) -> object? static Microsoft.CodeAnalysis.Emit.SemanticEdit.operator !=(Microsoft.CodeAnalysis.Emit.SemanticEdit left, Microsoft.CodeAnalysis.Emit.SemanticEdit right) -> bool static Microsoft.CodeAnalysis.Emit.SemanticEdit.operator ==(Microsoft.CodeAnalysis.Emit.SemanticEdit left, Microsoft.CodeAnalysis.Emit.SemanticEdit right) -> bool static Microsoft.CodeAnalysis.FileLinePositionSpan.operator !=(Microsoft.CodeAnalysis.FileLinePositionSpan left, Microsoft.CodeAnalysis.FileLinePositionSpan right) -> bool static Microsoft.CodeAnalysis.FileLinePositionSpan.operator ==(Microsoft.CodeAnalysis.FileLinePositionSpan left, Microsoft.CodeAnalysis.FileLinePositionSpan right) -> bool static Microsoft.CodeAnalysis.GeneratorExtensions.AsSourceGenerator(this Microsoft.CodeAnalysis.IIncrementalGenerator! incrementalGenerator) -> Microsoft.CodeAnalysis.ISourceGenerator! static Microsoft.CodeAnalysis.GeneratorExtensions.GetGeneratorType(this Microsoft.CodeAnalysis.ISourceGenerator! generator) -> System.Type! static Microsoft.CodeAnalysis.LineMapping.operator !=(Microsoft.CodeAnalysis.LineMapping left, Microsoft.CodeAnalysis.LineMapping right) -> bool static Microsoft.CodeAnalysis.LineMapping.operator ==(Microsoft.CodeAnalysis.LineMapping left, Microsoft.CodeAnalysis.LineMapping right) -> bool static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Collect<TSource>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source) -> Microsoft.CodeAnalysis.IncrementalValueProvider<System.Collections.Immutable.ImmutableArray<TSource>> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Combine<TLeft, TRight>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TLeft> provider1, Microsoft.CodeAnalysis.IncrementalValueProvider<TRight> provider2) -> Microsoft.CodeAnalysis.IncrementalValueProvider<(TLeft Left, TRight Right)> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Combine<TLeft, TRight>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TLeft> provider1, Microsoft.CodeAnalysis.IncrementalValueProvider<TRight> provider2) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<(TLeft Left, TRight Right)> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Select<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, TResult>! selector) -> Microsoft.CodeAnalysis.IncrementalValueProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Select<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, TResult>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.SelectMany<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, System.Collections.Generic.IEnumerable<TResult>!>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.SelectMany<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, System.Collections.Immutable.ImmutableArray<TResult>>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.SelectMany<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, System.Collections.Generic.IEnumerable<TResult>!>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.SelectMany<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, System.Collections.Immutable.ImmutableArray<TResult>>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Where<TSource>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Func<TSource, bool>! predicate) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.WithComparer<TSource>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Collections.Generic.IEqualityComparer<TSource>! comparer) -> Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.WithComparer<TSource>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Collections.Generic.IEqualityComparer<TSource>! comparer) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> virtual Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference.GetGenerators(string! language) -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ISourceGenerator!> virtual Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference.GetGeneratorsForAllLanguages() -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ISourceGenerator!> abstract Microsoft.CodeAnalysis.Compilation.GetUsedAssemblyReferences(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.MetadataReference!>
*REMOVED*Microsoft.CodeAnalysis.SyntaxNode.IsEquivalentTo(Microsoft.CodeAnalysis.SyntaxNode! other) -> bool abstract Microsoft.CodeAnalysis.SyntaxTree.GetLineMappings(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.LineMapping>! const Microsoft.CodeAnalysis.WellKnownMemberNames.PrintMembersMethodName = "PrintMembers" -> string! Microsoft.CodeAnalysis.Compilation.EmitDifference(Microsoft.CodeAnalysis.Emit.EmitBaseline! baseline, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Emit.SemanticEdit>! edits, System.Func<Microsoft.CodeAnalysis.ISymbol!, bool>! isAddedSymbol, System.IO.Stream! metadataStream, System.IO.Stream! ilStream, System.IO.Stream! pdbStream, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> Microsoft.CodeAnalysis.Emit.EmitDifferenceResult! Microsoft.CodeAnalysis.Emit.EmitDifferenceResult.ChangedTypes.get -> System.Collections.Immutable.ImmutableArray<System.Reflection.Metadata.TypeDefinitionHandle> Microsoft.CodeAnalysis.Emit.EmitDifferenceResult.UpdatedMethods.get -> System.Collections.Immutable.ImmutableArray<System.Reflection.Metadata.MethodDefinitionHandle> Microsoft.CodeAnalysis.Emit.SemanticEditKind.Replace = 4 -> Microsoft.CodeAnalysis.Emit.SemanticEditKind Microsoft.CodeAnalysis.GeneratorAttribute.GeneratorAttribute(string! firstLanguage, params string![]! additionalLanguages) -> void Microsoft.CodeAnalysis.GeneratorAttribute.Languages.get -> string![]! Microsoft.CodeAnalysis.GeneratorDriver.ReplaceAdditionalText(Microsoft.CodeAnalysis.AdditionalText! oldText, Microsoft.CodeAnalysis.AdditionalText! newText) -> Microsoft.CodeAnalysis.GeneratorDriver! Microsoft.CodeAnalysis.GeneratorDriver.WithUpdatedAnalyzerConfigOptions(Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider! newOptions) -> Microsoft.CodeAnalysis.GeneratorDriver! Microsoft.CodeAnalysis.GeneratorDriver.WithUpdatedParseOptions(Microsoft.CodeAnalysis.ParseOptions! newOptions) -> Microsoft.CodeAnalysis.GeneratorDriver! Microsoft.CodeAnalysis.GeneratorDriverOptions Microsoft.CodeAnalysis.GeneratorDriverOptions.GeneratorDriverOptions() -> void Microsoft.CodeAnalysis.GeneratorDriverOptions.GeneratorDriverOptions(Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind disabledOutputs) -> void Microsoft.CodeAnalysis.GeneratorExtensions Microsoft.CodeAnalysis.IFieldSymbol.FixedSize.get -> int Microsoft.CodeAnalysis.IFieldSymbol.IsExplicitlyNamedTupleElement.get -> bool Microsoft.CodeAnalysis.GeneratorExecutionContext.SyntaxContextReceiver.get -> Microsoft.CodeAnalysis.ISyntaxContextReceiver? Microsoft.CodeAnalysis.GeneratorInitializationContext.RegisterForSyntaxNotifications(Microsoft.CodeAnalysis.SyntaxContextReceiverCreator! receiverCreator) -> void Microsoft.CodeAnalysis.GeneratorSyntaxContext Microsoft.CodeAnalysis.GeneratorSyntaxContext.GeneratorSyntaxContext() -> void Microsoft.CodeAnalysis.GeneratorSyntaxContext.Node.get -> Microsoft.CodeAnalysis.SyntaxNode! Microsoft.CodeAnalysis.GeneratorSyntaxContext.SemanticModel.get -> Microsoft.CodeAnalysis.SemanticModel! Microsoft.CodeAnalysis.IIncrementalGenerator Microsoft.CodeAnalysis.IIncrementalGenerator.Initialize(Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext context) -> void Microsoft.CodeAnalysis.IMethodSymbol.IsPartialDefinition.get -> bool Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.AdditionalTextsProvider.get -> Microsoft.CodeAnalysis.IncrementalValuesProvider<Microsoft.CodeAnalysis.AdditionalText!> Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.AnalyzerConfigOptionsProvider.get -> Microsoft.CodeAnalysis.IncrementalValueProvider<Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider!> Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.CompilationProvider.get -> Microsoft.CodeAnalysis.IncrementalValueProvider<Microsoft.CodeAnalysis.Compilation!> Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.IncrementalGeneratorInitializationContext() -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.ParseOptionsProvider.get -> Microsoft.CodeAnalysis.IncrementalValueProvider<Microsoft.CodeAnalysis.ParseOptions!> Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterImplementationSourceOutput<TSource>(Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Action<Microsoft.CodeAnalysis.SourceProductionContext, TSource>! action) -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterImplementationSourceOutput<TSource>(Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Action<Microsoft.CodeAnalysis.SourceProductionContext, TSource>! action) -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterPostInitializationOutput(System.Action<Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext>! callback) -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterSourceOutput<TSource>(Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Action<Microsoft.CodeAnalysis.SourceProductionContext, TSource>! action) -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterSourceOutput<TSource>(Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Action<Microsoft.CodeAnalysis.SourceProductionContext, TSource>! action) -> void Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.SyntaxProvider.get -> Microsoft.CodeAnalysis.SyntaxValueProvider Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind.Implementation = 4 -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind.None = 0 -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind.PostInit = 2 -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind.Source = 1 -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext.AddSource(string! hintName, Microsoft.CodeAnalysis.Text.SourceText! sourceText) -> void Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext.AddSource(string! hintName, string! source) -> void Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext.CancellationToken.get -> System.Threading.CancellationToken Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext.IncrementalGeneratorPostInitializationContext() -> void Microsoft.CodeAnalysis.IncrementalValueProvider<TValue> Microsoft.CodeAnalysis.IncrementalValueProvider<TValue>.IncrementalValueProvider() -> void Microsoft.CodeAnalysis.IncrementalValueProviderExtensions Microsoft.CodeAnalysis.IncrementalValuesProvider<TValues> Microsoft.CodeAnalysis.IncrementalValuesProvider<TValues>.IncrementalValuesProvider() -> void Microsoft.CodeAnalysis.ISyntaxContextReceiver Microsoft.CodeAnalysis.ISyntaxContextReceiver.OnVisitSyntaxNode(Microsoft.CodeAnalysis.GeneratorSyntaxContext context) -> void Microsoft.CodeAnalysis.GeneratorInitializationContext.RegisterForPostInitialization(System.Action<Microsoft.CodeAnalysis.GeneratorPostInitializationContext>! callback) -> void Microsoft.CodeAnalysis.GeneratorPostInitializationContext Microsoft.CodeAnalysis.GeneratorPostInitializationContext.AddSource(string! hintName, Microsoft.CodeAnalysis.Text.SourceText! sourceText) -> void Microsoft.CodeAnalysis.GeneratorPostInitializationContext.AddSource(string! hintName, string! source) -> void Microsoft.CodeAnalysis.GeneratorPostInitializationContext.CancellationToken.get -> System.Threading.CancellationToken Microsoft.CodeAnalysis.GeneratorPostInitializationContext.GeneratorPostInitializationContext() -> void Microsoft.CodeAnalysis.IMethodSymbol.MethodImplementationFlags.get -> System.Reflection.MethodImplAttributes Microsoft.CodeAnalysis.ITypeSymbol.IsRecord.get -> bool Microsoft.CodeAnalysis.LineMapping Microsoft.CodeAnalysis.LineMapping.CharacterOffset.get -> int? Microsoft.CodeAnalysis.LineMapping.Equals(Microsoft.CodeAnalysis.LineMapping other) -> bool Microsoft.CodeAnalysis.LineMapping.IsHidden.get -> bool Microsoft.CodeAnalysis.LineMapping.LineMapping() -> void Microsoft.CodeAnalysis.LineMapping.LineMapping(Microsoft.CodeAnalysis.Text.LinePositionSpan span, int? characterOffset, Microsoft.CodeAnalysis.FileLinePositionSpan mappedSpan) -> void Microsoft.CodeAnalysis.LineMapping.MappedSpan.get -> Microsoft.CodeAnalysis.FileLinePositionSpan Microsoft.CodeAnalysis.LineMapping.Span.get -> Microsoft.CodeAnalysis.Text.LinePositionSpan override Microsoft.CodeAnalysis.LineMapping.Equals(object? obj) -> bool override Microsoft.CodeAnalysis.LineMapping.GetHashCode() -> int override Microsoft.CodeAnalysis.LineMapping.ToString() -> string? Microsoft.CodeAnalysis.Operations.ISwitchExpressionOperation.IsExhaustive.get -> bool Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument> Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument>.OperationWalker() -> void Microsoft.CodeAnalysis.SourceProductionContext Microsoft.CodeAnalysis.SourceProductionContext.AddSource(string! hintName, Microsoft.CodeAnalysis.Text.SourceText! sourceText) -> void Microsoft.CodeAnalysis.SourceProductionContext.AddSource(string! hintName, string! source) -> void Microsoft.CodeAnalysis.SourceProductionContext.CancellationToken.get -> System.Threading.CancellationToken Microsoft.CodeAnalysis.SourceProductionContext.ReportDiagnostic(Microsoft.CodeAnalysis.Diagnostic! diagnostic) -> void Microsoft.CodeAnalysis.SourceProductionContext.SourceProductionContext() -> void Microsoft.CodeAnalysis.SymbolDisplayPartKind.RecordClassName = 31 -> Microsoft.CodeAnalysis.SymbolDisplayPartKind const Microsoft.CodeAnalysis.WellKnownDiagnosticTags.CompilationEnd = "CompilationEnd" -> string! Microsoft.CodeAnalysis.SymbolDisplayPartKind.RecordStructName = 32 -> Microsoft.CodeAnalysis.SymbolDisplayPartKind Microsoft.CodeAnalysis.SyntaxContextReceiverCreator Microsoft.CodeAnalysis.SyntaxNode.IsEquivalentTo(Microsoft.CodeAnalysis.SyntaxNode? other) -> bool Microsoft.CodeAnalysis.SyntaxNode.IsIncrementallyIdenticalTo(Microsoft.CodeAnalysis.SyntaxNode? other) -> bool Microsoft.CodeAnalysis.SyntaxNodeOrToken.IsIncrementallyIdenticalTo(Microsoft.CodeAnalysis.SyntaxNodeOrToken other) -> bool Microsoft.CodeAnalysis.SyntaxToken.IsIncrementallyIdenticalTo(Microsoft.CodeAnalysis.SyntaxToken token) -> bool Microsoft.CodeAnalysis.SyntaxValueProvider Microsoft.CodeAnalysis.SyntaxValueProvider.CreateSyntaxProvider<T>(System.Func<Microsoft.CodeAnalysis.SyntaxNode!, System.Threading.CancellationToken, bool>! predicate, System.Func<Microsoft.CodeAnalysis.GeneratorSyntaxContext, System.Threading.CancellationToken, T>! transform) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<T> Microsoft.CodeAnalysis.SyntaxValueProvider.SyntaxValueProvider() -> void override Microsoft.CodeAnalysis.Text.TextChangeRange.ToString() -> string! readonly Microsoft.CodeAnalysis.GeneratorDriverOptions.DisabledOutputs -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind static Microsoft.CodeAnalysis.CaseInsensitiveComparison.Compare(System.ReadOnlySpan<char> left, System.ReadOnlySpan<char> right) -> int static Microsoft.CodeAnalysis.CaseInsensitiveComparison.Equals(System.ReadOnlySpan<char> left, System.ReadOnlySpan<char> right) -> bool override Microsoft.CodeAnalysis.Diagnostics.AnalyzerFileReference.GetGenerators(string! language) -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ISourceGenerator!> override Microsoft.CodeAnalysis.Diagnostics.AnalyzerFileReference.GetGeneratorsForAllLanguages() -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ISourceGenerator!> override Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument>.DefaultVisit(Microsoft.CodeAnalysis.IOperation! operation, TArgument argument) -> object? override Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument>.Visit(Microsoft.CodeAnalysis.IOperation? operation, TArgument argument) -> object? static Microsoft.CodeAnalysis.Emit.SemanticEdit.operator !=(Microsoft.CodeAnalysis.Emit.SemanticEdit left, Microsoft.CodeAnalysis.Emit.SemanticEdit right) -> bool static Microsoft.CodeAnalysis.Emit.SemanticEdit.operator ==(Microsoft.CodeAnalysis.Emit.SemanticEdit left, Microsoft.CodeAnalysis.Emit.SemanticEdit right) -> bool static Microsoft.CodeAnalysis.FileLinePositionSpan.operator !=(Microsoft.CodeAnalysis.FileLinePositionSpan left, Microsoft.CodeAnalysis.FileLinePositionSpan right) -> bool static Microsoft.CodeAnalysis.FileLinePositionSpan.operator ==(Microsoft.CodeAnalysis.FileLinePositionSpan left, Microsoft.CodeAnalysis.FileLinePositionSpan right) -> bool static Microsoft.CodeAnalysis.GeneratorExtensions.AsSourceGenerator(this Microsoft.CodeAnalysis.IIncrementalGenerator! incrementalGenerator) -> Microsoft.CodeAnalysis.ISourceGenerator! static Microsoft.CodeAnalysis.GeneratorExtensions.GetGeneratorType(this Microsoft.CodeAnalysis.ISourceGenerator! generator) -> System.Type! static Microsoft.CodeAnalysis.LineMapping.operator !=(Microsoft.CodeAnalysis.LineMapping left, Microsoft.CodeAnalysis.LineMapping right) -> bool static Microsoft.CodeAnalysis.LineMapping.operator ==(Microsoft.CodeAnalysis.LineMapping left, Microsoft.CodeAnalysis.LineMapping right) -> bool static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Collect<TSource>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source) -> Microsoft.CodeAnalysis.IncrementalValueProvider<System.Collections.Immutable.ImmutableArray<TSource>> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Combine<TLeft, TRight>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TLeft> provider1, Microsoft.CodeAnalysis.IncrementalValueProvider<TRight> provider2) -> Microsoft.CodeAnalysis.IncrementalValueProvider<(TLeft Left, TRight Right)> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Combine<TLeft, TRight>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TLeft> provider1, Microsoft.CodeAnalysis.IncrementalValueProvider<TRight> provider2) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<(TLeft Left, TRight Right)> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Select<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, TResult>! selector) -> Microsoft.CodeAnalysis.IncrementalValueProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Select<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, TResult>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.SelectMany<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, System.Collections.Generic.IEnumerable<TResult>!>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.SelectMany<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, System.Collections.Immutable.ImmutableArray<TResult>>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.SelectMany<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, System.Collections.Generic.IEnumerable<TResult>!>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.SelectMany<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, System.Collections.Immutable.ImmutableArray<TResult>>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Where<TSource>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Func<TSource, bool>! predicate) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.WithComparer<TSource>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Collections.Generic.IEqualityComparer<TSource>! comparer) -> Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.WithComparer<TSource>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Collections.Generic.IEqualityComparer<TSource>! comparer) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> virtual Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference.GetGenerators(string! language) -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ISourceGenerator!> virtual Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference.GetGeneratorsForAllLanguages() -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ISourceGenerator!> abstract Microsoft.CodeAnalysis.Compilation.GetUsedAssemblyReferences(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.MetadataReference!>
1
dotnet/roslyn
55,354
Add IFieldSymbol.FixedSize API
Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
333fred
2021-08-02T22:15:12Z
2021-08-03T21:43:37Z
76bdda7fe502a74f91aee0feb2fe251039be4e82
a81b07d0d5a6b5c5430443fc843e4a730399c946
Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
./src/Compilers/Core/Portable/Symbols/IFieldSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a field in a class, struct or enum. /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> public interface IFieldSymbol : ISymbol { /// <summary> /// If this field serves as a backing variable for an automatically generated /// property or a field-like event, returns that /// property/event. Otherwise returns null. /// Note, the set of possible associated symbols might be expanded in the future to /// reflect changes in the languages. /// </summary> ISymbol? AssociatedSymbol { get; } /// <summary> /// Returns true if this field was declared as "const" (i.e. is a constant declaration). /// Also returns true for an enum member. /// </summary> bool IsConst { get; } /// <summary> /// Returns true if this field was declared as "readonly". /// </summary> bool IsReadOnly { get; } /// <summary> /// Returns true if this field was declared as "volatile". /// </summary> bool IsVolatile { get; } /// <summary> /// Returns true if this field was declared as "fixed". /// Note that for a fixed-size buffer declaration, this.Type will be a pointer type, of which /// the pointed-to type will be the declared element type of the fixed-size buffer. /// </summary> bool IsFixedSizeBuffer { get; } /// <summary> /// Gets the type of this field. /// </summary> ITypeSymbol Type { get; } /// <summary> /// Gets the top-level nullability of this field. /// </summary> NullableAnnotation NullableAnnotation { get; } /// <summary> /// Returns false if the field wasn't declared as "const", or constant value was omitted or erroneous. /// True otherwise. /// </summary> [MemberNotNullWhen(true, nameof(ConstantValue))] bool HasConstantValue { get; } /// <summary> /// Gets the constant value of this field /// </summary> object? ConstantValue { get; } /// <summary> /// Returns custom modifiers associated with the field, or an empty array if there are none. /// </summary> ImmutableArray<CustomModifier> CustomModifiers { get; } /// <summary> /// Get the original definition of this symbol. If this symbol is derived from another /// symbol by (say) type substitution, this gets the original symbol, as it was defined in /// source or metadata. /// </summary> new IFieldSymbol OriginalDefinition { get; } /// <summary> /// If this field represents a tuple element, returns a corresponding default element field. /// Otherwise returns null. /// </summary> /// <remarks> /// A tuple type will always have default elements such as Item1, Item2, Item3... /// This API allows matching a field that represents a named element, such as "Alice" /// to the corresponding default element field such as "Item1" /// </remarks> IFieldSymbol? CorrespondingTupleField { get; } /// <summary> /// Returns true if this field represents a tuple element which was given an explicit name. /// </summary> bool IsExplicitlyNamedTupleElement { 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.CodeAnalysis; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a field in a class, struct or enum. /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> public interface IFieldSymbol : ISymbol { /// <summary> /// If this field serves as a backing variable for an automatically generated /// property or a field-like event, returns that /// property/event. Otherwise returns null. /// Note, the set of possible associated symbols might be expanded in the future to /// reflect changes in the languages. /// </summary> ISymbol? AssociatedSymbol { get; } /// <summary> /// Returns true if this field was declared as "const" (i.e. is a constant declaration). /// Also returns true for an enum member. /// </summary> bool IsConst { get; } /// <summary> /// Returns true if this field was declared as "readonly". /// </summary> bool IsReadOnly { get; } /// <summary> /// Returns true if this field was declared as "volatile". /// </summary> bool IsVolatile { get; } /// <summary> /// Returns true if this field was declared as "fixed". /// Note that for a fixed-size buffer declaration, this.Type will be a pointer type, of which /// the pointed-to type will be the declared element type of the fixed-size buffer. /// </summary> bool IsFixedSizeBuffer { get; } /// <summary> /// If IsFixedSizeBuffer is true, the value between brackets in the fixed-size-buffer declaration. /// If IsFixedSizeBuffer is false or there is an error (such as a bad constant value in source), FixedSize is 0. /// Note that for fixed-size buffer declaration, this.Type will be a pointer type, of which /// the pointed-to type will be the declared element type of the fixed-size buffer. /// </summary> int FixedSize { get; } /// <summary> /// Gets the type of this field. /// </summary> ITypeSymbol Type { get; } /// <summary> /// Gets the top-level nullability of this field. /// </summary> NullableAnnotation NullableAnnotation { get; } /// <summary> /// Returns false if the field wasn't declared as "const", or constant value was omitted or erroneous. /// True otherwise. /// </summary> [MemberNotNullWhen(true, nameof(ConstantValue))] bool HasConstantValue { get; } /// <summary> /// Gets the constant value of this field /// </summary> object? ConstantValue { get; } /// <summary> /// Returns custom modifiers associated with the field, or an empty array if there are none. /// </summary> ImmutableArray<CustomModifier> CustomModifiers { get; } /// <summary> /// Get the original definition of this symbol. If this symbol is derived from another /// symbol by (say) type substitution, this gets the original symbol, as it was defined in /// source or metadata. /// </summary> new IFieldSymbol OriginalDefinition { get; } /// <summary> /// If this field represents a tuple element, returns a corresponding default element field. /// Otherwise returns null. /// </summary> /// <remarks> /// A tuple type will always have default elements such as Item1, Item2, Item3... /// This API allows matching a field that represents a named element, such as "Alice" /// to the corresponding default element field such as "Item1" /// </remarks> IFieldSymbol? CorrespondingTupleField { get; } /// <summary> /// Returns true if this field represents a tuple element which was given an explicit name. /// </summary> bool IsExplicitlyNamedTupleElement { get; } } }
1
dotnet/roslyn
55,354
Add IFieldSymbol.FixedSize API
Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
333fred
2021-08-02T22:15:12Z
2021-08-03T21:43:37Z
76bdda7fe502a74f91aee0feb2fe251039be4e82
a81b07d0d5a6b5c5430443fc843e4a730399c946
Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
./src/Compilers/VisualBasic/Portable/Symbols/FieldSymbol.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a member variable -- a variable declared as a member of a Class or Structure. ''' </summary> Friend MustInherit Class FieldSymbol Inherits Symbol Implements IFieldSymbol, IFieldSymbolInternal ' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ' Changes to the public interface of this class should remain synchronized with the C# version. ' Do not make any changes to the public interface without making the corresponding change ' to the C# version. ' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Friend Sub New() End Sub ''' <summary> ''' Get the original definition of this symbol. If this symbol is derived from another ''' symbol by (say) type substitution, this gets the original symbol, as it was defined ''' in source or metadata. ''' </summary> Public Overridable Shadows ReadOnly Property OriginalDefinition As FieldSymbol Get ' Default implements returns Me. Return Me End Get End Property Protected NotOverridable Overrides ReadOnly Property OriginalSymbolDefinition As Symbol Get Return Me.OriginalDefinition End Get End Property ''' <summary> ''' Gets the type of this variable. ''' </summary> Public MustOverride ReadOnly Property Type As TypeSymbol ''' <summary> ''' Gets a value indicating whether this instance has declared type. This means a field was declared with an AsClause ''' or in case of const fields with an AsClause whose type is not System.Object ''' </summary> ''' <value> ''' <c>true</c> if this instance has declared type; otherwise, <c>false</c>. ''' </value> Friend Overridable ReadOnly Property HasDeclaredType As Boolean Get Return True End Get End Property ''' <summary> ''' The list of custom modifiers, if any, associated with the member variable. ''' </summary> Public MustOverride ReadOnly Property CustomModifiers As ImmutableArray(Of CustomModifier) ''' <summary> ''' If this variable serves as a backing variable for an automatically generated ''' property or event, returns that property or event. ''' Otherwise returns Nothing. ''' Note, the set of possible associated symbols might be expanded in the future to ''' reflect changes in the languages. ''' </summary> Public MustOverride ReadOnly Property AssociatedSymbol As Symbol ''' <summary> ''' Returns true if this variable was declared as ReadOnly ''' </summary> Public MustOverride ReadOnly Property IsReadOnly As Boolean Implements IFieldSymbol.IsReadOnly ''' <summary> ''' Returns true if this field was declared as "const" (i.e. is a constant declaration), or ''' is an Enum member. ''' </summary> Public MustOverride ReadOnly Property IsConst As Boolean ''' <summary> ''' Gets a value indicating whether this instance is metadata constant. A field is considered to be ''' metadata constant if the field value is a valid default value for a field. ''' </summary> ''' <value> ''' <c>true</c> if this instance is metadata constant; otherwise, <c>false</c>. ''' </value> Friend ReadOnly Property IsMetadataConstant As Boolean Get If Me.IsConst Then Dim specialType = Me.Type.SpecialType Return specialType <> Microsoft.CodeAnalysis.SpecialType.System_DateTime AndAlso specialType <> Microsoft.CodeAnalysis.SpecialType.System_Decimal End If Return False End Get End Property ''' <summary> ''' Gets a value indicating whether this instance is const, but not metadata constant. A field is considered to be ''' const but not metadata constant if the const field's type is either Date or Decimal. ''' </summary> ''' <value> ''' <c>true</c> if this instance is metadata constant; otherwise, <c>false</c>. ''' </value> Friend ReadOnly Property IsConstButNotMetadataConstant As Boolean Get If Me.IsConst Then Dim specialType = Me.Type.SpecialType Return specialType = Microsoft.CodeAnalysis.SpecialType.System_DateTime OrElse specialType = Microsoft.CodeAnalysis.SpecialType.System_Decimal End If Return False End Get End Property ''' <summary> ''' Returns false if the field wasn't declared as "const", or constant value was omitted or erroneous. ''' True otherwise. ''' </summary> Public Overridable ReadOnly Property HasConstantValue As Boolean Get If Not Me.IsConst Then Return False End If Dim value = GetConstantValue(ConstantFieldsInProgress.Empty) Return (value IsNot Nothing) AndAlso Not value.IsBad ' can be null in error scenarios End Get End Property ''' <summary> ''' If IsConst returns true, then returns the value of the constant or Enum member. ''' If IsConst return false, then returns Nothing. ''' </summary> Public Overridable ReadOnly Property ConstantValue As Object Get If Not IsConst Then Return Nothing End If Dim value = GetConstantValue(ConstantFieldsInProgress.Empty) Return If(value IsNot Nothing, value.Value, Nothing) ' can be null in error scenarios End Get End Property ''' <summary> ''' Gets the constant value. ''' </summary> ''' <param name="inProgress">Used to detect dependencies between constant field values.</param> Friend MustOverride Function GetConstantValue(inProgress As ConstantFieldsInProgress) As ConstantValue ''' <summary> ''' Const fields do not (always) have to be declared with a given type. To get the inferred type determined from ''' the initialization this method should be called instead of "Type". For non const field this method returns the ''' declared type. ''' </summary> ''' <param name="inProgress">Used to detect dependencies between constant field values.</param><returns></returns> Friend Overridable Function GetInferredType(inProgress As ConstantFieldsInProgress) As TypeSymbol Return Type End Function Public NotOverridable Overrides ReadOnly Property Kind As SymbolKind Get Return SymbolKind.Field End Get End Property Friend Overrides Function Accept(Of TArgument, TResult)(visitor As VisualBasicSymbolVisitor(Of TArgument, TResult), arg As TArgument) As TResult Return visitor.VisitField(Me, arg) End Function Public NotOverridable Overrides ReadOnly Property IsMustOverride As Boolean Get Return False End Get End Property Public NotOverridable Overrides ReadOnly Property IsNotOverridable As Boolean Get Return False End Get End Property Public NotOverridable Overrides ReadOnly Property IsOverridable As Boolean Get Return False End Get End Property Public NotOverridable Overrides ReadOnly Property IsOverrides As Boolean Get Return False End Get End Property ''' <summary> ''' True if this symbol has a special name (metadata flag SpecialName is set). ''' </summary> Friend MustOverride ReadOnly Property HasSpecialName As Boolean ''' <summary> ''' True if RuntimeSpecialName metadata flag is set for this symbol. ''' </summary> Friend MustOverride ReadOnly Property HasRuntimeSpecialName As Boolean ''' <summary> ''' True if NotSerialized metadata flag is set for this symbol. ''' </summary> Friend MustOverride ReadOnly Property IsNotSerialized As Boolean ''' <summary> ''' Describes how the field is marshalled when passed to native code. ''' Null if no specific marshalling information is available for the field. ''' </summary> ''' <remarks>PE symbols don't provide this information and always return Nothing.</remarks> Friend MustOverride ReadOnly Property MarshallingInformation As MarshalPseudoCustomAttributeData ''' <summary> ''' Returns the marshalling type of this field, or 0 if marshalling information isn't available. ''' </summary> ''' <remarks> ''' By default this information is extracted from <see cref="MarshallingInformation"/> if available. ''' Since the compiler does only need to know the marshalling type of symbols that aren't emitted ''' PE symbols just decode the type from metadata and don't provide full marshalling information. ''' </remarks> Friend Overridable ReadOnly Property MarshallingType As UnmanagedType Get Dim info = MarshallingInformation Return If(info IsNot Nothing, info.UnmanagedType, CType(0, UnmanagedType)) End Get End Property ''' <summary> ''' Offset assigned to the field when the containing type is laid out by the VM. ''' Nothing if unspecified. ''' </summary> Friend MustOverride ReadOnly Property TypeLayoutOffset As Integer? ''' <summary> ''' Get the "this" parameter for this field. This is only valid for source fields. ''' </summary> Friend Overridable ReadOnly Property MeParameter As ParameterSymbol Get Throw ExceptionUtilities.Unreachable End Get End Property ''' <summary> ''' Returns true when field is a backing field for a captured frame pointer (typically "Me"). ''' </summary> Friend Overridable ReadOnly Property IsCapturedFrame As Boolean Get Return False End Get End Property Friend Overrides Function GetUseSiteInfo() As UseSiteInfo(Of AssemblySymbol) If Me.IsDefinition Then Return New UseSiteInfo(Of AssemblySymbol)(PrimaryDependency) End If Return Me.OriginalDefinition.GetUseSiteInfo() End Function Friend Function CalculateUseSiteInfo() As UseSiteInfo(Of AssemblySymbol) Debug.Assert(IsDefinition) ' Check type. Dim useSiteInfo As UseSiteInfo(Of AssemblySymbol) = MergeUseSiteInfo(New UseSiteInfo(Of AssemblySymbol)(PrimaryDependency), DeriveUseSiteInfoFromType(Me.Type)) If useSiteInfo.DiagnosticInfo?.Code = ERRID.ERR_UnsupportedField1 Then Return useSiteInfo End If ' Check custom modifiers. Dim modifiersUseSiteInfo As UseSiteInfo(Of AssemblySymbol) = DeriveUseSiteInfoFromCustomModifiers(Me.CustomModifiers) If modifiersUseSiteInfo.DiagnosticInfo?.Code = ERRID.ERR_UnsupportedField1 Then Return modifiersUseSiteInfo End If useSiteInfo = MergeUseSiteInfo(useSiteInfo, modifiersUseSiteInfo) ' If the member is in an assembly with unified references, ' we check if its definition depends on a type from a unified reference. If useSiteInfo.DiagnosticInfo Is Nothing AndAlso Me.ContainingModule.HasUnifiedReferences Then Dim unificationCheckedTypes As HashSet(Of TypeSymbol) = Nothing Dim errorInfo As DiagnosticInfo = If(Me.Type.GetUnificationUseSiteDiagnosticRecursive(Me, unificationCheckedTypes), GetUnificationUseSiteDiagnosticRecursive(Me.CustomModifiers, Me, unificationCheckedTypes)) If errorInfo IsNot Nothing Then Debug.Assert(errorInfo.Severity = DiagnosticSeverity.Error) useSiteInfo = New UseSiteInfo(Of AssemblySymbol)(errorInfo) End If End If Return useSiteInfo End Function ''' <summary> ''' Return error code that has highest priority while calculating use site error for this symbol. ''' </summary> Protected Overrides ReadOnly Property HighestPriorityUseSiteError As Integer Get Return ERRID.ERR_UnsupportedField1 End Get End Property Public NotOverridable Overrides ReadOnly Property HasUnsupportedMetadata As Boolean Get Dim info As DiagnosticInfo = GetUseSiteInfo().DiagnosticInfo Return info IsNot Nothing AndAlso info.Code = ERRID.ERR_UnsupportedField1 End Get End Property Friend Overrides ReadOnly Property EmbeddedSymbolKind As EmbeddedSymbolKind Get Return Me.ContainingSymbol.EmbeddedSymbolKind End Get End Property ''' <summary> ''' Is this a field of a tuple type? ''' </summary> Public Overridable ReadOnly Property IsTupleField() As Boolean Get Return False End Get End Property ''' <summary> ''' Returns True when field symbol is not mapped directly to a field in the underlying tuple struct. ''' </summary> Public Overridable ReadOnly Property IsVirtualTupleField As Boolean Get Return False End Get End Property ''' <summary> ''' Returns true if this is a field representing a Default element like Item1, Item2... ''' </summary> Public Overridable ReadOnly Property IsDefaultTupleElement As Boolean Get Return False End Get End Property ''' <summary> ''' If this is a field of a tuple type, return corresponding underlying field from the ''' tuple underlying type. Otherwise, Nothing. In case of a malformed underlying type ''' the corresponding underlying field might be missing, return Nothing in this case too. ''' </summary> Public Overridable ReadOnly Property TupleUnderlyingField() As FieldSymbol Get Return Nothing End Get End Property ''' <summary> ''' If this field represents a tuple element, returns a corresponding default element field. ''' Otherwise returns Nothing ''' </summary> Public Overridable ReadOnly Property CorrespondingTupleField As FieldSymbol Get Return Nothing End Get End Property ''' <summary> ''' If this is a field representing a tuple element, ''' returns the index of the element (zero-based). ''' Otherwise returns -1 ''' </summary> Public Overridable ReadOnly Property TupleElementIndex As Integer Get Return -1 End Get End Property Friend Function AsMember(newOwner As NamedTypeSymbol) As FieldSymbol Debug.Assert(Me Is Me.OriginalDefinition) Debug.Assert(newOwner.OriginalDefinition Is Me.ContainingSymbol.OriginalDefinition) Return If(TypeSymbol.Equals(newOwner, Me.ContainingType, TypeCompareKind.ConsiderEverything), Me, DirectCast(DirectCast(newOwner, SubstitutedNamedType).GetMemberForDefinition(Me), FieldSymbol)) End Function #Region "IFieldSymbol" Private ReadOnly Property IFieldSymbol_AssociatedSymbol As ISymbol Implements IFieldSymbol.AssociatedSymbol Get Return Me.AssociatedSymbol End Get End Property Private ReadOnly Property IFieldSymbol_IsConst As Boolean Implements IFieldSymbol.IsConst Get Return Me.IsConst End Get End Property Private ReadOnly Property IFieldSymbol_IsVolatile As Boolean Implements IFieldSymbol.IsVolatile, IFieldSymbolInternal.IsVolatile Get Return False End Get End Property Private ReadOnly Property IFieldSymbol_IsFixedSizeBuffer As Boolean Implements IFieldSymbol.IsFixedSizeBuffer Get Return False End Get End Property Private ReadOnly Property IFieldSymbol_Type As ITypeSymbol Implements IFieldSymbol.Type Get Return Me.Type End Get End Property Private ReadOnly Property IFieldSymbol_NullableAnnotation As NullableAnnotation Implements IFieldSymbol.NullableAnnotation Get Return NullableAnnotation.None End Get End Property Private ReadOnly Property IFieldSymbol_HasConstantValue As Boolean Implements IFieldSymbol.HasConstantValue Get Return Me.HasConstantValue End Get End Property Private ReadOnly Property IFieldSymbol_ConstantValue As Object Implements IFieldSymbol.ConstantValue Get Return Me.ConstantValue End Get End Property Private ReadOnly Property IFieldSymbol_CustomModifiers As ImmutableArray(Of CustomModifier) Implements IFieldSymbol.CustomModifiers Get Return Me.CustomModifiers End Get End Property Private ReadOnly Property IFieldSymbol_OriginalDefinition As IFieldSymbol Implements IFieldSymbol.OriginalDefinition Get Return Me.OriginalDefinition End Get End Property Private ReadOnly Property IFieldSymbol_CorrespondingTupleField As IFieldSymbol Implements IFieldSymbol.CorrespondingTupleField Get Return Me.CorrespondingTupleField End Get End Property Private ReadOnly Property IFieldSymbol_HasExplicitTupleElementName As Boolean Implements IFieldSymbol.IsExplicitlyNamedTupleElement Get Return Not Me.IsImplicitlyDeclared End Get End Property Public Overrides Sub Accept(visitor As SymbolVisitor) visitor.VisitField(Me) End Sub Public Overrides Function Accept(Of TResult)(visitor As SymbolVisitor(Of TResult)) As TResult Return visitor.VisitField(Me) End Function Public Overrides Sub Accept(visitor As VisualBasicSymbolVisitor) visitor.VisitField(Me) End Sub Public Overrides Function Accept(Of TResult)(visitor As VisualBasicSymbolVisitor(Of TResult)) As TResult Return visitor.VisitField(Me) End Function #End Region End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a member variable -- a variable declared as a member of a Class or Structure. ''' </summary> Friend MustInherit Class FieldSymbol Inherits Symbol Implements IFieldSymbol, IFieldSymbolInternal ' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ' Changes to the public interface of this class should remain synchronized with the C# version. ' Do not make any changes to the public interface without making the corresponding change ' to the C# version. ' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Friend Sub New() End Sub ''' <summary> ''' Get the original definition of this symbol. If this symbol is derived from another ''' symbol by (say) type substitution, this gets the original symbol, as it was defined ''' in source or metadata. ''' </summary> Public Overridable Shadows ReadOnly Property OriginalDefinition As FieldSymbol Get ' Default implements returns Me. Return Me End Get End Property Protected NotOverridable Overrides ReadOnly Property OriginalSymbolDefinition As Symbol Get Return Me.OriginalDefinition End Get End Property ''' <summary> ''' Gets the type of this variable. ''' </summary> Public MustOverride ReadOnly Property Type As TypeSymbol ''' <summary> ''' Gets a value indicating whether this instance has declared type. This means a field was declared with an AsClause ''' or in case of const fields with an AsClause whose type is not System.Object ''' </summary> ''' <value> ''' <c>true</c> if this instance has declared type; otherwise, <c>false</c>. ''' </value> Friend Overridable ReadOnly Property HasDeclaredType As Boolean Get Return True End Get End Property ''' <summary> ''' The list of custom modifiers, if any, associated with the member variable. ''' </summary> Public MustOverride ReadOnly Property CustomModifiers As ImmutableArray(Of CustomModifier) ''' <summary> ''' If this variable serves as a backing variable for an automatically generated ''' property or event, returns that property or event. ''' Otherwise returns Nothing. ''' Note, the set of possible associated symbols might be expanded in the future to ''' reflect changes in the languages. ''' </summary> Public MustOverride ReadOnly Property AssociatedSymbol As Symbol ''' <summary> ''' Returns true if this variable was declared as ReadOnly ''' </summary> Public MustOverride ReadOnly Property IsReadOnly As Boolean Implements IFieldSymbol.IsReadOnly ''' <summary> ''' Returns true if this field was declared as "const" (i.e. is a constant declaration), or ''' is an Enum member. ''' </summary> Public MustOverride ReadOnly Property IsConst As Boolean ''' <summary> ''' Gets a value indicating whether this instance is metadata constant. A field is considered to be ''' metadata constant if the field value is a valid default value for a field. ''' </summary> ''' <value> ''' <c>true</c> if this instance is metadata constant; otherwise, <c>false</c>. ''' </value> Friend ReadOnly Property IsMetadataConstant As Boolean Get If Me.IsConst Then Dim specialType = Me.Type.SpecialType Return specialType <> Microsoft.CodeAnalysis.SpecialType.System_DateTime AndAlso specialType <> Microsoft.CodeAnalysis.SpecialType.System_Decimal End If Return False End Get End Property ''' <summary> ''' Gets a value indicating whether this instance is const, but not metadata constant. A field is considered to be ''' const but not metadata constant if the const field's type is either Date or Decimal. ''' </summary> ''' <value> ''' <c>true</c> if this instance is metadata constant; otherwise, <c>false</c>. ''' </value> Friend ReadOnly Property IsConstButNotMetadataConstant As Boolean Get If Me.IsConst Then Dim specialType = Me.Type.SpecialType Return specialType = Microsoft.CodeAnalysis.SpecialType.System_DateTime OrElse specialType = Microsoft.CodeAnalysis.SpecialType.System_Decimal End If Return False End Get End Property ''' <summary> ''' Returns false if the field wasn't declared as "const", or constant value was omitted or erroneous. ''' True otherwise. ''' </summary> Public Overridable ReadOnly Property HasConstantValue As Boolean Get If Not Me.IsConst Then Return False End If Dim value = GetConstantValue(ConstantFieldsInProgress.Empty) Return (value IsNot Nothing) AndAlso Not value.IsBad ' can be null in error scenarios End Get End Property ''' <summary> ''' If IsConst returns true, then returns the value of the constant or Enum member. ''' If IsConst return false, then returns Nothing. ''' </summary> Public Overridable ReadOnly Property ConstantValue As Object Get If Not IsConst Then Return Nothing End If Dim value = GetConstantValue(ConstantFieldsInProgress.Empty) Return If(value IsNot Nothing, value.Value, Nothing) ' can be null in error scenarios End Get End Property ''' <summary> ''' Gets the constant value. ''' </summary> ''' <param name="inProgress">Used to detect dependencies between constant field values.</param> Friend MustOverride Function GetConstantValue(inProgress As ConstantFieldsInProgress) As ConstantValue ''' <summary> ''' Const fields do not (always) have to be declared with a given type. To get the inferred type determined from ''' the initialization this method should be called instead of "Type". For non const field this method returns the ''' declared type. ''' </summary> ''' <param name="inProgress">Used to detect dependencies between constant field values.</param><returns></returns> Friend Overridable Function GetInferredType(inProgress As ConstantFieldsInProgress) As TypeSymbol Return Type End Function Public NotOverridable Overrides ReadOnly Property Kind As SymbolKind Get Return SymbolKind.Field End Get End Property Friend Overrides Function Accept(Of TArgument, TResult)(visitor As VisualBasicSymbolVisitor(Of TArgument, TResult), arg As TArgument) As TResult Return visitor.VisitField(Me, arg) End Function Public NotOverridable Overrides ReadOnly Property IsMustOverride As Boolean Get Return False End Get End Property Public NotOverridable Overrides ReadOnly Property IsNotOverridable As Boolean Get Return False End Get End Property Public NotOverridable Overrides ReadOnly Property IsOverridable As Boolean Get Return False End Get End Property Public NotOverridable Overrides ReadOnly Property IsOverrides As Boolean Get Return False End Get End Property ''' <summary> ''' True if this symbol has a special name (metadata flag SpecialName is set). ''' </summary> Friend MustOverride ReadOnly Property HasSpecialName As Boolean ''' <summary> ''' True if RuntimeSpecialName metadata flag is set for this symbol. ''' </summary> Friend MustOverride ReadOnly Property HasRuntimeSpecialName As Boolean ''' <summary> ''' True if NotSerialized metadata flag is set for this symbol. ''' </summary> Friend MustOverride ReadOnly Property IsNotSerialized As Boolean ''' <summary> ''' Describes how the field is marshalled when passed to native code. ''' Null if no specific marshalling information is available for the field. ''' </summary> ''' <remarks>PE symbols don't provide this information and always return Nothing.</remarks> Friend MustOverride ReadOnly Property MarshallingInformation As MarshalPseudoCustomAttributeData ''' <summary> ''' Returns the marshalling type of this field, or 0 if marshalling information isn't available. ''' </summary> ''' <remarks> ''' By default this information is extracted from <see cref="MarshallingInformation"/> if available. ''' Since the compiler does only need to know the marshalling type of symbols that aren't emitted ''' PE symbols just decode the type from metadata and don't provide full marshalling information. ''' </remarks> Friend Overridable ReadOnly Property MarshallingType As UnmanagedType Get Dim info = MarshallingInformation Return If(info IsNot Nothing, info.UnmanagedType, CType(0, UnmanagedType)) End Get End Property ''' <summary> ''' Offset assigned to the field when the containing type is laid out by the VM. ''' Nothing if unspecified. ''' </summary> Friend MustOverride ReadOnly Property TypeLayoutOffset As Integer? ''' <summary> ''' Get the "this" parameter for this field. This is only valid for source fields. ''' </summary> Friend Overridable ReadOnly Property MeParameter As ParameterSymbol Get Throw ExceptionUtilities.Unreachable End Get End Property ''' <summary> ''' Returns true when field is a backing field for a captured frame pointer (typically "Me"). ''' </summary> Friend Overridable ReadOnly Property IsCapturedFrame As Boolean Get Return False End Get End Property Friend Overrides Function GetUseSiteInfo() As UseSiteInfo(Of AssemblySymbol) If Me.IsDefinition Then Return New UseSiteInfo(Of AssemblySymbol)(PrimaryDependency) End If Return Me.OriginalDefinition.GetUseSiteInfo() End Function Friend Function CalculateUseSiteInfo() As UseSiteInfo(Of AssemblySymbol) Debug.Assert(IsDefinition) ' Check type. Dim useSiteInfo As UseSiteInfo(Of AssemblySymbol) = MergeUseSiteInfo(New UseSiteInfo(Of AssemblySymbol)(PrimaryDependency), DeriveUseSiteInfoFromType(Me.Type)) If useSiteInfo.DiagnosticInfo?.Code = ERRID.ERR_UnsupportedField1 Then Return useSiteInfo End If ' Check custom modifiers. Dim modifiersUseSiteInfo As UseSiteInfo(Of AssemblySymbol) = DeriveUseSiteInfoFromCustomModifiers(Me.CustomModifiers) If modifiersUseSiteInfo.DiagnosticInfo?.Code = ERRID.ERR_UnsupportedField1 Then Return modifiersUseSiteInfo End If useSiteInfo = MergeUseSiteInfo(useSiteInfo, modifiersUseSiteInfo) ' If the member is in an assembly with unified references, ' we check if its definition depends on a type from a unified reference. If useSiteInfo.DiagnosticInfo Is Nothing AndAlso Me.ContainingModule.HasUnifiedReferences Then Dim unificationCheckedTypes As HashSet(Of TypeSymbol) = Nothing Dim errorInfo As DiagnosticInfo = If(Me.Type.GetUnificationUseSiteDiagnosticRecursive(Me, unificationCheckedTypes), GetUnificationUseSiteDiagnosticRecursive(Me.CustomModifiers, Me, unificationCheckedTypes)) If errorInfo IsNot Nothing Then Debug.Assert(errorInfo.Severity = DiagnosticSeverity.Error) useSiteInfo = New UseSiteInfo(Of AssemblySymbol)(errorInfo) End If End If Return useSiteInfo End Function ''' <summary> ''' Return error code that has highest priority while calculating use site error for this symbol. ''' </summary> Protected Overrides ReadOnly Property HighestPriorityUseSiteError As Integer Get Return ERRID.ERR_UnsupportedField1 End Get End Property Public NotOverridable Overrides ReadOnly Property HasUnsupportedMetadata As Boolean Get Dim info As DiagnosticInfo = GetUseSiteInfo().DiagnosticInfo Return info IsNot Nothing AndAlso info.Code = ERRID.ERR_UnsupportedField1 End Get End Property Friend Overrides ReadOnly Property EmbeddedSymbolKind As EmbeddedSymbolKind Get Return Me.ContainingSymbol.EmbeddedSymbolKind End Get End Property ''' <summary> ''' Is this a field of a tuple type? ''' </summary> Public Overridable ReadOnly Property IsTupleField() As Boolean Get Return False End Get End Property ''' <summary> ''' Returns True when field symbol is not mapped directly to a field in the underlying tuple struct. ''' </summary> Public Overridable ReadOnly Property IsVirtualTupleField As Boolean Get Return False End Get End Property ''' <summary> ''' Returns true if this is a field representing a Default element like Item1, Item2... ''' </summary> Public Overridable ReadOnly Property IsDefaultTupleElement As Boolean Get Return False End Get End Property ''' <summary> ''' If this is a field of a tuple type, return corresponding underlying field from the ''' tuple underlying type. Otherwise, Nothing. In case of a malformed underlying type ''' the corresponding underlying field might be missing, return Nothing in this case too. ''' </summary> Public Overridable ReadOnly Property TupleUnderlyingField() As FieldSymbol Get Return Nothing End Get End Property ''' <summary> ''' If this field represents a tuple element, returns a corresponding default element field. ''' Otherwise returns Nothing ''' </summary> Public Overridable ReadOnly Property CorrespondingTupleField As FieldSymbol Get Return Nothing End Get End Property ''' <summary> ''' If this is a field representing a tuple element, ''' returns the index of the element (zero-based). ''' Otherwise returns -1 ''' </summary> Public Overridable ReadOnly Property TupleElementIndex As Integer Get Return -1 End Get End Property Friend Function AsMember(newOwner As NamedTypeSymbol) As FieldSymbol Debug.Assert(Me Is Me.OriginalDefinition) Debug.Assert(newOwner.OriginalDefinition Is Me.ContainingSymbol.OriginalDefinition) Return If(TypeSymbol.Equals(newOwner, Me.ContainingType, TypeCompareKind.ConsiderEverything), Me, DirectCast(DirectCast(newOwner, SubstitutedNamedType).GetMemberForDefinition(Me), FieldSymbol)) End Function #Region "IFieldSymbol" Private ReadOnly Property IFieldSymbol_AssociatedSymbol As ISymbol Implements IFieldSymbol.AssociatedSymbol Get Return Me.AssociatedSymbol End Get End Property Private ReadOnly Property IFieldSymbol_IsConst As Boolean Implements IFieldSymbol.IsConst Get Return Me.IsConst End Get End Property Private ReadOnly Property IFieldSymbol_IsVolatile As Boolean Implements IFieldSymbol.IsVolatile, IFieldSymbolInternal.IsVolatile Get Return False End Get End Property Private ReadOnly Property IFieldSymbol_IsFixedSizeBuffer As Boolean Implements IFieldSymbol.IsFixedSizeBuffer Get Return False End Get End Property Private ReadOnly Property IFieldSymbol_FixedSize As Integer Implements IFieldSymbol.FixedSize Get Return 0 End Get End Property Private ReadOnly Property IFieldSymbol_Type As ITypeSymbol Implements IFieldSymbol.Type Get Return Me.Type End Get End Property Private ReadOnly Property IFieldSymbol_NullableAnnotation As NullableAnnotation Implements IFieldSymbol.NullableAnnotation Get Return NullableAnnotation.None End Get End Property Private ReadOnly Property IFieldSymbol_HasConstantValue As Boolean Implements IFieldSymbol.HasConstantValue Get Return Me.HasConstantValue End Get End Property Private ReadOnly Property IFieldSymbol_ConstantValue As Object Implements IFieldSymbol.ConstantValue Get Return Me.ConstantValue End Get End Property Private ReadOnly Property IFieldSymbol_CustomModifiers As ImmutableArray(Of CustomModifier) Implements IFieldSymbol.CustomModifiers Get Return Me.CustomModifiers End Get End Property Private ReadOnly Property IFieldSymbol_OriginalDefinition As IFieldSymbol Implements IFieldSymbol.OriginalDefinition Get Return Me.OriginalDefinition End Get End Property Private ReadOnly Property IFieldSymbol_CorrespondingTupleField As IFieldSymbol Implements IFieldSymbol.CorrespondingTupleField Get Return Me.CorrespondingTupleField End Get End Property Private ReadOnly Property IFieldSymbol_HasExplicitTupleElementName As Boolean Implements IFieldSymbol.IsExplicitlyNamedTupleElement Get Return Not Me.IsImplicitlyDeclared End Get End Property Public Overrides Sub Accept(visitor As SymbolVisitor) visitor.VisitField(Me) End Sub Public Overrides Function Accept(Of TResult)(visitor As SymbolVisitor(Of TResult)) As TResult Return visitor.VisitField(Me) End Function Public Overrides Sub Accept(visitor As VisualBasicSymbolVisitor) visitor.VisitField(Me) End Sub Public Overrides Function Accept(Of TResult)(visitor As VisualBasicSymbolVisitor(Of TResult)) As TResult Return visitor.VisitField(Me) End Function #End Region End Class End Namespace
1
dotnet/roslyn
55,354
Add IFieldSymbol.FixedSize API
Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
333fred
2021-08-02T22:15:12Z
2021-08-03T21:43:37Z
76bdda7fe502a74f91aee0feb2fe251039be4e82
a81b07d0d5a6b5c5430443fc843e4a730399c946
Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/FieldTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Globalization Imports System.Text Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class FieldTests Inherits BasicTestBase <Fact> Public Sub SimpleFields() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="AAA"> <file name="a.vb"> Public Structure C Shared ch1, ch2 as Char End Structure </file> </compilation>) Dim globalNS = compilation.SourceModule.GlobalNamespace Dim structC = DirectCast(globalNS.GetMembers().Single(), NamedTypeSymbol) Dim field1 = DirectCast(structC.GetMembers()(1), FieldSymbol) Dim field2 = DirectCast(structC.GetMembers()(2), FieldSymbol) Assert.Same(structC, field1.ContainingSymbol) Assert.Same(structC, field2.ContainingType) Assert.Equal("ch1", field1.Name) Assert.Equal("C.ch2 As System.Char", field2.ToTestDisplayString()) Assert.False(field1.IsMustOverride) Assert.False(field1.IsNotOverridable) Assert.False(field2.IsOverrides) Assert.False(field2.IsOverridable) Assert.Equal(0, field2.CustomModifiers.Length) CompilationUtils.AssertNoDeclarationDiagnostics(compilation) End Sub <Fact> <CompilerTrait(CompilerFeature.Tuples)> Public Sub TupleAPIs() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="AAA"> <file name="a.vb"> Public Class C Shared ch1 as C End Class </file> </compilation>) Dim globalNS = compilation.SourceModule.GlobalNamespace Dim structC = DirectCast(globalNS.GetMembers().Single(), NamedTypeSymbol) Dim field = DirectCast(structC.GetMembers()(1), FieldSymbol) Dim fieldType = DirectCast(field.Type, INamedTypeSymbol) Assert.False(fieldType.IsTupleType) Assert.True(fieldType.TupleElements.IsDefault) End Sub <Fact> Public Sub Fields1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C"> <file name="a.vb"> Public Partial Class C Public Shared p?, q as Char, t% Protected Friend u@() Friend Shared v(,)() as Object End Class </file> <file name="b.vb"> Public Partial Class C Protected s As Long ReadOnly r Private Class D Shared Friend l As UInteger = 5 End Class End Class </file> </compilation>) Dim globalNS = compilation.SourceModule.GlobalNamespace Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol) Dim globalNSmembers = globalNS.GetMembers() Assert.Equal(1, globalNSmembers.Length) Dim classC = DirectCast(globalNSmembers(0), NamedTypeSymbol) Dim membersOfC = classC.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ToArray() Assert.Equal(9, membersOfC.Length) Dim classD = DirectCast(membersOfC(1), NamedTypeSymbol) Assert.Equal("D", classD.Name) Assert.Equal(TypeKind.Class, classD.TypeKind) Dim fieldP = DirectCast(membersOfC(2), FieldSymbol) Assert.Same(classC, fieldP.ContainingSymbol) Assert.Same(classC, fieldP.ContainingType) Assert.Equal("p", fieldP.Name) Assert.Equal(Accessibility.Public, fieldP.DeclaredAccessibility) Assert.True(fieldP.IsShared) Assert.False(fieldP.IsReadOnly) Assert.Same(sourceMod.GetCorLibType(SpecialType.System_Nullable_T), fieldP.Type.OriginalDefinition) Assert.Same(sourceMod.GetCorLibType(SpecialType.System_Char), DirectCast(fieldP.Type, NamedTypeSymbol).TypeArguments(0)) Dim fieldQ = DirectCast(membersOfC(3), FieldSymbol) Assert.Equal("q", fieldQ.Name) Assert.Equal(Accessibility.Public, fieldQ.DeclaredAccessibility) Assert.True(fieldQ.IsShared) Assert.False(fieldQ.IsReadOnly) Assert.Same(sourceMod.GetCorLibType(SpecialType.System_Char), fieldQ.Type) Dim fieldR = DirectCast(membersOfC(4), FieldSymbol) Assert.Equal("r", fieldR.Name) Assert.Equal(Accessibility.Private, fieldR.DeclaredAccessibility) Assert.False(fieldR.IsShared) Assert.True(fieldR.IsReadOnly) Assert.Same(sourceMod.GetCorLibType(SpecialType.System_Object), fieldR.Type) Dim fieldS = DirectCast(membersOfC(5), FieldSymbol) Assert.Equal("s", fieldS.Name) Assert.Equal(Accessibility.Protected, fieldS.DeclaredAccessibility) Assert.False(fieldS.IsShared) Assert.False(fieldS.IsReadOnly) Assert.Same(sourceMod.GetCorLibType(SpecialType.System_Int64), fieldS.Type) Dim fieldT = DirectCast(membersOfC(6), FieldSymbol) Assert.Equal("t", fieldT.Name) Assert.Equal(Accessibility.Public, fieldT.DeclaredAccessibility) Assert.True(fieldT.IsShared) Assert.False(fieldT.IsReadOnly) Assert.Same(sourceMod.GetCorLibType(SpecialType.System_Int32), fieldT.Type) Dim fieldU = DirectCast(membersOfC(7), FieldSymbol) Assert.Equal("u", fieldU.Name) Assert.Equal(Accessibility.ProtectedOrFriend, fieldU.DeclaredAccessibility) Assert.False(fieldU.IsShared) Assert.False(fieldU.IsReadOnly) Assert.Equal(TypeKind.Array, fieldU.Type.TypeKind) Assert.Same(sourceMod.GetCorLibType(SpecialType.System_Decimal), DirectCast(fieldU.Type, ArrayTypeSymbol).ElementType) Assert.Equal(1, DirectCast(fieldU.Type, ArrayTypeSymbol).Rank) Dim fieldV = DirectCast(membersOfC(8), FieldSymbol) Assert.Equal("v", fieldV.Name) Assert.Equal(Accessibility.Friend, fieldV.DeclaredAccessibility) Assert.True(fieldV.IsShared) Assert.False(fieldV.IsReadOnly) Assert.Equal(TypeKind.Array, fieldV.Type.TypeKind) ' v is a 2d array of a 1d array. Assert.Equal(2, DirectCast(fieldV.Type, ArrayTypeSymbol).Rank) Assert.Equal(1, DirectCast(DirectCast(fieldV.Type, ArrayTypeSymbol).ElementType, ArrayTypeSymbol).Rank) Dim membersOfD = classD.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ToArray() Assert.Equal(3, membersOfD.Length) Dim fieldL = DirectCast(membersOfD(2), FieldSymbol) Assert.Same(classD, fieldL.ContainingSymbol) Assert.Same(classD, fieldL.ContainingType) Assert.Equal("l", fieldL.Name) Assert.Equal(Accessibility.Friend, fieldL.DeclaredAccessibility) Assert.True(fieldL.IsShared) Assert.False(fieldL.IsReadOnly) Assert.Same(sourceMod.GetCorLibType(SpecialType.System_UInt32), fieldL.Type) CompilationUtils.AssertNoDeclarationDiagnostics(compilation) End Sub <WorkItem(537491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537491")> <Fact> Public Sub ImplicitTypedFields01() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Field"> <file name="a.vb"> 'Imports statements should go here Imports System Namespace ConstInit02 Class C Const C1 = 2, C2 = 4, C3 = -1 Public Const ImplChar = "c"c Private Const ImplString = "Microsoft" Protected Const ImplShort As Short = 32767S Friend Const ImplInteger = 123% Const ImplLong = 12345678910&amp; Friend Protected Const ImplDouble = 1234.1234# Public Const ImplSingle = 1234.1234! Public Const ImplDecimal = 1234.456@ End Class End namespace </file> </compilation>) CompilationUtils.AssertNoDeclarationDiagnostics(compilation) Dim globalNS = compilation.SourceModule.GlobalNamespace Dim ns = DirectCast(globalNS.GetMembers("ConstInit02").Single(), NamespaceSymbol) Dim type1 = DirectCast(ns.GetTypeMembers("C").Single(), NamedTypeSymbol) ' 11 field + ctor (cctor for decimal is not part of members list) Dim m = type1.GetMembers() Assert.Equal(12, type1.GetMembers().Length) Dim fieldC = DirectCast(type1.GetMembers("C2").Single(), FieldSymbol) Assert.Same(type1, fieldC.ContainingSymbol) Assert.Same(type1, fieldC.ContainingType) Assert.Equal("C2", fieldC.Name) Assert.Equal(Accessibility.Private, fieldC.DeclaredAccessibility) Assert.Equal("Int32", fieldC.Type.Name) Dim field1 = DirectCast(type1.GetMembers("ImplChar").Single(), FieldSymbol) Assert.Equal("char", field1.Type.Name.ToLowerInvariant()) Dim field2 = DirectCast(type1.GetMembers("ImplString").Single(), FieldSymbol) Assert.Equal("string", field2.Type.Name.ToLowerInvariant()) Dim field3 = DirectCast(type1.GetMembers("ImplShort").Single(), FieldSymbol) Assert.Equal("int16", field3.Type.Name.ToLowerInvariant()) Dim field4 = DirectCast(type1.GetMembers("ImplInteger").Single(), FieldSymbol) Assert.Equal("int32", field4.Type.Name.ToLowerInvariant()) Dim field5 = DirectCast(type1.GetMembers("ImplLong").Single(), FieldSymbol) Assert.Equal("int64", field5.Type.Name.ToLowerInvariant()) Dim field6 = DirectCast(type1.GetMembers("ImplDouble").Single(), FieldSymbol) Assert.Equal("double", field6.Type.Name.ToLowerInvariant()) Dim field7 = DirectCast(type1.GetMembers("ImplSingle").Single(), FieldSymbol) Assert.Equal("single", field7.Type.Name.ToLowerInvariant()) Dim field8 = DirectCast(type1.GetMembers("ImplDecimal").Single(), FieldSymbol) Assert.Equal("decimal", field8.Type.Name.ToLowerInvariant()) End Sub <Fact> Public Sub Bug4993() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="AAA"> <file name="a.vb"> Option Infer Off Option Strict On Public Class Class1 Private Const LOCAL_SIZE = 1 Sub Test() Const thisIsAConst = 1 Dim y As Object = thisIsAConst End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30209: Option Strict On requires all variable declarations to have an 'As' clause. Private Const LOCAL_SIZE = 1 ~~~~~~~~~~ BC30209: Option Strict On requires all variable declarations to have an 'As' clause. Const thisIsAConst = 1 ~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub Bug4993_related_StrictOn() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="AAA"> <file name="a.vb"> Option Strict On Public Class Class1 Private Const LOCAL_SIZE = 1 Private Const LOCAL_SIZE_2 as object = 1 Sub Test() End Sub End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact> Public Sub Bug4993_related_StrictOff() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="AAA"> <file name="a.vb"> Option Strict Off Public Class Class1 Private Const LOCAL_SIZE = 1 Private Const LOCAL_SIZE_2 as object = 1 Sub Test() End Sub End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact> Public Sub ConstFieldWithoutValueErr() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ConstFieldWithoutValueErr"> <file name="a.vb"> Public Class C Const x As Integer End Class </file> </compilation>) Dim type1 = DirectCast(compilation.SourceModule.GlobalNamespace.GetMembers("C").Single(), NamedTypeSymbol) Dim mem = DirectCast(type1.GetMembers("x").Single(), FieldSymbol) Assert.Equal("x", mem.Name) Assert.True(mem.IsConst) Assert.False(mem.HasConstantValue) Assert.Equal(Nothing, mem.ConstantValue) End Sub <Fact> Public Sub Bug9902_NoValuesForConstField() Dim expectedErrors() As XElement = { <errors> BC30438: Constants must have a value. Private Const Field1 As Integer ~~~~~~ BC30438: Constants must have a value. Private Const Field2 ~~~~~~ </errors>, <errors> BC30438: Constants must have a value. Private Const Field1 As Integer ~~~~~~ BC30209: Option Strict On requires all variable declarations to have an 'As' clause. Private Const Field2 ~~~~~~ BC30438: Constants must have a value. Private Const Field2 ~~~~~~ </errors>, <errors> BC30438: Constants must have a value. Private Const Field1 As Integer ~~~~~~ BC30438: Constants must have a value. Private Const Field2 ~~~~~~ </errors>, <errors> BC30438: Constants must have a value. Private Const Field1 As Integer ~~~~~~ BC30438: Constants must have a value. Private Const Field2 ~~~~~~ </errors> } Dim index = 0 For Each optionStrict In {"On", "Off"} For Each infer In {"On", "Off"} Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="AAA"> <file name="a.vb"> Option Strict <%= optionStrict %> Option Infer <%= infer %> Public Class Class1 Private Const Field1 As Integer Private Const Field2 Public Sub Main() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors(index) ) index += 1 Next Next End Sub <Fact> Public Sub Bug9902_ValuesForConstField() Dim expectedErrors() As XElement = { <errors> </errors>, <errors> BC30209: Option Strict On requires all variable declarations to have an 'As' clause. Private Const Field2 = 42 ~~~~~~ </errors>, <errors> </errors>, <errors> </errors> } Dim index = 0 For Each optionStrict In {"On", "Off"} For Each infer In {"On", "Off"} Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="AAA"> <file name="a.vb"> Option Strict <%= optionStrict %> Option Infer <%= infer %> Public Class Class1 Private Const Field1 As Object = 23 Private Const Field2 = 42 Public Sub Main() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors(index) ) index += 1 Next Next End Sub <WorkItem(543689, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543689")> <Fact()> Public Sub TestReadonlyFieldAccessWithoutQualifyingInstance() Dim vbCompilation = CreateVisualBasicCompilation("TestReadonlyFieldAccessWithoutQualifyingInstance", <![CDATA[ Class Outer Public ReadOnly field As Integer Class Inner Sub New(ByVal value As Integer) value = field End Sub End Class End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) vbCompilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_ObjectReferenceNotSupplied, "field")) End Sub ''' <summary> ''' Fields named "value__" should be marked rtspecialname. ''' </summary> <WorkItem(546185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546185")> <WorkItem(6190, "https://github.com/dotnet/roslyn/issues/6190")> <ConditionalFact(GetType(DesktopOnly))> Public Sub RTSpecialName() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class A Private value__ As Object = Nothing End Class Class B Private VALUE__ As Object = Nothing End Class Class C Sub value__() End Sub End Class Class D Property value__ As Object End Class Class E Event value__ As System.Action End Class Class F Interface value__ End Interface End Class Class G Class value__ End Class End Class Module M Function F() As System.Action(Of Object) Dim value__ As Object = Nothing Return Function(v) value__ = v End Function End Module ]]></file> </compilation>) compilation.AssertNoErrors() ' PEVerify should not report "Field value__ ... is not marked RTSpecialName". Dim verifier = New CompilationVerifier(compilation) verifier.EmitAndVerify( "Error: Field name value__ is reserved for Enums only.") End Sub <Fact> Public Sub MultipleFieldsWithBadType() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="AAA"> <file name="a.vb"> Public Class C Public x, y, z as abcDef End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30002: Type 'abcDef' is not defined. Public x, y, z as abcDef ~~~~~~ </expected>) End Sub <Fact> Public Sub AssociatedSymbolOfSubstitutedField() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="AAA"> <file name="a.vb"> Public Class C(Of T) Public Property P As Integer End Class </file> </compilation>) Dim type = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim [property] = type.GetMember(Of PropertySymbol)("P") Dim field = [property].AssociatedField Assert.Equal([property], field.AssociatedSymbol) Dim substitutedType = type.Construct(compilation.GetSpecialType(SpecialType.System_Int32)) Dim substitutedProperty = substitutedType.GetMember(Of PropertySymbol)("P") Dim substitutedField = substitutedProperty.AssociatedField Assert.IsType(Of SubstitutedFieldSymbol)(substitutedField) Assert.Equal(substitutedProperty, substitutedField.AssociatedSymbol) End Sub <WorkItem(26364, "https://github.com/dotnet/roslyn/issues/26364")> <Fact> Public Sub FixedSizeBufferFalse() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="AAA"> <file name="a.vb"> Public Structure S Private goo as Byte End Structure </file> </compilation>) Dim globalNS = compilation.SourceModule.GlobalNamespace Dim s = globalNS.GetMember(Of NamedTypeSymbol)("S") Dim goo = DirectCast(s.GetMember(Of FieldSymbol)("goo"), IFieldSymbol) Assert.False(goo.IsFixedSizeBuffer) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Globalization Imports System.Text Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class FieldTests Inherits BasicTestBase <Fact> Public Sub SimpleFields() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="AAA"> <file name="a.vb"> Public Structure C Shared ch1, ch2 as Char End Structure </file> </compilation>) Dim globalNS = compilation.SourceModule.GlobalNamespace Dim structC = DirectCast(globalNS.GetMembers().Single(), NamedTypeSymbol) Dim field1 = DirectCast(structC.GetMembers()(1), FieldSymbol) Dim field2 = DirectCast(structC.GetMembers()(2), FieldSymbol) Assert.Same(structC, field1.ContainingSymbol) Assert.Same(structC, field2.ContainingType) Assert.Equal("ch1", field1.Name) Assert.Equal("C.ch2 As System.Char", field2.ToTestDisplayString()) Assert.False(field1.IsMustOverride) Assert.False(field1.IsNotOverridable) Assert.False(field2.IsOverrides) Assert.False(field2.IsOverridable) Assert.Equal(0, field2.CustomModifiers.Length) CompilationUtils.AssertNoDeclarationDiagnostics(compilation) End Sub <Fact> <CompilerTrait(CompilerFeature.Tuples)> Public Sub TupleAPIs() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="AAA"> <file name="a.vb"> Public Class C Shared ch1 as C End Class </file> </compilation>) Dim globalNS = compilation.SourceModule.GlobalNamespace Dim structC = DirectCast(globalNS.GetMembers().Single(), NamedTypeSymbol) Dim field = DirectCast(structC.GetMembers()(1), FieldSymbol) Dim fieldType = DirectCast(field.Type, INamedTypeSymbol) Assert.False(fieldType.IsTupleType) Assert.True(fieldType.TupleElements.IsDefault) End Sub <Fact> Public Sub Fields1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C"> <file name="a.vb"> Public Partial Class C Public Shared p?, q as Char, t% Protected Friend u@() Friend Shared v(,)() as Object End Class </file> <file name="b.vb"> Public Partial Class C Protected s As Long ReadOnly r Private Class D Shared Friend l As UInteger = 5 End Class End Class </file> </compilation>) Dim globalNS = compilation.SourceModule.GlobalNamespace Dim sourceMod = DirectCast(compilation.SourceModule, SourceModuleSymbol) Dim globalNSmembers = globalNS.GetMembers() Assert.Equal(1, globalNSmembers.Length) Dim classC = DirectCast(globalNSmembers(0), NamedTypeSymbol) Dim membersOfC = classC.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ToArray() Assert.Equal(9, membersOfC.Length) Dim classD = DirectCast(membersOfC(1), NamedTypeSymbol) Assert.Equal("D", classD.Name) Assert.Equal(TypeKind.Class, classD.TypeKind) Dim fieldP = DirectCast(membersOfC(2), FieldSymbol) Assert.Same(classC, fieldP.ContainingSymbol) Assert.Same(classC, fieldP.ContainingType) Assert.Equal("p", fieldP.Name) Assert.Equal(Accessibility.Public, fieldP.DeclaredAccessibility) Assert.True(fieldP.IsShared) Assert.False(fieldP.IsReadOnly) Assert.Same(sourceMod.GetCorLibType(SpecialType.System_Nullable_T), fieldP.Type.OriginalDefinition) Assert.Same(sourceMod.GetCorLibType(SpecialType.System_Char), DirectCast(fieldP.Type, NamedTypeSymbol).TypeArguments(0)) Dim fieldQ = DirectCast(membersOfC(3), FieldSymbol) Assert.Equal("q", fieldQ.Name) Assert.Equal(Accessibility.Public, fieldQ.DeclaredAccessibility) Assert.True(fieldQ.IsShared) Assert.False(fieldQ.IsReadOnly) Assert.Same(sourceMod.GetCorLibType(SpecialType.System_Char), fieldQ.Type) Dim fieldR = DirectCast(membersOfC(4), FieldSymbol) Assert.Equal("r", fieldR.Name) Assert.Equal(Accessibility.Private, fieldR.DeclaredAccessibility) Assert.False(fieldR.IsShared) Assert.True(fieldR.IsReadOnly) Assert.Same(sourceMod.GetCorLibType(SpecialType.System_Object), fieldR.Type) Dim fieldS = DirectCast(membersOfC(5), FieldSymbol) Assert.Equal("s", fieldS.Name) Assert.Equal(Accessibility.Protected, fieldS.DeclaredAccessibility) Assert.False(fieldS.IsShared) Assert.False(fieldS.IsReadOnly) Assert.Same(sourceMod.GetCorLibType(SpecialType.System_Int64), fieldS.Type) Dim fieldT = DirectCast(membersOfC(6), FieldSymbol) Assert.Equal("t", fieldT.Name) Assert.Equal(Accessibility.Public, fieldT.DeclaredAccessibility) Assert.True(fieldT.IsShared) Assert.False(fieldT.IsReadOnly) Assert.Same(sourceMod.GetCorLibType(SpecialType.System_Int32), fieldT.Type) Dim fieldU = DirectCast(membersOfC(7), FieldSymbol) Assert.Equal("u", fieldU.Name) Assert.Equal(Accessibility.ProtectedOrFriend, fieldU.DeclaredAccessibility) Assert.False(fieldU.IsShared) Assert.False(fieldU.IsReadOnly) Assert.Equal(TypeKind.Array, fieldU.Type.TypeKind) Assert.Same(sourceMod.GetCorLibType(SpecialType.System_Decimal), DirectCast(fieldU.Type, ArrayTypeSymbol).ElementType) Assert.Equal(1, DirectCast(fieldU.Type, ArrayTypeSymbol).Rank) Dim fieldV = DirectCast(membersOfC(8), FieldSymbol) Assert.Equal("v", fieldV.Name) Assert.Equal(Accessibility.Friend, fieldV.DeclaredAccessibility) Assert.True(fieldV.IsShared) Assert.False(fieldV.IsReadOnly) Assert.Equal(TypeKind.Array, fieldV.Type.TypeKind) ' v is a 2d array of a 1d array. Assert.Equal(2, DirectCast(fieldV.Type, ArrayTypeSymbol).Rank) Assert.Equal(1, DirectCast(DirectCast(fieldV.Type, ArrayTypeSymbol).ElementType, ArrayTypeSymbol).Rank) Dim membersOfD = classD.GetMembers().AsEnumerable().OrderBy(Function(s) s.Name).ToArray() Assert.Equal(3, membersOfD.Length) Dim fieldL = DirectCast(membersOfD(2), FieldSymbol) Assert.Same(classD, fieldL.ContainingSymbol) Assert.Same(classD, fieldL.ContainingType) Assert.Equal("l", fieldL.Name) Assert.Equal(Accessibility.Friend, fieldL.DeclaredAccessibility) Assert.True(fieldL.IsShared) Assert.False(fieldL.IsReadOnly) Assert.Same(sourceMod.GetCorLibType(SpecialType.System_UInt32), fieldL.Type) CompilationUtils.AssertNoDeclarationDiagnostics(compilation) End Sub <WorkItem(537491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537491")> <Fact> Public Sub ImplicitTypedFields01() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Field"> <file name="a.vb"> 'Imports statements should go here Imports System Namespace ConstInit02 Class C Const C1 = 2, C2 = 4, C3 = -1 Public Const ImplChar = "c"c Private Const ImplString = "Microsoft" Protected Const ImplShort As Short = 32767S Friend Const ImplInteger = 123% Const ImplLong = 12345678910&amp; Friend Protected Const ImplDouble = 1234.1234# Public Const ImplSingle = 1234.1234! Public Const ImplDecimal = 1234.456@ End Class End namespace </file> </compilation>) CompilationUtils.AssertNoDeclarationDiagnostics(compilation) Dim globalNS = compilation.SourceModule.GlobalNamespace Dim ns = DirectCast(globalNS.GetMembers("ConstInit02").Single(), NamespaceSymbol) Dim type1 = DirectCast(ns.GetTypeMembers("C").Single(), NamedTypeSymbol) ' 11 field + ctor (cctor for decimal is not part of members list) Dim m = type1.GetMembers() Assert.Equal(12, type1.GetMembers().Length) Dim fieldC = DirectCast(type1.GetMembers("C2").Single(), FieldSymbol) Assert.Same(type1, fieldC.ContainingSymbol) Assert.Same(type1, fieldC.ContainingType) Assert.Equal("C2", fieldC.Name) Assert.Equal(Accessibility.Private, fieldC.DeclaredAccessibility) Assert.Equal("Int32", fieldC.Type.Name) Dim field1 = DirectCast(type1.GetMembers("ImplChar").Single(), FieldSymbol) Assert.Equal("char", field1.Type.Name.ToLowerInvariant()) Dim field2 = DirectCast(type1.GetMembers("ImplString").Single(), FieldSymbol) Assert.Equal("string", field2.Type.Name.ToLowerInvariant()) Dim field3 = DirectCast(type1.GetMembers("ImplShort").Single(), FieldSymbol) Assert.Equal("int16", field3.Type.Name.ToLowerInvariant()) Dim field4 = DirectCast(type1.GetMembers("ImplInteger").Single(), FieldSymbol) Assert.Equal("int32", field4.Type.Name.ToLowerInvariant()) Dim field5 = DirectCast(type1.GetMembers("ImplLong").Single(), FieldSymbol) Assert.Equal("int64", field5.Type.Name.ToLowerInvariant()) Dim field6 = DirectCast(type1.GetMembers("ImplDouble").Single(), FieldSymbol) Assert.Equal("double", field6.Type.Name.ToLowerInvariant()) Dim field7 = DirectCast(type1.GetMembers("ImplSingle").Single(), FieldSymbol) Assert.Equal("single", field7.Type.Name.ToLowerInvariant()) Dim field8 = DirectCast(type1.GetMembers("ImplDecimal").Single(), FieldSymbol) Assert.Equal("decimal", field8.Type.Name.ToLowerInvariant()) End Sub <Fact> Public Sub Bug4993() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="AAA"> <file name="a.vb"> Option Infer Off Option Strict On Public Class Class1 Private Const LOCAL_SIZE = 1 Sub Test() Const thisIsAConst = 1 Dim y As Object = thisIsAConst End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30209: Option Strict On requires all variable declarations to have an 'As' clause. Private Const LOCAL_SIZE = 1 ~~~~~~~~~~ BC30209: Option Strict On requires all variable declarations to have an 'As' clause. Const thisIsAConst = 1 ~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub Bug4993_related_StrictOn() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="AAA"> <file name="a.vb"> Option Strict On Public Class Class1 Private Const LOCAL_SIZE = 1 Private Const LOCAL_SIZE_2 as object = 1 Sub Test() End Sub End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact> Public Sub Bug4993_related_StrictOff() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="AAA"> <file name="a.vb"> Option Strict Off Public Class Class1 Private Const LOCAL_SIZE = 1 Private Const LOCAL_SIZE_2 as object = 1 Sub Test() End Sub End Class </file> </compilation>) CompilationUtils.AssertNoErrors(compilation) End Sub <Fact> Public Sub ConstFieldWithoutValueErr() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="ConstFieldWithoutValueErr"> <file name="a.vb"> Public Class C Const x As Integer End Class </file> </compilation>) Dim type1 = DirectCast(compilation.SourceModule.GlobalNamespace.GetMembers("C").Single(), NamedTypeSymbol) Dim mem = DirectCast(type1.GetMembers("x").Single(), FieldSymbol) Assert.Equal("x", mem.Name) Assert.True(mem.IsConst) Assert.False(mem.HasConstantValue) Assert.Equal(Nothing, mem.ConstantValue) End Sub <Fact> Public Sub Bug9902_NoValuesForConstField() Dim expectedErrors() As XElement = { <errors> BC30438: Constants must have a value. Private Const Field1 As Integer ~~~~~~ BC30438: Constants must have a value. Private Const Field2 ~~~~~~ </errors>, <errors> BC30438: Constants must have a value. Private Const Field1 As Integer ~~~~~~ BC30209: Option Strict On requires all variable declarations to have an 'As' clause. Private Const Field2 ~~~~~~ BC30438: Constants must have a value. Private Const Field2 ~~~~~~ </errors>, <errors> BC30438: Constants must have a value. Private Const Field1 As Integer ~~~~~~ BC30438: Constants must have a value. Private Const Field2 ~~~~~~ </errors>, <errors> BC30438: Constants must have a value. Private Const Field1 As Integer ~~~~~~ BC30438: Constants must have a value. Private Const Field2 ~~~~~~ </errors> } Dim index = 0 For Each optionStrict In {"On", "Off"} For Each infer In {"On", "Off"} Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="AAA"> <file name="a.vb"> Option Strict <%= optionStrict %> Option Infer <%= infer %> Public Class Class1 Private Const Field1 As Integer Private Const Field2 Public Sub Main() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors(index) ) index += 1 Next Next End Sub <Fact> Public Sub Bug9902_ValuesForConstField() Dim expectedErrors() As XElement = { <errors> </errors>, <errors> BC30209: Option Strict On requires all variable declarations to have an 'As' clause. Private Const Field2 = 42 ~~~~~~ </errors>, <errors> </errors>, <errors> </errors> } Dim index = 0 For Each optionStrict In {"On", "Off"} For Each infer In {"On", "Off"} Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="AAA"> <file name="a.vb"> Option Strict <%= optionStrict %> Option Infer <%= infer %> Public Class Class1 Private Const Field1 As Object = 23 Private Const Field2 = 42 Public Sub Main() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors(index) ) index += 1 Next Next End Sub <WorkItem(543689, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543689")> <Fact()> Public Sub TestReadonlyFieldAccessWithoutQualifyingInstance() Dim vbCompilation = CreateVisualBasicCompilation("TestReadonlyFieldAccessWithoutQualifyingInstance", <![CDATA[ Class Outer Public ReadOnly field As Integer Class Inner Sub New(ByVal value As Integer) value = field End Sub End Class End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) vbCompilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_ObjectReferenceNotSupplied, "field")) End Sub ''' <summary> ''' Fields named "value__" should be marked rtspecialname. ''' </summary> <WorkItem(546185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546185")> <WorkItem(6190, "https://github.com/dotnet/roslyn/issues/6190")> <ConditionalFact(GetType(DesktopOnly))> Public Sub RTSpecialName() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class A Private value__ As Object = Nothing End Class Class B Private VALUE__ As Object = Nothing End Class Class C Sub value__() End Sub End Class Class D Property value__ As Object End Class Class E Event value__ As System.Action End Class Class F Interface value__ End Interface End Class Class G Class value__ End Class End Class Module M Function F() As System.Action(Of Object) Dim value__ As Object = Nothing Return Function(v) value__ = v End Function End Module ]]></file> </compilation>) compilation.AssertNoErrors() ' PEVerify should not report "Field value__ ... is not marked RTSpecialName". Dim verifier = New CompilationVerifier(compilation) verifier.EmitAndVerify( "Error: Field name value__ is reserved for Enums only.") End Sub <Fact> Public Sub MultipleFieldsWithBadType() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="AAA"> <file name="a.vb"> Public Class C Public x, y, z as abcDef End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30002: Type 'abcDef' is not defined. Public x, y, z as abcDef ~~~~~~ </expected>) End Sub <Fact> Public Sub AssociatedSymbolOfSubstitutedField() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="AAA"> <file name="a.vb"> Public Class C(Of T) Public Property P As Integer End Class </file> </compilation>) Dim type = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim [property] = type.GetMember(Of PropertySymbol)("P") Dim field = [property].AssociatedField Assert.Equal([property], field.AssociatedSymbol) Dim substitutedType = type.Construct(compilation.GetSpecialType(SpecialType.System_Int32)) Dim substitutedProperty = substitutedType.GetMember(Of PropertySymbol)("P") Dim substitutedField = substitutedProperty.AssociatedField Assert.IsType(Of SubstitutedFieldSymbol)(substitutedField) Assert.Equal(substitutedProperty, substitutedField.AssociatedSymbol) End Sub <WorkItem(26364, "https://github.com/dotnet/roslyn/issues/26364")> <WorkItem(54799, "https://github.com/dotnet/roslyn/issues/54799")> <Fact> Public Sub FixedSizeBufferFalse() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="AAA"> <file name="a.vb"> Public Structure S Private goo as Byte End Structure </file> </compilation>) Dim globalNS = compilation.SourceModule.GlobalNamespace Dim s = globalNS.GetMember(Of NamedTypeSymbol)("S") Dim goo = DirectCast(s.GetMember(Of FieldSymbol)("goo"), IFieldSymbol) Assert.False(goo.IsFixedSizeBuffer) Assert.Equal(0, goo.FixedSize) End Sub End Class End Namespace
1
dotnet/roslyn
55,354
Add IFieldSymbol.FixedSize API
Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
333fred
2021-08-02T22:15:12Z
2021-08-03T21:43:37Z
76bdda7fe502a74f91aee0feb2fe251039be4e82
a81b07d0d5a6b5c5430443fc843e4a730399c946
Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
./src/Features/Core/Portable/MetadataAsSource/AbstractMetadataAsSourceService.WrappedFieldSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.DocumentationComments; namespace Microsoft.CodeAnalysis.MetadataAsSource { internal partial class AbstractMetadataAsSourceService { private class WrappedFieldSymbol : AbstractWrappedSymbol, IFieldSymbol { private readonly IFieldSymbol _symbol; public WrappedFieldSymbol(IFieldSymbol fieldSymbol, IDocumentationCommentFormattingService docCommentFormattingService) : base(fieldSymbol, canImplementImplicitly: false, docCommentFormattingService: docCommentFormattingService) { _symbol = fieldSymbol; } public new IFieldSymbol OriginalDefinition => _symbol.OriginalDefinition; public IFieldSymbol CorrespondingTupleField => null; public ISymbol AssociatedSymbol => _symbol.AssociatedSymbol; public object ConstantValue => _symbol.ConstantValue; public ImmutableArray<CustomModifier> CustomModifiers => _symbol.CustomModifiers; public bool HasConstantValue => _symbol.HasConstantValue; public bool IsConst => _symbol.IsConst; public bool IsReadOnly => _symbol.IsReadOnly; public bool IsVolatile => _symbol.IsVolatile; public bool IsFixedSizeBuffer => _symbol.IsFixedSizeBuffer; public ITypeSymbol Type => _symbol.Type; public NullableAnnotation NullableAnnotation => _symbol.NullableAnnotation; public bool IsExplicitlyNamedTupleElement => _symbol.IsExplicitlyNamedTupleElement; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.DocumentationComments; namespace Microsoft.CodeAnalysis.MetadataAsSource { internal partial class AbstractMetadataAsSourceService { private class WrappedFieldSymbol : AbstractWrappedSymbol, IFieldSymbol { private readonly IFieldSymbol _symbol; public WrappedFieldSymbol(IFieldSymbol fieldSymbol, IDocumentationCommentFormattingService docCommentFormattingService) : base(fieldSymbol, canImplementImplicitly: false, docCommentFormattingService: docCommentFormattingService) { _symbol = fieldSymbol; } public new IFieldSymbol OriginalDefinition => _symbol.OriginalDefinition; public IFieldSymbol CorrespondingTupleField => null; public ISymbol AssociatedSymbol => _symbol.AssociatedSymbol; public object ConstantValue => _symbol.ConstantValue; public ImmutableArray<CustomModifier> CustomModifiers => _symbol.CustomModifiers; public bool HasConstantValue => _symbol.HasConstantValue; public bool IsConst => _symbol.IsConst; public bool IsReadOnly => _symbol.IsReadOnly; public bool IsVolatile => _symbol.IsVolatile; public bool IsFixedSizeBuffer => _symbol.IsFixedSizeBuffer; public int FixedSize => _symbol.FixedSize; public ITypeSymbol Type => _symbol.Type; public NullableAnnotation NullableAnnotation => _symbol.NullableAnnotation; public bool IsExplicitlyNamedTupleElement => _symbol.IsExplicitlyNamedTupleElement; } } }
1
dotnet/roslyn
55,354
Add IFieldSymbol.FixedSize API
Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
333fred
2021-08-02T22:15:12Z
2021-08-03T21:43:37Z
76bdda7fe502a74f91aee0feb2fe251039be4e82
a81b07d0d5a6b5c5430443fc843e4a730399c946
Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
./src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationFieldSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Editing; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationFieldSymbol : CodeGenerationSymbol, IFieldSymbol { public ITypeSymbol Type { get; } public NullableAnnotation NullableAnnotation => Type.NullableAnnotation; public object ConstantValue { get; } public bool HasConstantValue { get; } public CodeGenerationFieldSymbol( INamedTypeSymbol containingType, ImmutableArray<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol type, string name, bool hasConstantValue, object constantValue) : base(containingType?.ContainingAssembly, containingType, attributes, accessibility, modifiers, name) { this.Type = type; this.HasConstantValue = hasConstantValue; this.ConstantValue = constantValue; } protected override CodeGenerationSymbol Clone() { return new CodeGenerationFieldSymbol( this.ContainingType, this.GetAttributes(), this.DeclaredAccessibility, this.Modifiers, this.Type, this.Name, this.HasConstantValue, this.ConstantValue); } public new IFieldSymbol OriginalDefinition { get { return this; } } public IFieldSymbol CorrespondingTupleField => null; public override SymbolKind Kind => SymbolKind.Field; public override void Accept(SymbolVisitor visitor) => visitor.VisitField(this); public override TResult Accept<TResult>(SymbolVisitor<TResult> visitor) => visitor.VisitField(this); public bool IsConst { get { return this.Modifiers.IsConst; } } public bool IsReadOnly { get { return this.Modifiers.IsReadOnly; } } public bool IsVolatile => false; public bool IsFixedSizeBuffer => false; public ImmutableArray<CustomModifier> CustomModifiers { get { return ImmutableArray.Create<CustomModifier>(); } } public ISymbol AssociatedSymbol => null; public bool IsExplicitlyNamedTupleElement => 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.Collections.Immutable; using Microsoft.CodeAnalysis.Editing; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationFieldSymbol : CodeGenerationSymbol, IFieldSymbol { public ITypeSymbol Type { get; } public NullableAnnotation NullableAnnotation => Type.NullableAnnotation; public object ConstantValue { get; } public bool HasConstantValue { get; } public CodeGenerationFieldSymbol( INamedTypeSymbol containingType, ImmutableArray<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol type, string name, bool hasConstantValue, object constantValue) : base(containingType?.ContainingAssembly, containingType, attributes, accessibility, modifiers, name) { this.Type = type; this.HasConstantValue = hasConstantValue; this.ConstantValue = constantValue; } protected override CodeGenerationSymbol Clone() { return new CodeGenerationFieldSymbol( this.ContainingType, this.GetAttributes(), this.DeclaredAccessibility, this.Modifiers, this.Type, this.Name, this.HasConstantValue, this.ConstantValue); } public new IFieldSymbol OriginalDefinition { get { return this; } } public IFieldSymbol CorrespondingTupleField => null; public override SymbolKind Kind => SymbolKind.Field; public override void Accept(SymbolVisitor visitor) => visitor.VisitField(this); public override TResult Accept<TResult>(SymbolVisitor<TResult> visitor) => visitor.VisitField(this); public bool IsConst { get { return this.Modifiers.IsConst; } } public bool IsReadOnly { get { return this.Modifiers.IsReadOnly; } } public bool IsVolatile => false; public bool IsFixedSizeBuffer => false; public int FixedSize => 0; public ImmutableArray<CustomModifier> CustomModifiers { get { return ImmutableArray.Create<CustomModifier>(); } } public ISymbol AssociatedSymbol => null; public bool IsExplicitlyNamedTupleElement => false; } }
1
dotnet/roslyn
55,354
Add IFieldSymbol.FixedSize API
Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
333fred
2021-08-02T22:15:12Z
2021-08-03T21:43:37Z
76bdda7fe502a74f91aee0feb2fe251039be4e82
a81b07d0d5a6b5c5430443fc843e4a730399c946
Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
./src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/AwaitCompletionProviderTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic.Completion.Providers Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders Public Class AwaitCompletionProviderTests Inherits AbstractVisualBasicCompletionProviderTests Friend Overrides Function GetCompletionProviderType() As Type Return GetType(AwaitCompletionProvider) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub InSynchronousMethodTest() VerifyItemExistsAsync(" Class C Sub Goo() Dim z = $$ End Sub End Class ", "Await") End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub InMethodStatementTest() VerifyItemExistsAsync(" Class C Async Sub Goo() $$ End Sub End Class ", "Await") End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub InMethodExpressionTest() VerifyItemExistsAsync(" Class C Async Sub Goo() Dim z = $$ End Sub End Class ", "Await") End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub NotInCatchTest() VerifyItemExistsAsync(" Class C Async Sub Goo() Try Catch Dim z = $$ End Try End Sub End Class ", "Await") End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub NotInCatchExceptionFilterTest() VerifyNoItemsExistAsync(" Class C Async Sub Goo() Try Catch When Err = $$ End Try End Sub End Class ") End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub InCatchNestedDelegateTest() VerifyItemExistsAsync(" Class C Async Sub Goo() Try Catch Dim z = Function() $$ End Try End Sub End Class ", "Await") End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub NotInFinallyTest() VerifyItemExistsAsync(" Class C Async Sub Goo() Try Finally Dim z = $$ End Try End Sub End Class ", "Await") End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub NotInSyncLockTest() VerifyItemExistsAsync(" Class C Async Sub Goo() SyncLock True Dim z = $$ End SyncLock End Sub End Class ", "Await") End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic.Completion.Providers Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders Public Class AwaitCompletionProviderTests Inherits AbstractVisualBasicCompletionProviderTests Friend Overrides Function GetCompletionProviderType() As Type Return GetType(AwaitCompletionProvider) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub InSynchronousMethodTest() VerifyItemExistsAsync(" Class C Sub Goo() Dim z = $$ End Sub End Class ", "Await") End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub InMethodStatementTest() VerifyItemExistsAsync(" Class C Async Sub Goo() $$ End Sub End Class ", "Await") End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub InMethodExpressionTest() VerifyItemExistsAsync(" Class C Async Sub Goo() Dim z = $$ End Sub End Class ", "Await") End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub NotInCatchTest() VerifyItemExistsAsync(" Class C Async Sub Goo() Try Catch Dim z = $$ End Try End Sub End Class ", "Await") End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub NotInCatchExceptionFilterTest() VerifyNoItemsExistAsync(" Class C Async Sub Goo() Try Catch When Err = $$ End Try End Sub End Class ") End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub InCatchNestedDelegateTest() VerifyItemExistsAsync(" Class C Async Sub Goo() Try Catch Dim z = Function() $$ End Try End Sub End Class ", "Await") End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub NotInFinallyTest() VerifyItemExistsAsync(" Class C Async Sub Goo() Try Finally Dim z = $$ End Try End Sub End Class ", "Await") End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub NotInSyncLockTest() VerifyItemExistsAsync(" Class C Async Sub Goo() SyncLock True Dim z = $$ End SyncLock End Sub End Class ", "Await") End Sub End Class End Namespace
-1
dotnet/roslyn
55,354
Add IFieldSymbol.FixedSize API
Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
333fred
2021-08-02T22:15:12Z
2021-08-03T21:43:37Z
76bdda7fe502a74f91aee0feb2fe251039be4e82
a81b07d0d5a6b5c5430443fc843e4a730399c946
Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
./src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Formatting/FormatDocumentRangeHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Xaml; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer.Handler { [ExportLspRequestHandlerProvider(StringConstants.XamlLanguageName), Shared] [ProvidesMethod(Methods.TextDocumentRangeFormattingName)] internal class FormatDocumentRangeHandler : AbstractFormatDocumentHandlerBase<DocumentRangeFormattingParams, TextEdit[]> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FormatDocumentRangeHandler() { } public override string Method => Methods.TextDocumentRangeFormattingName; public override TextDocumentIdentifier? GetTextDocumentIdentifier(DocumentRangeFormattingParams request) => request.TextDocument; public override Task<TextEdit[]> HandleRequestAsync(DocumentRangeFormattingParams request, RequestContext context, CancellationToken cancellationToken) => GetTextEditsAsync(request.Options, context, cancellationToken, range: request.Range); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Xaml; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer.Handler { [ExportLspRequestHandlerProvider(StringConstants.XamlLanguageName), Shared] [ProvidesMethod(Methods.TextDocumentRangeFormattingName)] internal class FormatDocumentRangeHandler : AbstractFormatDocumentHandlerBase<DocumentRangeFormattingParams, TextEdit[]> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FormatDocumentRangeHandler() { } public override string Method => Methods.TextDocumentRangeFormattingName; public override TextDocumentIdentifier? GetTextDocumentIdentifier(DocumentRangeFormattingParams request) => request.TextDocument; public override Task<TextEdit[]> HandleRequestAsync(DocumentRangeFormattingParams request, RequestContext context, CancellationToken cancellationToken) => GetTextEditsAsync(request.Options, context, cancellationToken, range: request.Range); } }
-1
dotnet/roslyn
55,354
Add IFieldSymbol.FixedSize API
Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
333fred
2021-08-02T22:15:12Z
2021-08-03T21:43:37Z
76bdda7fe502a74f91aee0feb2fe251039be4e82
a81b07d0d5a6b5c5430443fc843e4a730399c946
Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
./src/Compilers/Core/Portable/Symbols/TypeParameterKind.cs
// Licensed to the .NET Foundation under one or more 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 { /// <summary> /// Represents the different kinds of type parameters. /// </summary> public enum TypeParameterKind { /// <summary> /// Type parameter of a named type. For example: <c>T</c> in <c><![CDATA[List<T>]]></c>. /// </summary> Type = 0, /// <summary> /// Type parameter of a method. For example: <c>T</c> in <c><![CDATA[void M<T>()]]></c>. /// </summary> Method = 1, /// <summary> /// Type parameter in a <c>cref</c> attribute in XML documentation comments. For example: <c>T</c> in <c><![CDATA[<see cref="List{T}"/>]]></c>. /// </summary> Cref = 2, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis { /// <summary> /// Represents the different kinds of type parameters. /// </summary> public enum TypeParameterKind { /// <summary> /// Type parameter of a named type. For example: <c>T</c> in <c><![CDATA[List<T>]]></c>. /// </summary> Type = 0, /// <summary> /// Type parameter of a method. For example: <c>T</c> in <c><![CDATA[void M<T>()]]></c>. /// </summary> Method = 1, /// <summary> /// Type parameter in a <c>cref</c> attribute in XML documentation comments. For example: <c>T</c> in <c><![CDATA[<see cref="List{T}"/>]]></c>. /// </summary> Cref = 2, } }
-1
dotnet/roslyn
55,354
Add IFieldSymbol.FixedSize API
Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
333fred
2021-08-02T22:15:12Z
2021-08-03T21:43:37Z
76bdda7fe502a74f91aee0feb2fe251039be4e82
a81b07d0d5a6b5c5430443fc843e4a730399c946
Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
./src/Workspaces/VisualBasic/Portable/Composition/VisualBasicWorkspaceFeatures.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Composition #If False Then Public Class VisualBasicWorkspaceFeatures Inherits FeaturePack Public Shared ReadOnly Instance As New VisualBasicWorkspaceFeatures() Private Sub New() End Sub Friend Overrides Function ComposeExports(root As ExportSource) As ExportSource Dim list = New ExportList() ' Case Correction list.Add( New Lazy(Of ILanguageServiceFactory, LanguageServiceMetadata)( Function() New Microsoft.CodeAnalysis.VisualBasic.CaseCorrection.VisualBasicCaseCorrectionServiceFactory(), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(Microsoft.CodeAnalysis.CaseCorrection.ICaseCorrectionService), ServiceLayer.Default))) ' Code Cleanup list.Add( New Lazy(Of ILanguageServiceFactory, LanguageServiceMetadata)( Function() New Microsoft.CodeAnalysis.VisualBasic.CodeCleanup.VisualBasicCodeCleanerServiceFactory(), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(Microsoft.CodeAnalysis.CodeCleanup.ICodeCleanerService), ServiceLayer.Default))) list.Add( New Lazy(Of Microsoft.CodeAnalysis.CodeCleanup.Providers.ICodeCleanupProvider, OrderableLanguageMetadata)( Function() New Microsoft.CodeAnalysis.CodeCleanup.Providers.AddMissingTokensCodeCleanupProvider(), New OrderableLanguageMetadata(Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.AddMissingTokens, LanguageNames.VisualBasic, before:={Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.Simplification}))) list.Add( New Lazy(Of Microsoft.CodeAnalysis.CodeCleanup.Providers.ICodeCleanupProvider, OrderableLanguageMetadata)( Function() New Microsoft.CodeAnalysis.CodeCleanup.Providers.CaseCorrectionCodeCleanupProvider(), New OrderableLanguageMetadata(Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.CaseCorrection, LanguageNames.VisualBasic, before:={Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.Simplification}))) list.Add( New Lazy(Of Microsoft.CodeAnalysis.CodeCleanup.Providers.ICodeCleanupProvider, OrderableLanguageMetadata)( Function() New Microsoft.CodeAnalysis.CodeCleanup.Providers.FixIncorrectTokensCodeCleanupProvider(), New OrderableLanguageMetadata(Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.FixIncorrectTokens, LanguageNames.VisualBasic, after:={Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.AddMissingTokens}, before:={Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.Simplification}))) list.Add( New Lazy(Of Microsoft.CodeAnalysis.CodeCleanup.Providers.ICodeCleanupProvider, OrderableLanguageMetadata)( Function() New Microsoft.CodeAnalysis.CodeCleanup.Providers.NormalizeModifiersOrOperatorsCodeCleanupProvider(), New OrderableLanguageMetadata(Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.NormalizeModifiersOrOperators, LanguageNames.VisualBasic, after:={Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.AddMissingTokens}, before:={Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.Simplification}))) list.Add( New Lazy(Of Microsoft.CodeAnalysis.CodeCleanup.Providers.ICodeCleanupProvider, OrderableLanguageMetadata)( Function() New Microsoft.CodeAnalysis.CodeCleanup.Providers.ReduceTokensCodeCleanupProvider(), New OrderableLanguageMetadata(Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.ReduceTokens, LanguageNames.VisualBasic, after:={Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.AddMissingTokens}, before:={Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.Simplification}))) list.Add( New Lazy(Of Microsoft.CodeAnalysis.CodeCleanup.Providers.ICodeCleanupProvider, OrderableLanguageMetadata)( Function() New Microsoft.CodeAnalysis.CodeCleanup.Providers.RemoveUnnecessaryLineContinuationCodeCleanupProvider(), New OrderableLanguageMetadata(Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.RemoveUnnecessaryLineContinuation, LanguageNames.VisualBasic, after:={Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.NormalizeModifiersOrOperators}, before:={Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.Simplification}))) list.Add( New Lazy(Of Microsoft.CodeAnalysis.CodeCleanup.Providers.ICodeCleanupProvider, OrderableLanguageMetadata)( Function() New Microsoft.CodeAnalysis.CodeCleanup.Providers.SimplificationCodeCleanupProvider(), New OrderableLanguageMetadata(Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.Simplification, LanguageNames.VisualBasic, before:={Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.Format}))) list.Add( New Lazy(Of Microsoft.CodeAnalysis.CodeCleanup.Providers.ICodeCleanupProvider, OrderableLanguageMetadata)( Function() New Microsoft.CodeAnalysis.CodeCleanup.Providers.FormatCodeCleanupProvider(), New OrderableLanguageMetadata(Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.Format, LanguageNames.VisualBasic, after:={Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.Simplification}))) ' Code Generation list.Add( New Lazy(Of ILanguageServiceFactory, LanguageServiceMetadata)( Function() New Microsoft.CodeAnalysis.VisualBasic.CodeGeneration.VisualBasicCodeGenerationServiceFactory(), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(Microsoft.CodeAnalysis.CodeGeneration.ICodeGenerationService), ServiceLayer.Default))) list.Add( New Lazy(Of ILanguageService, LanguageServiceMetadata)( Function() New Microsoft.CodeAnalysis.VisualBasic.CodeGeneration.VisualBasicSyntaxFactory(), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(Microsoft.CodeAnalysis.CodeGeneration.ISyntaxFactoryService), ServiceLayer.Default))) ' Formatting list.Add( New Lazy(Of ILanguageService, LanguageServiceMetadata)( Function() New Microsoft.CodeAnalysis.VisualBasic.Formatting.VisualBasicFormattingService(root), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(Microsoft.CodeAnalysis.Formatting.IFormattingService), ServiceLayer.Default))) list.Add( New Lazy(Of Microsoft.CodeAnalysis.Formatting.Rules.IFormattingRule, OrderableLanguageMetadata)( Function() New Microsoft.CodeAnalysis.VisualBasic.Formatting.AdjustSpaceFormattingRule(), New OrderableLanguageMetadata(Microsoft.CodeAnalysis.VisualBasic.Formatting.AdjustSpaceFormattingRule.Name, LanguageNames.VisualBasic, after:={Microsoft.CodeAnalysis.VisualBasic.Formatting.ElasticTriviaFormattingRule.Name}))) list.Add( New Lazy(Of Microsoft.CodeAnalysis.Formatting.Rules.IFormattingRule, OrderableLanguageMetadata)( Function() New Microsoft.CodeAnalysis.VisualBasic.Formatting.AlignTokensFormattingRule(), New OrderableLanguageMetadata(Microsoft.CodeAnalysis.VisualBasic.Formatting.AlignTokensFormattingRule.Name, LanguageNames.VisualBasic, after:={Microsoft.CodeAnalysis.VisualBasic.Formatting.AdjustSpaceFormattingRule.Name}))) list.Add( New Lazy(Of Microsoft.CodeAnalysis.Formatting.Rules.IFormattingRule, OrderableLanguageMetadata)( Function() New Microsoft.CodeAnalysis.VisualBasic.Formatting.ElasticTriviaFormattingRule(), New OrderableLanguageMetadata(Microsoft.CodeAnalysis.VisualBasic.Formatting.ElasticTriviaFormattingRule.Name, LanguageNames.VisualBasic, after:={Microsoft.CodeAnalysis.VisualBasic.Formatting.StructuredTriviaFormattingRule.Name}))) list.Add( New Lazy(Of Microsoft.CodeAnalysis.Formatting.Rules.IFormattingRule, OrderableLanguageMetadata)( Function() New Microsoft.CodeAnalysis.VisualBasic.Formatting.NodeBasedFormattingRule(), New OrderableLanguageMetadata(Microsoft.CodeAnalysis.VisualBasic.Formatting.NodeBasedFormattingRule.Name, LanguageNames.VisualBasic, after:={Microsoft.CodeAnalysis.VisualBasic.Formatting.AlignTokensFormattingRule.Name}))) list.Add( New Lazy(Of Microsoft.CodeAnalysis.Formatting.Rules.IFormattingRule, OrderableLanguageMetadata)( Function() New Microsoft.CodeAnalysis.VisualBasic.Formatting.StructuredTriviaFormattingRule(), New OrderableLanguageMetadata(Microsoft.CodeAnalysis.VisualBasic.Formatting.StructuredTriviaFormattingRule.Name, LanguageNames.VisualBasic))) ' Recommendation service list.Add( New Lazy(Of ILanguageService, LanguageServiceMetadata)( Function() New VisualBasicRecommendationService(), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(IRecommendationService), ServiceLayer.Default))) ' Command Line Arguments list.Add( New Lazy(Of ILanguageService, LanguageServiceMetadata)( Function() New VisualBasicCommandLineArgumentsFactoryService(), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(ICommandLineArgumentsFactoryService), ServiceLayer.Default))) ' Compilation Factory list.Add( New Lazy(Of ILanguageService, LanguageServiceMetadata)( Function() New VisualBasicCompilationFactoryService(), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(ICompilationFactoryService), ServiceLayer.Default))) ' Project File Loader list.Add( New Lazy(Of ILanguageService, LanguageServiceMetadata)( Function() New VisualBasicProjectFileLoaderService(), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(Host.ProjectFileLoader.IProjectFileLoaderLanguageService), ServiceLayer.Default))) ' Semantic Facts list.Add( New Lazy(Of ILanguageService, LanguageServiceMetadata)( Function() New VisualBasicSemanticFactsService(), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(ISemanticFactsService), ServiceLayer.Default))) ' Symbol Declaration list.Add( New Lazy(Of ILanguageService, LanguageServiceMetadata)( Function() New VisualBasicSymbolDeclarationService(), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(ISymbolDeclarationService), ServiceLayer.Default))) ' Syntax Facts list.Add( New Lazy(Of ILanguageService, LanguageServiceMetadata)( Function() New VisualBasicSyntaxFactsService(), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(ISyntaxFactsService), ServiceLayer.Default))) ' SyntaxTree Factory list.Add( New Lazy(Of ILanguageServiceFactory, LanguageServiceMetadata)( Function() New VisualBasicSyntaxTreeFactoryServiceFactory(), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(ISyntaxTreeFactoryService), ServiceLayer.Default))) ' Syntax Version list.Add( New Lazy(Of ILanguageService, LanguageServiceMetadata)( Function() New VisualBasicSyntaxVersionLanguageService(), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(ISyntaxVersionLanguageService), ServiceLayer.Default))) ' Type Inference list.Add( New Lazy(Of ILanguageService, LanguageServiceMetadata)( Function() New VisualBasicTypeInferenceService(), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(ITypeInferenceService), ServiceLayer.Default))) ' Rename Rewriter list.Add( New Lazy(Of ILanguageServiceFactory, LanguageServiceMetadata)( Function() New Microsoft.CodeAnalysis.VisualBasic.Rename.VisualBasicRenameRewriterLanguageServiceFactory(), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(Microsoft.CodeAnalysis.Rename.IRenameRewriterLanguageService), ServiceLayer.Default))) ' Simplification list.Add( New Lazy(Of ILanguageService, LanguageServiceMetadata)( Function() New Microsoft.CodeAnalysis.VisualBasic.Simplification.VisualBasicSimplificationService(), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(Microsoft.CodeAnalysis.Simplification.ISimplificationService), ServiceLayer.Default))) Return list End Function End Class #End If End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Composition #If False Then Public Class VisualBasicWorkspaceFeatures Inherits FeaturePack Public Shared ReadOnly Instance As New VisualBasicWorkspaceFeatures() Private Sub New() End Sub Friend Overrides Function ComposeExports(root As ExportSource) As ExportSource Dim list = New ExportList() ' Case Correction list.Add( New Lazy(Of ILanguageServiceFactory, LanguageServiceMetadata)( Function() New Microsoft.CodeAnalysis.VisualBasic.CaseCorrection.VisualBasicCaseCorrectionServiceFactory(), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(Microsoft.CodeAnalysis.CaseCorrection.ICaseCorrectionService), ServiceLayer.Default))) ' Code Cleanup list.Add( New Lazy(Of ILanguageServiceFactory, LanguageServiceMetadata)( Function() New Microsoft.CodeAnalysis.VisualBasic.CodeCleanup.VisualBasicCodeCleanerServiceFactory(), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(Microsoft.CodeAnalysis.CodeCleanup.ICodeCleanerService), ServiceLayer.Default))) list.Add( New Lazy(Of Microsoft.CodeAnalysis.CodeCleanup.Providers.ICodeCleanupProvider, OrderableLanguageMetadata)( Function() New Microsoft.CodeAnalysis.CodeCleanup.Providers.AddMissingTokensCodeCleanupProvider(), New OrderableLanguageMetadata(Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.AddMissingTokens, LanguageNames.VisualBasic, before:={Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.Simplification}))) list.Add( New Lazy(Of Microsoft.CodeAnalysis.CodeCleanup.Providers.ICodeCleanupProvider, OrderableLanguageMetadata)( Function() New Microsoft.CodeAnalysis.CodeCleanup.Providers.CaseCorrectionCodeCleanupProvider(), New OrderableLanguageMetadata(Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.CaseCorrection, LanguageNames.VisualBasic, before:={Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.Simplification}))) list.Add( New Lazy(Of Microsoft.CodeAnalysis.CodeCleanup.Providers.ICodeCleanupProvider, OrderableLanguageMetadata)( Function() New Microsoft.CodeAnalysis.CodeCleanup.Providers.FixIncorrectTokensCodeCleanupProvider(), New OrderableLanguageMetadata(Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.FixIncorrectTokens, LanguageNames.VisualBasic, after:={Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.AddMissingTokens}, before:={Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.Simplification}))) list.Add( New Lazy(Of Microsoft.CodeAnalysis.CodeCleanup.Providers.ICodeCleanupProvider, OrderableLanguageMetadata)( Function() New Microsoft.CodeAnalysis.CodeCleanup.Providers.NormalizeModifiersOrOperatorsCodeCleanupProvider(), New OrderableLanguageMetadata(Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.NormalizeModifiersOrOperators, LanguageNames.VisualBasic, after:={Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.AddMissingTokens}, before:={Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.Simplification}))) list.Add( New Lazy(Of Microsoft.CodeAnalysis.CodeCleanup.Providers.ICodeCleanupProvider, OrderableLanguageMetadata)( Function() New Microsoft.CodeAnalysis.CodeCleanup.Providers.ReduceTokensCodeCleanupProvider(), New OrderableLanguageMetadata(Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.ReduceTokens, LanguageNames.VisualBasic, after:={Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.AddMissingTokens}, before:={Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.Simplification}))) list.Add( New Lazy(Of Microsoft.CodeAnalysis.CodeCleanup.Providers.ICodeCleanupProvider, OrderableLanguageMetadata)( Function() New Microsoft.CodeAnalysis.CodeCleanup.Providers.RemoveUnnecessaryLineContinuationCodeCleanupProvider(), New OrderableLanguageMetadata(Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.RemoveUnnecessaryLineContinuation, LanguageNames.VisualBasic, after:={Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.NormalizeModifiersOrOperators}, before:={Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.Simplification}))) list.Add( New Lazy(Of Microsoft.CodeAnalysis.CodeCleanup.Providers.ICodeCleanupProvider, OrderableLanguageMetadata)( Function() New Microsoft.CodeAnalysis.CodeCleanup.Providers.SimplificationCodeCleanupProvider(), New OrderableLanguageMetadata(Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.Simplification, LanguageNames.VisualBasic, before:={Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.Format}))) list.Add( New Lazy(Of Microsoft.CodeAnalysis.CodeCleanup.Providers.ICodeCleanupProvider, OrderableLanguageMetadata)( Function() New Microsoft.CodeAnalysis.CodeCleanup.Providers.FormatCodeCleanupProvider(), New OrderableLanguageMetadata(Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.Format, LanguageNames.VisualBasic, after:={Microsoft.CodeAnalysis.CodeCleanup.Providers.PredefinedCodeCleanupProviderNames.Simplification}))) ' Code Generation list.Add( New Lazy(Of ILanguageServiceFactory, LanguageServiceMetadata)( Function() New Microsoft.CodeAnalysis.VisualBasic.CodeGeneration.VisualBasicCodeGenerationServiceFactory(), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(Microsoft.CodeAnalysis.CodeGeneration.ICodeGenerationService), ServiceLayer.Default))) list.Add( New Lazy(Of ILanguageService, LanguageServiceMetadata)( Function() New Microsoft.CodeAnalysis.VisualBasic.CodeGeneration.VisualBasicSyntaxFactory(), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(Microsoft.CodeAnalysis.CodeGeneration.ISyntaxFactoryService), ServiceLayer.Default))) ' Formatting list.Add( New Lazy(Of ILanguageService, LanguageServiceMetadata)( Function() New Microsoft.CodeAnalysis.VisualBasic.Formatting.VisualBasicFormattingService(root), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(Microsoft.CodeAnalysis.Formatting.IFormattingService), ServiceLayer.Default))) list.Add( New Lazy(Of Microsoft.CodeAnalysis.Formatting.Rules.IFormattingRule, OrderableLanguageMetadata)( Function() New Microsoft.CodeAnalysis.VisualBasic.Formatting.AdjustSpaceFormattingRule(), New OrderableLanguageMetadata(Microsoft.CodeAnalysis.VisualBasic.Formatting.AdjustSpaceFormattingRule.Name, LanguageNames.VisualBasic, after:={Microsoft.CodeAnalysis.VisualBasic.Formatting.ElasticTriviaFormattingRule.Name}))) list.Add( New Lazy(Of Microsoft.CodeAnalysis.Formatting.Rules.IFormattingRule, OrderableLanguageMetadata)( Function() New Microsoft.CodeAnalysis.VisualBasic.Formatting.AlignTokensFormattingRule(), New OrderableLanguageMetadata(Microsoft.CodeAnalysis.VisualBasic.Formatting.AlignTokensFormattingRule.Name, LanguageNames.VisualBasic, after:={Microsoft.CodeAnalysis.VisualBasic.Formatting.AdjustSpaceFormattingRule.Name}))) list.Add( New Lazy(Of Microsoft.CodeAnalysis.Formatting.Rules.IFormattingRule, OrderableLanguageMetadata)( Function() New Microsoft.CodeAnalysis.VisualBasic.Formatting.ElasticTriviaFormattingRule(), New OrderableLanguageMetadata(Microsoft.CodeAnalysis.VisualBasic.Formatting.ElasticTriviaFormattingRule.Name, LanguageNames.VisualBasic, after:={Microsoft.CodeAnalysis.VisualBasic.Formatting.StructuredTriviaFormattingRule.Name}))) list.Add( New Lazy(Of Microsoft.CodeAnalysis.Formatting.Rules.IFormattingRule, OrderableLanguageMetadata)( Function() New Microsoft.CodeAnalysis.VisualBasic.Formatting.NodeBasedFormattingRule(), New OrderableLanguageMetadata(Microsoft.CodeAnalysis.VisualBasic.Formatting.NodeBasedFormattingRule.Name, LanguageNames.VisualBasic, after:={Microsoft.CodeAnalysis.VisualBasic.Formatting.AlignTokensFormattingRule.Name}))) list.Add( New Lazy(Of Microsoft.CodeAnalysis.Formatting.Rules.IFormattingRule, OrderableLanguageMetadata)( Function() New Microsoft.CodeAnalysis.VisualBasic.Formatting.StructuredTriviaFormattingRule(), New OrderableLanguageMetadata(Microsoft.CodeAnalysis.VisualBasic.Formatting.StructuredTriviaFormattingRule.Name, LanguageNames.VisualBasic))) ' Recommendation service list.Add( New Lazy(Of ILanguageService, LanguageServiceMetadata)( Function() New VisualBasicRecommendationService(), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(IRecommendationService), ServiceLayer.Default))) ' Command Line Arguments list.Add( New Lazy(Of ILanguageService, LanguageServiceMetadata)( Function() New VisualBasicCommandLineArgumentsFactoryService(), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(ICommandLineArgumentsFactoryService), ServiceLayer.Default))) ' Compilation Factory list.Add( New Lazy(Of ILanguageService, LanguageServiceMetadata)( Function() New VisualBasicCompilationFactoryService(), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(ICompilationFactoryService), ServiceLayer.Default))) ' Project File Loader list.Add( New Lazy(Of ILanguageService, LanguageServiceMetadata)( Function() New VisualBasicProjectFileLoaderService(), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(Host.ProjectFileLoader.IProjectFileLoaderLanguageService), ServiceLayer.Default))) ' Semantic Facts list.Add( New Lazy(Of ILanguageService, LanguageServiceMetadata)( Function() New VisualBasicSemanticFactsService(), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(ISemanticFactsService), ServiceLayer.Default))) ' Symbol Declaration list.Add( New Lazy(Of ILanguageService, LanguageServiceMetadata)( Function() New VisualBasicSymbolDeclarationService(), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(ISymbolDeclarationService), ServiceLayer.Default))) ' Syntax Facts list.Add( New Lazy(Of ILanguageService, LanguageServiceMetadata)( Function() New VisualBasicSyntaxFactsService(), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(ISyntaxFactsService), ServiceLayer.Default))) ' SyntaxTree Factory list.Add( New Lazy(Of ILanguageServiceFactory, LanguageServiceMetadata)( Function() New VisualBasicSyntaxTreeFactoryServiceFactory(), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(ISyntaxTreeFactoryService), ServiceLayer.Default))) ' Syntax Version list.Add( New Lazy(Of ILanguageService, LanguageServiceMetadata)( Function() New VisualBasicSyntaxVersionLanguageService(), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(ISyntaxVersionLanguageService), ServiceLayer.Default))) ' Type Inference list.Add( New Lazy(Of ILanguageService, LanguageServiceMetadata)( Function() New VisualBasicTypeInferenceService(), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(ITypeInferenceService), ServiceLayer.Default))) ' Rename Rewriter list.Add( New Lazy(Of ILanguageServiceFactory, LanguageServiceMetadata)( Function() New Microsoft.CodeAnalysis.VisualBasic.Rename.VisualBasicRenameRewriterLanguageServiceFactory(), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(Microsoft.CodeAnalysis.Rename.IRenameRewriterLanguageService), ServiceLayer.Default))) ' Simplification list.Add( New Lazy(Of ILanguageService, LanguageServiceMetadata)( Function() New Microsoft.CodeAnalysis.VisualBasic.Simplification.VisualBasicSimplificationService(), New LanguageServiceMetadata(LanguageNames.VisualBasic, GetType(Microsoft.CodeAnalysis.Simplification.ISimplificationService), ServiceLayer.Default))) Return list End Function End Class #End If End Namespace
-1
dotnet/roslyn
55,354
Add IFieldSymbol.FixedSize API
Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
333fred
2021-08-02T22:15:12Z
2021-08-03T21:43:37Z
76bdda7fe502a74f91aee0feb2fe251039be4e82
a81b07d0d5a6b5c5430443fc843e4a730399c946
Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
./src/EditorFeatures/TestUtilities2/Intellisense/MockCompletionPresenterProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.ComponentModel.Composition Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion Imports Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Utilities Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense <Export(GetType(ICompletionPresenterProvider))> <PartNotDiscoverable> <Name(NameOf(MockCompletionPresenterProvider))> <ContentType(ContentTypeNames.RoslynContentType)> <Order(Before:=NameOf(PredefinedCompletionNames.DefaultCompletionPresenter))> Public Class MockCompletionPresenterProvider Implements ICompletionPresenterProvider Private ReadOnly _presenters As Dictionary(Of ITextView, ICompletionPresenter) = New Dictionary(Of ITextView, ICompletionPresenter)() <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public ReadOnly Property Options As CompletionPresenterOptions Implements ICompletionPresenterProvider.Options Get ' resultsPerPage can be set for any reasonable value corresponding to the number of lines in popup. ' It is used in some tests involving Up/Down keystrokes. Return New CompletionPresenterOptions(resultsPerPage:=10) End Get End Property Public Function GetOrCreate(textView As ITextView) As ICompletionPresenter Implements ICompletionPresenterProvider.GetOrCreate If Not _presenters.ContainsKey(textView) Then _presenters(textView) = New MockCompletionPresenter(textView) End If Return _presenters(textView) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.ComponentModel.Composition Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion Imports Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Utilities Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense <Export(GetType(ICompletionPresenterProvider))> <PartNotDiscoverable> <Name(NameOf(MockCompletionPresenterProvider))> <ContentType(ContentTypeNames.RoslynContentType)> <Order(Before:=NameOf(PredefinedCompletionNames.DefaultCompletionPresenter))> Public Class MockCompletionPresenterProvider Implements ICompletionPresenterProvider Private ReadOnly _presenters As Dictionary(Of ITextView, ICompletionPresenter) = New Dictionary(Of ITextView, ICompletionPresenter)() <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public ReadOnly Property Options As CompletionPresenterOptions Implements ICompletionPresenterProvider.Options Get ' resultsPerPage can be set for any reasonable value corresponding to the number of lines in popup. ' It is used in some tests involving Up/Down keystrokes. Return New CompletionPresenterOptions(resultsPerPage:=10) End Get End Property Public Function GetOrCreate(textView As ITextView) As ICompletionPresenter Implements ICompletionPresenterProvider.GetOrCreate If Not _presenters.ContainsKey(textView) Then _presenters(textView) = New MockCompletionPresenter(textView) End If Return _presenters(textView) End Function End Class End Namespace
-1
dotnet/roslyn
55,354
Add IFieldSymbol.FixedSize API
Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
333fred
2021-08-02T22:15:12Z
2021-08-03T21:43:37Z
76bdda7fe502a74f91aee0feb2fe251039be4e82
a81b07d0d5a6b5c5430443fc843e4a730399c946
Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
./src/EditorFeatures/Core/GoToDefinition/GoToSymbolContext.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.GoToDefinition { internal class GoToSymbolContext { private readonly object _gate = new(); private readonly MultiDictionary<string, DefinitionItem> _items = new(); public GoToSymbolContext(Document document, int position, CancellationToken cancellationToken) { Document = document; Position = position; CancellationToken = cancellationToken; } public Document Document { get; } public int Position { get; } public CancellationToken CancellationToken { get; } public TextSpan Span { get; set; } internal bool TryGetItems(string key, out IEnumerable<DefinitionItem> items) { if (_items.ContainsKey(key)) { // Multidictionary valuesets are structs so we can't // just check for null items = _items[key]; return true; } else { items = null; return false; } } public void AddItem(string key, DefinitionItem item) { lock (_gate) { _items.Add(key, item); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.GoToDefinition { internal class GoToSymbolContext { private readonly object _gate = new(); private readonly MultiDictionary<string, DefinitionItem> _items = new(); public GoToSymbolContext(Document document, int position, CancellationToken cancellationToken) { Document = document; Position = position; CancellationToken = cancellationToken; } public Document Document { get; } public int Position { get; } public CancellationToken CancellationToken { get; } public TextSpan Span { get; set; } internal bool TryGetItems(string key, out IEnumerable<DefinitionItem> items) { if (_items.ContainsKey(key)) { // Multidictionary valuesets are structs so we can't // just check for null items = _items[key]; return true; } else { items = null; return false; } } public void AddItem(string key, DefinitionItem item) { lock (_gate) { _items.Add(key, item); } } } }
-1
dotnet/roslyn
55,354
Add IFieldSymbol.FixedSize API
Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
333fred
2021-08-02T22:15:12Z
2021-08-03T21:43:37Z
76bdda7fe502a74f91aee0feb2fe251039be4e82
a81b07d0d5a6b5c5430443fc843e4a730399c946
Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
./src/Compilers/VisualBasic/Portable/Emit/NoPia/EmbeddedTypesManager.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports System.Collections.Concurrent Imports System.Threading #If Not DEBUG Then Imports SymbolAdapter = Microsoft.CodeAnalysis.VisualBasic.Symbol Imports NamedTypeSymbolAdapter = Microsoft.CodeAnalysis.VisualBasic.Symbols.NamedTypeSymbol Imports FieldSymbolAdapter = Microsoft.CodeAnalysis.VisualBasic.Symbols.FieldSymbol Imports MethodSymbolAdapter = Microsoft.CodeAnalysis.VisualBasic.Symbols.MethodSymbol Imports EventSymbolAdapter = Microsoft.CodeAnalysis.VisualBasic.Symbols.EventSymbol Imports PropertySymbolAdapter = Microsoft.CodeAnalysis.VisualBasic.Symbols.PropertySymbol Imports ParameterSymbolAdapter = Microsoft.CodeAnalysis.VisualBasic.Symbols.ParameterSymbol Imports TypeParameterSymbolAdapter = Microsoft.CodeAnalysis.VisualBasic.Symbols.TypeParameterSymbol #End If Namespace Microsoft.CodeAnalysis.VisualBasic.Emit.NoPia Friend NotInheritable Class EmbeddedTypesManager Inherits Microsoft.CodeAnalysis.Emit.NoPia.EmbeddedTypesManager(Of PEModuleBuilder, ModuleCompilationState, EmbeddedTypesManager, SyntaxNode, VisualBasicAttributeData, SymbolAdapter, AssemblySymbol, NamedTypeSymbolAdapter, FieldSymbolAdapter, MethodSymbolAdapter, EventSymbolAdapter, PropertySymbolAdapter, ParameterSymbolAdapter, TypeParameterSymbolAdapter, EmbeddedType, EmbeddedField, EmbeddedMethod, EmbeddedEvent, EmbeddedProperty, EmbeddedParameter, EmbeddedTypeParameter) Private ReadOnly _assemblyGuidMap As New ConcurrentDictionary(Of AssemblySymbol, String)(ReferenceEqualityComparer.Instance) Private ReadOnly _reportedSymbolsMap As New ConcurrentDictionary(Of Symbol, Boolean)(ReferenceEqualityComparer.Instance) Private _lazySystemStringType As NamedTypeSymbol = ErrorTypeSymbol.UnknownResultType Private ReadOnly _lazyWellKnownTypeMethods As MethodSymbol() Public Sub New(moduleBeingBuilt As PEModuleBuilder) MyBase.New(moduleBeingBuilt) _lazyWellKnownTypeMethods = New MethodSymbol(WellKnownMember.Count - 1) {} For i = 0 To WellKnownMember.Count - 1 _lazyWellKnownTypeMethods(i) = ErrorMethodSymbol.UnknownMethod Next End Sub Public Function GetSystemStringType(syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag) As NamedTypeSymbol If _lazySystemStringType Is ErrorTypeSymbol.UnknownResultType Then Dim type = ModuleBeingBuilt.Compilation.GetSpecialType(SpecialType.System_String) Dim info = type.GetUseSiteInfo() If type.IsErrorType() Then type = Nothing End If If TypeSymbol.Equals(Interlocked.CompareExchange(Of NamedTypeSymbol)(_lazySystemStringType, type, ErrorTypeSymbol.UnknownResultType), ErrorTypeSymbol.UnknownResultType, TypeCompareKind.ConsiderEverything) Then If info.DiagnosticInfo IsNot Nothing Then ReportDiagnostic(diagnostics, syntaxNodeOpt, info.DiagnosticInfo) End If End If End If Return _lazySystemStringType End Function Public Function GetWellKnownMethod(method As WellKnownMember, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag) As MethodSymbol Return LazyGetWellKnownTypeMethod(_lazyWellKnownTypeMethods(CInt(method)), method, syntaxNodeOpt, diagnostics) End Function Private Function LazyGetWellKnownTypeMethod(ByRef lazyMethod As MethodSymbol, method As WellKnownMember, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag) As MethodSymbol If lazyMethod Is ErrorMethodSymbol.UnknownMethod Then Dim info As UseSiteInfo(Of AssemblySymbol) = Nothing Dim symbol = DirectCast(Binder.GetWellKnownTypeMember(ModuleBeingBuilt.Compilation, method, info), MethodSymbol) Debug.Assert(info.DiagnosticInfo Is Nothing OrElse symbol Is Nothing) If Interlocked.CompareExchange(Of MethodSymbol)(lazyMethod, symbol, ErrorMethodSymbol.UnknownMethod) = ErrorMethodSymbol.UnknownMethod Then If info.DiagnosticInfo IsNot Nothing Then ReportDiagnostic(diagnostics, syntaxNodeOpt, info.DiagnosticInfo) End If End If End If Return lazyMethod End Function Friend Overrides Function GetTargetAttributeSignatureIndex(underlyingSymbol As SymbolAdapter, attrData As VisualBasicAttributeData, description As AttributeDescription) As Integer Return attrData.GetTargetAttributeSignatureIndex(underlyingSymbol.AdaptedSymbol, description) End Function Friend Overrides Function CreateSynthesizedAttribute(constructor As WellKnownMember, attrData As VisualBasicAttributeData, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag) As VisualBasicAttributeData Dim ctor = GetWellKnownMethod(constructor, syntaxNodeOpt, diagnostics) If ctor Is Nothing Then Return Nothing End If Select Case constructor Case WellKnownMember.System_Runtime_InteropServices_ComEventInterfaceAttribute__ctor ' When emitting a com event interface, we have to tweak the parameters: the spec requires that we use ' the original source interface as both source interface and event provider. Otherwise, we'd have to embed ' the event provider class too. Return New SynthesizedAttributeData(ctor, ImmutableArray.Create(attrData.CommonConstructorArguments(0), attrData.CommonConstructorArguments(0)), ImmutableArray(Of KeyValuePair(Of String, TypedConstant)).Empty) Case WellKnownMember.System_Runtime_InteropServices_CoClassAttribute__ctor ' The interface needs to have a coclass attribute so that we can tell at runtime that it should be ' instantiatable. The attribute cannot refer directly to the coclass, however, because we can't embed ' classes, and we can't emit a reference to the PIA. We don't actually need ' the class name at runtime: we will instead emit a reference to System.Object, as a placeholder. Return New SynthesizedAttributeData(ctor, ImmutableArray.Create(New TypedConstant(ctor.Parameters(0).Type, TypedConstantKind.Type, ctor.ContainingAssembly.GetSpecialType(SpecialType.System_Object))), ImmutableArray(Of KeyValuePair(Of String, TypedConstant)).Empty) Case Else Return New SynthesizedAttributeData(ctor, attrData.CommonConstructorArguments, attrData.CommonNamedArguments) End Select End Function Friend Function GetAssemblyGuidString(assembly As AssemblySymbol) As String Debug.Assert(Not IsFrozen) ' After we freeze the set of types, we might add additional assemblies into this map without actual guid values. Dim guidString As String = Nothing If _assemblyGuidMap.TryGetValue(assembly, guidString) Then Return guidString End If Debug.Assert(guidString Is Nothing) assembly.GetGuidString(guidString) Return _assemblyGuidMap.GetOrAdd(assembly, guidString) End Function Protected Overrides Sub OnGetTypesCompleted(types As ImmutableArray(Of EmbeddedType), diagnostics As DiagnosticBag) For Each t In types ' Note, once we reached this point we are no longer interested in guid values, using null. _assemblyGuidMap.TryAdd(t.UnderlyingNamedType.AdaptedNamedTypeSymbol.ContainingAssembly, Nothing) Next For Each a In ModuleBeingBuilt.GetReferencedAssembliesUsedSoFar() ReportIndirectReferencesToLinkedAssemblies(a, diagnostics) Next End Sub Protected Overrides Sub ReportNameCollisionBetweenEmbeddedTypes(typeA As EmbeddedType, typeB As EmbeddedType, diagnostics As DiagnosticBag) Dim underlyingTypeA = typeA.UnderlyingNamedType.AdaptedNamedTypeSymbol Dim underlyingTypeB = typeB.UnderlyingNamedType.AdaptedNamedTypeSymbol ReportDiagnostic(diagnostics, ERRID.ERR_DuplicateLocalTypes3, Nothing, underlyingTypeA, underlyingTypeA.ContainingAssembly, underlyingTypeB.ContainingAssembly) End Sub Protected Overrides Sub ReportNameCollisionWithAlreadyDeclaredType(type As EmbeddedType, diagnostics As DiagnosticBag) Dim underlyingType = type.UnderlyingNamedType.AdaptedNamedTypeSymbol ReportDiagnostic(diagnostics, ERRID.ERR_LocalTypeNameClash2, Nothing, underlyingType, underlyingType.ContainingAssembly) End Sub Friend Overrides Sub ReportIndirectReferencesToLinkedAssemblies(assembly As AssemblySymbol, diagnostics As DiagnosticBag) Debug.Assert(IsFrozen) ' We are emitting an assembly, A, which /references some assembly, B, and ' /links some other assembly, C, so that it can use C's types (by embedding them) ' without having an assemblyref to C itself. ' We can say that A has an indirect reference to each assembly that B references. ' In this function, we are looking for the situation where B has an assemblyref to C, ' thus giving A an indirect reference to C. If so, we will report a warning. For Each [module] In assembly.Modules For Each indirectRef In [module].GetReferencedAssemblySymbols() If Not indirectRef.IsMissing AndAlso indirectRef.IsLinked AndAlso _assemblyGuidMap.ContainsKey(indirectRef) Then ' WRNID_IndirectRefToLinkedAssembly2/WRN_ReferencedAssemblyReferencesLinkedPIA ReportDiagnostic(diagnostics, ERRID.WRN_IndirectRefToLinkedAssembly2, Nothing, indirectRef, assembly) End If Next Next End Sub ''' <summary> ''' Returns true if the type can be embedded. If the type is defined in a linked (/l-ed) ''' assembly, but doesn't meet embeddable type requirements, this function returns ''' False and reports appropriate diagnostics. ''' </summary> Friend Shared Function IsValidEmbeddableType( type As NamedTypeSymbol, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag, Optional typeManagerOpt As EmbeddedTypesManager = Nothing ) As Boolean ' We do not embed SpecialTypes (they must be defined in Core assembly), ' error types and types from assemblies that aren't linked. If type.SpecialType <> SpecialType.None OrElse type.IsErrorType() OrElse Not type.ContainingAssembly.IsLinked Then ' Assuming that we already complained about an error type, ' no additional diagnostics necessary. Return False End If Dim id = ERRID.ERR_None Select Case type.TypeKind Case TypeKind.Interface For Each member As Symbol In type.GetMembersUnordered() If member.Kind <> SymbolKind.NamedType Then If Not member.IsMustOverride Then id = ERRID.ERR_DefaultInterfaceImplementationInNoPIAType ElseIf member.IsNotOverridable Then id = ERRID.ERR_ReAbstractionInNoPIAType End If End If Next If id = ERRID.ERR_None Then GoTo checksForAllEmbedabbleTypes End If Case TypeKind.Structure, TypeKind.Enum, TypeKind.Delegate checksForAllEmbedabbleTypes: If type.IsTupleType Then type = type.TupleUnderlyingType End If If type.ContainingType IsNot Nothing Then ' We do not support nesting for embedded types. ' ERRID.ERR_InvalidInteropType/ERR_NoPIANestedType id = ERRID.ERR_NestedInteropType ElseIf type.IsGenericType Then ' We do not support generic embedded types. ' ERRID.ERR_CannotEmbedInterfaceWithGeneric/ERR_GenericsUsedInNoPIAType id = ERRID.ERR_CannotEmbedInterfaceWithGeneric End If Case Else ' ERRID.ERR_CannotLinkClassWithNoPIA1/ERR_NewCoClassOnLink Debug.Assert(type.TypeKind = TypeKind.Class OrElse type.TypeKind = TypeKind.Module) id = ERRID.ERR_CannotLinkClassWithNoPIA1 End Select If id <> ERRID.ERR_None Then ReportNotEmbeddableSymbol(id, type, syntaxNodeOpt, diagnostics, typeManagerOpt) Return False End If Return True End Function Private Sub VerifyNotFrozen() Debug.Assert(Not IsFrozen) If IsFrozen Then Throw ExceptionUtilities.UnexpectedValue(IsFrozen) End If End Sub Private Shared Sub ReportNotEmbeddableSymbol(id As ERRID, symbol As Symbol, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag, typeManagerOpt As EmbeddedTypesManager) ' Avoid reporting multiple errors for the symbol. If typeManagerOpt Is Nothing OrElse typeManagerOpt._reportedSymbolsMap.TryAdd(symbol.OriginalDefinition, True) Then ReportDiagnostic(diagnostics, id, syntaxNodeOpt, symbol.OriginalDefinition) End If End Sub Friend Shared Sub ReportDiagnostic(diagnostics As DiagnosticBag, id As ERRID, syntaxNodeOpt As SyntaxNode, ParamArray args As Object()) ReportDiagnostic(diagnostics, syntaxNodeOpt, ErrorFactory.ErrorInfo(id, args)) End Sub Private Shared Sub ReportDiagnostic(diagnostics As DiagnosticBag, syntaxNodeOpt As SyntaxNode, info As DiagnosticInfo) diagnostics.Add(New VBDiagnostic(info, If(syntaxNodeOpt Is Nothing, NoLocation.Singleton, syntaxNodeOpt.GetLocation()))) End Sub Friend Function EmbedTypeIfNeedTo(namedType As NamedTypeSymbol, fromImplements As Boolean, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag) As Cci.INamedTypeReference Debug.Assert(namedType.IsDefinition) Debug.Assert(ModuleBeingBuilt.SourceModule.AnyReferencedAssembliesAreLinked) If IsValidEmbeddableType(namedType, syntaxNodeOpt, diagnostics, Me) Then Return EmbedType(namedType, fromImplements, syntaxNodeOpt, diagnostics) End If Return Nothing End Function Private Function EmbedType(namedType As NamedTypeSymbol, fromImplements As Boolean, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag) As EmbeddedType Debug.Assert(namedType.IsDefinition) Dim adapter = namedType.GetCciAdapter() Dim embedded = New EmbeddedType(Me, adapter) Dim cached = EmbeddedTypesMap.GetOrAdd(adapter, embedded) Dim isInterface = (namedType.IsInterface) If isInterface AndAlso fromImplements Then ' Note, we must use 'cached' here because we might drop 'embedded' below. cached.EmbedAllMembersOfImplementedInterface(syntaxNodeOpt, diagnostics) End If If embedded IsNot cached Then Return cached End If ' We do not expect this method to be called on a different thread once GetTypes is called. VerifyNotFrozen() Dim noPiaIndexer = New Cci.TypeReferenceIndexer(New EmitContext(ModuleBeingBuilt, syntaxNodeOpt, diagnostics, metadataOnly:=False, includePrivateMembers:=True)) ' Make sure we embed all types referenced by the type declaration: implemented interfaces, etc. noPiaIndexer.VisitTypeDefinitionNoMembers(embedded) If Not isInterface Then Debug.Assert(namedType.TypeKind = TypeKind.Structure OrElse namedType.TypeKind = TypeKind.Enum OrElse namedType.TypeKind = TypeKind.Delegate) ' For structures, enums and delegates we embed all members. If namedType.TypeKind = TypeKind.Structure OrElse namedType.TypeKind = TypeKind.Enum Then ' TODO: When building debug versions in the IDE, the compiler will insert some extra members ' that support ENC. These make no sense in local types, so we will skip them. We have to ' check for them explicitly or they will trip the member-validity check that follows. End If For Each f In namedType.GetFieldsToEmit() EmbedField(embedded, f.GetCciAdapter(), syntaxNodeOpt, diagnostics) Next For Each m In namedType.GetMethodsToEmit() EmbedMethod(embedded, m.GetCciAdapter(), syntaxNodeOpt, diagnostics) Next ' We also should embed properties and events, but we don't need to do this explicitly here ' because accessors embed them automatically. End If Return embedded End Function Friend Overrides Function EmbedField( type As EmbeddedType, field As FieldSymbolAdapter, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag ) As EmbeddedField Debug.Assert(field.AdaptedFieldSymbol.IsDefinition) Dim embedded = New EmbeddedField(type, field) Dim cached = EmbeddedFieldsMap.GetOrAdd(field, embedded) If embedded IsNot cached Then Return cached End If ' We do not expect this method to be called on a different thread once GetTypes is called. VerifyNotFrozen() ' Embed types referenced by this field declaration. EmbedReferences(embedded, syntaxNodeOpt, diagnostics) Dim containerKind = field.AdaptedFieldSymbol.ContainingType.TypeKind ' Structures may contain only public instance fields. If containerKind = TypeKind.Interface OrElse containerKind = TypeKind.Delegate OrElse (containerKind = TypeKind.Structure AndAlso (field.AdaptedFieldSymbol.IsShared OrElse field.AdaptedFieldSymbol.DeclaredAccessibility <> Accessibility.Public)) Then ' ERRID.ERR_InvalidStructMemberNoPIA1/ERR_InteropStructContainsMethods ReportNotEmbeddableSymbol(ERRID.ERR_InvalidStructMemberNoPIA1, type.UnderlyingNamedType.AdaptedNamedTypeSymbol, syntaxNodeOpt, diagnostics, Me) End If Return embedded End Function Friend Overrides Function EmbedMethod( type As EmbeddedType, method As MethodSymbolAdapter, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag ) As EmbeddedMethod Debug.Assert(method.AdaptedMethodSymbol.IsDefinition) Debug.Assert(Not method.AdaptedMethodSymbol.IsDefaultValueTypeConstructor()) Dim embedded = New EmbeddedMethod(type, method) Dim cached = EmbeddedMethodsMap.GetOrAdd(method, embedded) If embedded IsNot cached Then Return cached End If ' We do not expect this method to be called on a different thread once GetTypes is called. VerifyNotFrozen() ' Embed types referenced by this method declaration. EmbedReferences(embedded, syntaxNodeOpt, diagnostics) Select Case type.UnderlyingNamedType.AdaptedNamedTypeSymbol.TypeKind Case TypeKind.Structure, TypeKind.Enum ' ERRID.ERR_InvalidStructMemberNoPIA1/ERR_InteropStructContainsMethods ReportNotEmbeddableSymbol(ERRID.ERR_InvalidStructMemberNoPIA1, type.UnderlyingNamedType.AdaptedNamedTypeSymbol, syntaxNodeOpt, diagnostics, Me) Case Else If Cci.Extensions.HasBody(embedded) Then ' ERRID.ERR_InteropMethodWithBody1/ERR_InteropMethodWithBody ReportDiagnostic(diagnostics, ERRID.ERR_InteropMethodWithBody1, syntaxNodeOpt, method.AdaptedMethodSymbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)) End If End Select ' If this proc happens to belong to a property/event, we should include the property/event as well. Dim propertyOrEvent = method.AdaptedMethodSymbol.AssociatedSymbol If propertyOrEvent IsNot Nothing Then Select Case propertyOrEvent.Kind Case SymbolKind.Property EmbedProperty(type, DirectCast(propertyOrEvent, PropertySymbol).GetCciAdapter(), syntaxNodeOpt, diagnostics) Case SymbolKind.Event EmbedEvent(type, DirectCast(propertyOrEvent, EventSymbol).GetCciAdapter(), syntaxNodeOpt, diagnostics, isUsedForComAwareEventBinding:=False) Case Else Throw ExceptionUtilities.UnexpectedValue(propertyOrEvent.Kind) End Select End If Return embedded End Function Friend Overrides Function EmbedProperty( type As EmbeddedType, [property] As PropertySymbolAdapter, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag ) As EmbeddedProperty Debug.Assert([property].AdaptedPropertySymbol.IsDefinition) ' Make sure accessors are embedded. Dim getMethod = [property].AdaptedPropertySymbol.GetMethod Dim setMethod = [property].AdaptedPropertySymbol.SetMethod Dim embeddedGet = If(getMethod IsNot Nothing, EmbedMethod(type, getMethod.GetCciAdapter(), syntaxNodeOpt, diagnostics), Nothing) Dim embeddedSet = If(setMethod IsNot Nothing, EmbedMethod(type, setMethod.GetCciAdapter(), syntaxNodeOpt, diagnostics), Nothing) Dim embedded = New EmbeddedProperty([property], embeddedGet, embeddedSet) Dim cached = EmbeddedPropertiesMap.GetOrAdd([property], embedded) If embedded IsNot cached Then Return cached End If ' We do not expect this method to be called on a different thread once GetTypes is called. VerifyNotFrozen() ' Embed types referenced by this property declaration. ' This should also embed accessors. EmbedReferences(embedded, syntaxNodeOpt, diagnostics) Return embedded End Function Friend Overrides Function EmbedEvent( type As EmbeddedType, [event] As EventSymbolAdapter, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag, isUsedForComAwareEventBinding As Boolean ) As EmbeddedEvent Debug.Assert([event].AdaptedEventSymbol.IsDefinition) ' Make sure accessors are embedded. Dim addMethod = [event].AdaptedEventSymbol.AddMethod Dim removeMethod = [event].AdaptedEventSymbol.RemoveMethod Dim callMethod = [event].AdaptedEventSymbol.RaiseMethod Dim embeddedAdd = If(addMethod IsNot Nothing, EmbedMethod(type, addMethod.GetCciAdapter(), syntaxNodeOpt, diagnostics), Nothing) Dim embeddedRemove = If(removeMethod IsNot Nothing, EmbedMethod(type, removeMethod.GetCciAdapter(), syntaxNodeOpt, diagnostics), Nothing) Dim embeddedCall = If(callMethod IsNot Nothing, EmbedMethod(type, callMethod.GetCciAdapter(), syntaxNodeOpt, diagnostics), Nothing) Dim embedded = New EmbeddedEvent([event], embeddedAdd, embeddedRemove, embeddedCall) Dim cached = EmbeddedEventsMap.GetOrAdd([event], embedded) If embedded IsNot cached Then If isUsedForComAwareEventBinding Then cached.EmbedCorrespondingComEventInterfaceMethod(syntaxNodeOpt, diagnostics, isUsedForComAwareEventBinding) End If Return cached End If ' We do not expect this method to be called on a different thread once GetTypes is called. VerifyNotFrozen() ' Embed types referenced by this event declaration. ' This should also embed accessors. EmbedReferences(embedded, syntaxNodeOpt, diagnostics) embedded.EmbedCorrespondingComEventInterfaceMethod(syntaxNodeOpt, diagnostics, isUsedForComAwareEventBinding) Return embedded End Function Protected Overrides Function GetEmbeddedTypeForMember(member As SymbolAdapter, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag) As EmbeddedType Debug.Assert(member.AdaptedSymbol.IsDefinition) Debug.Assert(ModuleBeingBuilt.SourceModule.AnyReferencedAssembliesAreLinked) Dim namedType = member.AdaptedSymbol.ContainingType If IsValidEmbeddableType(namedType, syntaxNodeOpt, diagnostics, Me) Then ' It is possible that we have found a reference to a member before ' encountering a reference to its container; make sure the container gets included. Return EmbedType(namedType, fromImplements:=False, syntaxNodeOpt:=syntaxNodeOpt, diagnostics:=diagnostics) End If Return Nothing End Function Friend Shared Function EmbedParameters(containingPropertyOrMethod As CommonEmbeddedMember, underlyingParameters As ImmutableArray(Of ParameterSymbol)) As ImmutableArray(Of EmbeddedParameter) Return underlyingParameters.SelectAsArray(Function(parameter, container) New EmbeddedParameter(container, parameter.GetCciAdapter()), containingPropertyOrMethod) End Function Protected Overrides Function CreateCompilerGeneratedAttribute() As VisualBasicAttributeData Debug.Assert(WellKnownMembers.IsSynthesizedAttributeOptional(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)) Dim compilation = ModuleBeingBuilt.Compilation Return compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports System.Collections.Concurrent Imports System.Threading #If Not DEBUG Then Imports SymbolAdapter = Microsoft.CodeAnalysis.VisualBasic.Symbol Imports NamedTypeSymbolAdapter = Microsoft.CodeAnalysis.VisualBasic.Symbols.NamedTypeSymbol Imports FieldSymbolAdapter = Microsoft.CodeAnalysis.VisualBasic.Symbols.FieldSymbol Imports MethodSymbolAdapter = Microsoft.CodeAnalysis.VisualBasic.Symbols.MethodSymbol Imports EventSymbolAdapter = Microsoft.CodeAnalysis.VisualBasic.Symbols.EventSymbol Imports PropertySymbolAdapter = Microsoft.CodeAnalysis.VisualBasic.Symbols.PropertySymbol Imports ParameterSymbolAdapter = Microsoft.CodeAnalysis.VisualBasic.Symbols.ParameterSymbol Imports TypeParameterSymbolAdapter = Microsoft.CodeAnalysis.VisualBasic.Symbols.TypeParameterSymbol #End If Namespace Microsoft.CodeAnalysis.VisualBasic.Emit.NoPia Friend NotInheritable Class EmbeddedTypesManager Inherits Microsoft.CodeAnalysis.Emit.NoPia.EmbeddedTypesManager(Of PEModuleBuilder, ModuleCompilationState, EmbeddedTypesManager, SyntaxNode, VisualBasicAttributeData, SymbolAdapter, AssemblySymbol, NamedTypeSymbolAdapter, FieldSymbolAdapter, MethodSymbolAdapter, EventSymbolAdapter, PropertySymbolAdapter, ParameterSymbolAdapter, TypeParameterSymbolAdapter, EmbeddedType, EmbeddedField, EmbeddedMethod, EmbeddedEvent, EmbeddedProperty, EmbeddedParameter, EmbeddedTypeParameter) Private ReadOnly _assemblyGuidMap As New ConcurrentDictionary(Of AssemblySymbol, String)(ReferenceEqualityComparer.Instance) Private ReadOnly _reportedSymbolsMap As New ConcurrentDictionary(Of Symbol, Boolean)(ReferenceEqualityComparer.Instance) Private _lazySystemStringType As NamedTypeSymbol = ErrorTypeSymbol.UnknownResultType Private ReadOnly _lazyWellKnownTypeMethods As MethodSymbol() Public Sub New(moduleBeingBuilt As PEModuleBuilder) MyBase.New(moduleBeingBuilt) _lazyWellKnownTypeMethods = New MethodSymbol(WellKnownMember.Count - 1) {} For i = 0 To WellKnownMember.Count - 1 _lazyWellKnownTypeMethods(i) = ErrorMethodSymbol.UnknownMethod Next End Sub Public Function GetSystemStringType(syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag) As NamedTypeSymbol If _lazySystemStringType Is ErrorTypeSymbol.UnknownResultType Then Dim type = ModuleBeingBuilt.Compilation.GetSpecialType(SpecialType.System_String) Dim info = type.GetUseSiteInfo() If type.IsErrorType() Then type = Nothing End If If TypeSymbol.Equals(Interlocked.CompareExchange(Of NamedTypeSymbol)(_lazySystemStringType, type, ErrorTypeSymbol.UnknownResultType), ErrorTypeSymbol.UnknownResultType, TypeCompareKind.ConsiderEverything) Then If info.DiagnosticInfo IsNot Nothing Then ReportDiagnostic(diagnostics, syntaxNodeOpt, info.DiagnosticInfo) End If End If End If Return _lazySystemStringType End Function Public Function GetWellKnownMethod(method As WellKnownMember, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag) As MethodSymbol Return LazyGetWellKnownTypeMethod(_lazyWellKnownTypeMethods(CInt(method)), method, syntaxNodeOpt, diagnostics) End Function Private Function LazyGetWellKnownTypeMethod(ByRef lazyMethod As MethodSymbol, method As WellKnownMember, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag) As MethodSymbol If lazyMethod Is ErrorMethodSymbol.UnknownMethod Then Dim info As UseSiteInfo(Of AssemblySymbol) = Nothing Dim symbol = DirectCast(Binder.GetWellKnownTypeMember(ModuleBeingBuilt.Compilation, method, info), MethodSymbol) Debug.Assert(info.DiagnosticInfo Is Nothing OrElse symbol Is Nothing) If Interlocked.CompareExchange(Of MethodSymbol)(lazyMethod, symbol, ErrorMethodSymbol.UnknownMethod) = ErrorMethodSymbol.UnknownMethod Then If info.DiagnosticInfo IsNot Nothing Then ReportDiagnostic(diagnostics, syntaxNodeOpt, info.DiagnosticInfo) End If End If End If Return lazyMethod End Function Friend Overrides Function GetTargetAttributeSignatureIndex(underlyingSymbol As SymbolAdapter, attrData As VisualBasicAttributeData, description As AttributeDescription) As Integer Return attrData.GetTargetAttributeSignatureIndex(underlyingSymbol.AdaptedSymbol, description) End Function Friend Overrides Function CreateSynthesizedAttribute(constructor As WellKnownMember, attrData As VisualBasicAttributeData, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag) As VisualBasicAttributeData Dim ctor = GetWellKnownMethod(constructor, syntaxNodeOpt, diagnostics) If ctor Is Nothing Then Return Nothing End If Select Case constructor Case WellKnownMember.System_Runtime_InteropServices_ComEventInterfaceAttribute__ctor ' When emitting a com event interface, we have to tweak the parameters: the spec requires that we use ' the original source interface as both source interface and event provider. Otherwise, we'd have to embed ' the event provider class too. Return New SynthesizedAttributeData(ctor, ImmutableArray.Create(attrData.CommonConstructorArguments(0), attrData.CommonConstructorArguments(0)), ImmutableArray(Of KeyValuePair(Of String, TypedConstant)).Empty) Case WellKnownMember.System_Runtime_InteropServices_CoClassAttribute__ctor ' The interface needs to have a coclass attribute so that we can tell at runtime that it should be ' instantiatable. The attribute cannot refer directly to the coclass, however, because we can't embed ' classes, and we can't emit a reference to the PIA. We don't actually need ' the class name at runtime: we will instead emit a reference to System.Object, as a placeholder. Return New SynthesizedAttributeData(ctor, ImmutableArray.Create(New TypedConstant(ctor.Parameters(0).Type, TypedConstantKind.Type, ctor.ContainingAssembly.GetSpecialType(SpecialType.System_Object))), ImmutableArray(Of KeyValuePair(Of String, TypedConstant)).Empty) Case Else Return New SynthesizedAttributeData(ctor, attrData.CommonConstructorArguments, attrData.CommonNamedArguments) End Select End Function Friend Function GetAssemblyGuidString(assembly As AssemblySymbol) As String Debug.Assert(Not IsFrozen) ' After we freeze the set of types, we might add additional assemblies into this map without actual guid values. Dim guidString As String = Nothing If _assemblyGuidMap.TryGetValue(assembly, guidString) Then Return guidString End If Debug.Assert(guidString Is Nothing) assembly.GetGuidString(guidString) Return _assemblyGuidMap.GetOrAdd(assembly, guidString) End Function Protected Overrides Sub OnGetTypesCompleted(types As ImmutableArray(Of EmbeddedType), diagnostics As DiagnosticBag) For Each t In types ' Note, once we reached this point we are no longer interested in guid values, using null. _assemblyGuidMap.TryAdd(t.UnderlyingNamedType.AdaptedNamedTypeSymbol.ContainingAssembly, Nothing) Next For Each a In ModuleBeingBuilt.GetReferencedAssembliesUsedSoFar() ReportIndirectReferencesToLinkedAssemblies(a, diagnostics) Next End Sub Protected Overrides Sub ReportNameCollisionBetweenEmbeddedTypes(typeA As EmbeddedType, typeB As EmbeddedType, diagnostics As DiagnosticBag) Dim underlyingTypeA = typeA.UnderlyingNamedType.AdaptedNamedTypeSymbol Dim underlyingTypeB = typeB.UnderlyingNamedType.AdaptedNamedTypeSymbol ReportDiagnostic(diagnostics, ERRID.ERR_DuplicateLocalTypes3, Nothing, underlyingTypeA, underlyingTypeA.ContainingAssembly, underlyingTypeB.ContainingAssembly) End Sub Protected Overrides Sub ReportNameCollisionWithAlreadyDeclaredType(type As EmbeddedType, diagnostics As DiagnosticBag) Dim underlyingType = type.UnderlyingNamedType.AdaptedNamedTypeSymbol ReportDiagnostic(diagnostics, ERRID.ERR_LocalTypeNameClash2, Nothing, underlyingType, underlyingType.ContainingAssembly) End Sub Friend Overrides Sub ReportIndirectReferencesToLinkedAssemblies(assembly As AssemblySymbol, diagnostics As DiagnosticBag) Debug.Assert(IsFrozen) ' We are emitting an assembly, A, which /references some assembly, B, and ' /links some other assembly, C, so that it can use C's types (by embedding them) ' without having an assemblyref to C itself. ' We can say that A has an indirect reference to each assembly that B references. ' In this function, we are looking for the situation where B has an assemblyref to C, ' thus giving A an indirect reference to C. If so, we will report a warning. For Each [module] In assembly.Modules For Each indirectRef In [module].GetReferencedAssemblySymbols() If Not indirectRef.IsMissing AndAlso indirectRef.IsLinked AndAlso _assemblyGuidMap.ContainsKey(indirectRef) Then ' WRNID_IndirectRefToLinkedAssembly2/WRN_ReferencedAssemblyReferencesLinkedPIA ReportDiagnostic(diagnostics, ERRID.WRN_IndirectRefToLinkedAssembly2, Nothing, indirectRef, assembly) End If Next Next End Sub ''' <summary> ''' Returns true if the type can be embedded. If the type is defined in a linked (/l-ed) ''' assembly, but doesn't meet embeddable type requirements, this function returns ''' False and reports appropriate diagnostics. ''' </summary> Friend Shared Function IsValidEmbeddableType( type As NamedTypeSymbol, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag, Optional typeManagerOpt As EmbeddedTypesManager = Nothing ) As Boolean ' We do not embed SpecialTypes (they must be defined in Core assembly), ' error types and types from assemblies that aren't linked. If type.SpecialType <> SpecialType.None OrElse type.IsErrorType() OrElse Not type.ContainingAssembly.IsLinked Then ' Assuming that we already complained about an error type, ' no additional diagnostics necessary. Return False End If Dim id = ERRID.ERR_None Select Case type.TypeKind Case TypeKind.Interface For Each member As Symbol In type.GetMembersUnordered() If member.Kind <> SymbolKind.NamedType Then If Not member.IsMustOverride Then id = ERRID.ERR_DefaultInterfaceImplementationInNoPIAType ElseIf member.IsNotOverridable Then id = ERRID.ERR_ReAbstractionInNoPIAType End If End If Next If id = ERRID.ERR_None Then GoTo checksForAllEmbedabbleTypes End If Case TypeKind.Structure, TypeKind.Enum, TypeKind.Delegate checksForAllEmbedabbleTypes: If type.IsTupleType Then type = type.TupleUnderlyingType End If If type.ContainingType IsNot Nothing Then ' We do not support nesting for embedded types. ' ERRID.ERR_InvalidInteropType/ERR_NoPIANestedType id = ERRID.ERR_NestedInteropType ElseIf type.IsGenericType Then ' We do not support generic embedded types. ' ERRID.ERR_CannotEmbedInterfaceWithGeneric/ERR_GenericsUsedInNoPIAType id = ERRID.ERR_CannotEmbedInterfaceWithGeneric End If Case Else ' ERRID.ERR_CannotLinkClassWithNoPIA1/ERR_NewCoClassOnLink Debug.Assert(type.TypeKind = TypeKind.Class OrElse type.TypeKind = TypeKind.Module) id = ERRID.ERR_CannotLinkClassWithNoPIA1 End Select If id <> ERRID.ERR_None Then ReportNotEmbeddableSymbol(id, type, syntaxNodeOpt, diagnostics, typeManagerOpt) Return False End If Return True End Function Private Sub VerifyNotFrozen() Debug.Assert(Not IsFrozen) If IsFrozen Then Throw ExceptionUtilities.UnexpectedValue(IsFrozen) End If End Sub Private Shared Sub ReportNotEmbeddableSymbol(id As ERRID, symbol As Symbol, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag, typeManagerOpt As EmbeddedTypesManager) ' Avoid reporting multiple errors for the symbol. If typeManagerOpt Is Nothing OrElse typeManagerOpt._reportedSymbolsMap.TryAdd(symbol.OriginalDefinition, True) Then ReportDiagnostic(diagnostics, id, syntaxNodeOpt, symbol.OriginalDefinition) End If End Sub Friend Shared Sub ReportDiagnostic(diagnostics As DiagnosticBag, id As ERRID, syntaxNodeOpt As SyntaxNode, ParamArray args As Object()) ReportDiagnostic(diagnostics, syntaxNodeOpt, ErrorFactory.ErrorInfo(id, args)) End Sub Private Shared Sub ReportDiagnostic(diagnostics As DiagnosticBag, syntaxNodeOpt As SyntaxNode, info As DiagnosticInfo) diagnostics.Add(New VBDiagnostic(info, If(syntaxNodeOpt Is Nothing, NoLocation.Singleton, syntaxNodeOpt.GetLocation()))) End Sub Friend Function EmbedTypeIfNeedTo(namedType As NamedTypeSymbol, fromImplements As Boolean, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag) As Cci.INamedTypeReference Debug.Assert(namedType.IsDefinition) Debug.Assert(ModuleBeingBuilt.SourceModule.AnyReferencedAssembliesAreLinked) If IsValidEmbeddableType(namedType, syntaxNodeOpt, diagnostics, Me) Then Return EmbedType(namedType, fromImplements, syntaxNodeOpt, diagnostics) End If Return Nothing End Function Private Function EmbedType(namedType As NamedTypeSymbol, fromImplements As Boolean, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag) As EmbeddedType Debug.Assert(namedType.IsDefinition) Dim adapter = namedType.GetCciAdapter() Dim embedded = New EmbeddedType(Me, adapter) Dim cached = EmbeddedTypesMap.GetOrAdd(adapter, embedded) Dim isInterface = (namedType.IsInterface) If isInterface AndAlso fromImplements Then ' Note, we must use 'cached' here because we might drop 'embedded' below. cached.EmbedAllMembersOfImplementedInterface(syntaxNodeOpt, diagnostics) End If If embedded IsNot cached Then Return cached End If ' We do not expect this method to be called on a different thread once GetTypes is called. VerifyNotFrozen() Dim noPiaIndexer = New Cci.TypeReferenceIndexer(New EmitContext(ModuleBeingBuilt, syntaxNodeOpt, diagnostics, metadataOnly:=False, includePrivateMembers:=True)) ' Make sure we embed all types referenced by the type declaration: implemented interfaces, etc. noPiaIndexer.VisitTypeDefinitionNoMembers(embedded) If Not isInterface Then Debug.Assert(namedType.TypeKind = TypeKind.Structure OrElse namedType.TypeKind = TypeKind.Enum OrElse namedType.TypeKind = TypeKind.Delegate) ' For structures, enums and delegates we embed all members. If namedType.TypeKind = TypeKind.Structure OrElse namedType.TypeKind = TypeKind.Enum Then ' TODO: When building debug versions in the IDE, the compiler will insert some extra members ' that support ENC. These make no sense in local types, so we will skip them. We have to ' check for them explicitly or they will trip the member-validity check that follows. End If For Each f In namedType.GetFieldsToEmit() EmbedField(embedded, f.GetCciAdapter(), syntaxNodeOpt, diagnostics) Next For Each m In namedType.GetMethodsToEmit() EmbedMethod(embedded, m.GetCciAdapter(), syntaxNodeOpt, diagnostics) Next ' We also should embed properties and events, but we don't need to do this explicitly here ' because accessors embed them automatically. End If Return embedded End Function Friend Overrides Function EmbedField( type As EmbeddedType, field As FieldSymbolAdapter, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag ) As EmbeddedField Debug.Assert(field.AdaptedFieldSymbol.IsDefinition) Dim embedded = New EmbeddedField(type, field) Dim cached = EmbeddedFieldsMap.GetOrAdd(field, embedded) If embedded IsNot cached Then Return cached End If ' We do not expect this method to be called on a different thread once GetTypes is called. VerifyNotFrozen() ' Embed types referenced by this field declaration. EmbedReferences(embedded, syntaxNodeOpt, diagnostics) Dim containerKind = field.AdaptedFieldSymbol.ContainingType.TypeKind ' Structures may contain only public instance fields. If containerKind = TypeKind.Interface OrElse containerKind = TypeKind.Delegate OrElse (containerKind = TypeKind.Structure AndAlso (field.AdaptedFieldSymbol.IsShared OrElse field.AdaptedFieldSymbol.DeclaredAccessibility <> Accessibility.Public)) Then ' ERRID.ERR_InvalidStructMemberNoPIA1/ERR_InteropStructContainsMethods ReportNotEmbeddableSymbol(ERRID.ERR_InvalidStructMemberNoPIA1, type.UnderlyingNamedType.AdaptedNamedTypeSymbol, syntaxNodeOpt, diagnostics, Me) End If Return embedded End Function Friend Overrides Function EmbedMethod( type As EmbeddedType, method As MethodSymbolAdapter, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag ) As EmbeddedMethod Debug.Assert(method.AdaptedMethodSymbol.IsDefinition) Debug.Assert(Not method.AdaptedMethodSymbol.IsDefaultValueTypeConstructor()) Dim embedded = New EmbeddedMethod(type, method) Dim cached = EmbeddedMethodsMap.GetOrAdd(method, embedded) If embedded IsNot cached Then Return cached End If ' We do not expect this method to be called on a different thread once GetTypes is called. VerifyNotFrozen() ' Embed types referenced by this method declaration. EmbedReferences(embedded, syntaxNodeOpt, diagnostics) Select Case type.UnderlyingNamedType.AdaptedNamedTypeSymbol.TypeKind Case TypeKind.Structure, TypeKind.Enum ' ERRID.ERR_InvalidStructMemberNoPIA1/ERR_InteropStructContainsMethods ReportNotEmbeddableSymbol(ERRID.ERR_InvalidStructMemberNoPIA1, type.UnderlyingNamedType.AdaptedNamedTypeSymbol, syntaxNodeOpt, diagnostics, Me) Case Else If Cci.Extensions.HasBody(embedded) Then ' ERRID.ERR_InteropMethodWithBody1/ERR_InteropMethodWithBody ReportDiagnostic(diagnostics, ERRID.ERR_InteropMethodWithBody1, syntaxNodeOpt, method.AdaptedMethodSymbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)) End If End Select ' If this proc happens to belong to a property/event, we should include the property/event as well. Dim propertyOrEvent = method.AdaptedMethodSymbol.AssociatedSymbol If propertyOrEvent IsNot Nothing Then Select Case propertyOrEvent.Kind Case SymbolKind.Property EmbedProperty(type, DirectCast(propertyOrEvent, PropertySymbol).GetCciAdapter(), syntaxNodeOpt, diagnostics) Case SymbolKind.Event EmbedEvent(type, DirectCast(propertyOrEvent, EventSymbol).GetCciAdapter(), syntaxNodeOpt, diagnostics, isUsedForComAwareEventBinding:=False) Case Else Throw ExceptionUtilities.UnexpectedValue(propertyOrEvent.Kind) End Select End If Return embedded End Function Friend Overrides Function EmbedProperty( type As EmbeddedType, [property] As PropertySymbolAdapter, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag ) As EmbeddedProperty Debug.Assert([property].AdaptedPropertySymbol.IsDefinition) ' Make sure accessors are embedded. Dim getMethod = [property].AdaptedPropertySymbol.GetMethod Dim setMethod = [property].AdaptedPropertySymbol.SetMethod Dim embeddedGet = If(getMethod IsNot Nothing, EmbedMethod(type, getMethod.GetCciAdapter(), syntaxNodeOpt, diagnostics), Nothing) Dim embeddedSet = If(setMethod IsNot Nothing, EmbedMethod(type, setMethod.GetCciAdapter(), syntaxNodeOpt, diagnostics), Nothing) Dim embedded = New EmbeddedProperty([property], embeddedGet, embeddedSet) Dim cached = EmbeddedPropertiesMap.GetOrAdd([property], embedded) If embedded IsNot cached Then Return cached End If ' We do not expect this method to be called on a different thread once GetTypes is called. VerifyNotFrozen() ' Embed types referenced by this property declaration. ' This should also embed accessors. EmbedReferences(embedded, syntaxNodeOpt, diagnostics) Return embedded End Function Friend Overrides Function EmbedEvent( type As EmbeddedType, [event] As EventSymbolAdapter, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag, isUsedForComAwareEventBinding As Boolean ) As EmbeddedEvent Debug.Assert([event].AdaptedEventSymbol.IsDefinition) ' Make sure accessors are embedded. Dim addMethod = [event].AdaptedEventSymbol.AddMethod Dim removeMethod = [event].AdaptedEventSymbol.RemoveMethod Dim callMethod = [event].AdaptedEventSymbol.RaiseMethod Dim embeddedAdd = If(addMethod IsNot Nothing, EmbedMethod(type, addMethod.GetCciAdapter(), syntaxNodeOpt, diagnostics), Nothing) Dim embeddedRemove = If(removeMethod IsNot Nothing, EmbedMethod(type, removeMethod.GetCciAdapter(), syntaxNodeOpt, diagnostics), Nothing) Dim embeddedCall = If(callMethod IsNot Nothing, EmbedMethod(type, callMethod.GetCciAdapter(), syntaxNodeOpt, diagnostics), Nothing) Dim embedded = New EmbeddedEvent([event], embeddedAdd, embeddedRemove, embeddedCall) Dim cached = EmbeddedEventsMap.GetOrAdd([event], embedded) If embedded IsNot cached Then If isUsedForComAwareEventBinding Then cached.EmbedCorrespondingComEventInterfaceMethod(syntaxNodeOpt, diagnostics, isUsedForComAwareEventBinding) End If Return cached End If ' We do not expect this method to be called on a different thread once GetTypes is called. VerifyNotFrozen() ' Embed types referenced by this event declaration. ' This should also embed accessors. EmbedReferences(embedded, syntaxNodeOpt, diagnostics) embedded.EmbedCorrespondingComEventInterfaceMethod(syntaxNodeOpt, diagnostics, isUsedForComAwareEventBinding) Return embedded End Function Protected Overrides Function GetEmbeddedTypeForMember(member As SymbolAdapter, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag) As EmbeddedType Debug.Assert(member.AdaptedSymbol.IsDefinition) Debug.Assert(ModuleBeingBuilt.SourceModule.AnyReferencedAssembliesAreLinked) Dim namedType = member.AdaptedSymbol.ContainingType If IsValidEmbeddableType(namedType, syntaxNodeOpt, diagnostics, Me) Then ' It is possible that we have found a reference to a member before ' encountering a reference to its container; make sure the container gets included. Return EmbedType(namedType, fromImplements:=False, syntaxNodeOpt:=syntaxNodeOpt, diagnostics:=diagnostics) End If Return Nothing End Function Friend Shared Function EmbedParameters(containingPropertyOrMethod As CommonEmbeddedMember, underlyingParameters As ImmutableArray(Of ParameterSymbol)) As ImmutableArray(Of EmbeddedParameter) Return underlyingParameters.SelectAsArray(Function(parameter, container) New EmbeddedParameter(container, parameter.GetCciAdapter()), containingPropertyOrMethod) End Function Protected Overrides Function CreateCompilerGeneratedAttribute() As VisualBasicAttributeData Debug.Assert(WellKnownMembers.IsSynthesizedAttributeOptional(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)) Dim compilation = ModuleBeingBuilt.Compilation Return compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor) End Function End Class End Namespace
-1
dotnet/roslyn
55,354
Add IFieldSymbol.FixedSize API
Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
333fred
2021-08-02T22:15:12Z
2021-08-03T21:43:37Z
76bdda7fe502a74f91aee0feb2fe251039be4e82
a81b07d0d5a6b5c5430443fc843e4a730399c946
Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
./src/EditorFeatures/Core/Implementation/TextStructureNavigation/AbstractTextStructureNavigatorProvider.TextStructureNavigator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.TextStructureNavigation { internal partial class AbstractTextStructureNavigatorProvider { private class TextStructureNavigator : ITextStructureNavigator { private readonly ITextBuffer _subjectBuffer; private readonly ITextStructureNavigator _naturalLanguageNavigator; private readonly AbstractTextStructureNavigatorProvider _provider; private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; internal TextStructureNavigator( ITextBuffer subjectBuffer, ITextStructureNavigator naturalLanguageNavigator, AbstractTextStructureNavigatorProvider provider, IUIThreadOperationExecutor uIThreadOperationExecutor) { Contract.ThrowIfNull(subjectBuffer); Contract.ThrowIfNull(naturalLanguageNavigator); Contract.ThrowIfNull(provider); _subjectBuffer = subjectBuffer; _naturalLanguageNavigator = naturalLanguageNavigator; _provider = provider; _uiThreadOperationExecutor = uIThreadOperationExecutor; } public IContentType ContentType => _subjectBuffer.ContentType; public TextExtent GetExtentOfWord(SnapshotPoint currentPosition) { using (Logger.LogBlock(FunctionId.TextStructureNavigator_GetExtentOfWord, CancellationToken.None)) { var result = default(TextExtent); _uiThreadOperationExecutor.Execute( title: EditorFeaturesResources.Text_Navigation, defaultDescription: EditorFeaturesResources.Finding_word_extent, allowCancellation: true, showProgress: false, action: context => { result = GetExtentOfWordWorker(currentPosition, context.UserCancellationToken); }); return result; } } private TextExtent GetExtentOfWordWorker(SnapshotPoint position, CancellationToken cancellationToken) { var textLength = position.Snapshot.Length; if (textLength == 0) { return _naturalLanguageNavigator.GetExtentOfWord(position); } // If at the end of the file, go back one character so stuff works if (position == textLength && position > 0) { position -= 1; } // If we're at the EOL position, return the line break's extent var line = position.Snapshot.GetLineFromPosition(position); if (position >= line.End && position < line.EndIncludingLineBreak) { return new TextExtent(new SnapshotSpan(line.End, line.EndIncludingLineBreak - line.End), isSignificant: false); } var document = GetDocument(position); if (document != null) { var root = document.GetSyntaxRootSynchronously(cancellationToken); var trivia = root.FindTrivia(position, findInsideTrivia: true); if (trivia != default) { if (trivia.Span.Start == position && _provider.ShouldSelectEntireTriviaFromStart(trivia)) { // We want to select the entire comment return new TextExtent(trivia.Span.ToSnapshotSpan(position.Snapshot), isSignificant: true); } } var token = root.FindToken(position, findInsideTrivia: true); // If end of file, go back a token if (token.Span.Length == 0 && token.Span.Start == textLength) { token = token.GetPreviousToken(); } if (token.Span.Length > 0 && token.Span.Contains(position) && !_provider.IsWithinNaturalLanguage(token, position)) { // Cursor position is in our domain - handle it. return _provider.GetExtentOfWordFromToken(token, position); } } // Fall back to natural language navigator do its thing. return _naturalLanguageNavigator.GetExtentOfWord(position); } public SnapshotSpan GetSpanOfEnclosing(SnapshotSpan activeSpan) { using (Logger.LogBlock(FunctionId.TextStructureNavigator_GetSpanOfEnclosing, CancellationToken.None)) { var span = default(SnapshotSpan); var result = _uiThreadOperationExecutor.Execute( title: EditorFeaturesResources.Text_Navigation, defaultDescription: EditorFeaturesResources.Finding_enclosing_span, allowCancellation: true, showProgress: false, action: context => { span = GetSpanOfEnclosingWorker(activeSpan, context.UserCancellationToken); }); return result == UIThreadOperationStatus.Completed ? span : activeSpan; } } private static SnapshotSpan GetSpanOfEnclosingWorker(SnapshotSpan activeSpan, CancellationToken cancellationToken) { // Find node that covers the entire span. var node = FindLeafNode(activeSpan, cancellationToken); if (node != null && activeSpan.Length == node.Value.Span.Length) { // Go one level up so the span widens. node = GetEnclosingNode(node.Value); } return node == null ? activeSpan : node.Value.Span.ToSnapshotSpan(activeSpan.Snapshot); } public SnapshotSpan GetSpanOfFirstChild(SnapshotSpan activeSpan) { using (Logger.LogBlock(FunctionId.TextStructureNavigator_GetSpanOfFirstChild, CancellationToken.None)) { var span = default(SnapshotSpan); var result = _uiThreadOperationExecutor.Execute( title: EditorFeaturesResources.Text_Navigation, defaultDescription: EditorFeaturesResources.Finding_enclosing_span, allowCancellation: true, showProgress: false, action: context => { span = GetSpanOfFirstChildWorker(activeSpan, context.UserCancellationToken); }); return result == UIThreadOperationStatus.Completed ? span : activeSpan; } } private static SnapshotSpan GetSpanOfFirstChildWorker(SnapshotSpan activeSpan, CancellationToken cancellationToken) { // Find node that covers the entire span. var node = FindLeafNode(activeSpan, cancellationToken); if (node != null) { // Take first child if possible, otherwise default to node itself. var firstChild = node.Value.ChildNodesAndTokens().FirstOrNull(); if (firstChild.HasValue) { node = firstChild.Value; } } return node == null ? activeSpan : node.Value.Span.ToSnapshotSpan(activeSpan.Snapshot); } public SnapshotSpan GetSpanOfNextSibling(SnapshotSpan activeSpan) { using (Logger.LogBlock(FunctionId.TextStructureNavigator_GetSpanOfNextSibling, CancellationToken.None)) { var span = default(SnapshotSpan); var result = _uiThreadOperationExecutor.Execute( title: EditorFeaturesResources.Text_Navigation, defaultDescription: EditorFeaturesResources.Finding_span_of_next_sibling, allowCancellation: true, showProgress: false, action: context => { span = GetSpanOfNextSiblingWorker(activeSpan, context.UserCancellationToken); }); return result == UIThreadOperationStatus.Completed ? span : activeSpan; } } private static SnapshotSpan GetSpanOfNextSiblingWorker(SnapshotSpan activeSpan, CancellationToken cancellationToken) { // Find node that covers the entire span. var node = FindLeafNode(activeSpan, cancellationToken); if (node != null) { // Get ancestor with a wider span. var parent = GetEnclosingNode(node.Value); if (parent != null) { // Find node immediately after the current in the children collection. var nodeOrToken = parent.Value .ChildNodesAndTokens() .SkipWhile(child => child != node) .Skip(1) .FirstOrNull(); if (nodeOrToken.HasValue) { node = nodeOrToken.Value; } else { // If this is the last node, move to the parent so that the user can continue // navigation at the higher level. node = parent.Value; } } } return node == null ? activeSpan : node.Value.Span.ToSnapshotSpan(activeSpan.Snapshot); } public SnapshotSpan GetSpanOfPreviousSibling(SnapshotSpan activeSpan) { using (Logger.LogBlock(FunctionId.TextStructureNavigator_GetSpanOfPreviousSibling, CancellationToken.None)) { var span = default(SnapshotSpan); var result = _uiThreadOperationExecutor.Execute( title: EditorFeaturesResources.Text_Navigation, defaultDescription: EditorFeaturesResources.Finding_span_of_previous_sibling, allowCancellation: true, showProgress: false, action: context => { span = GetSpanOfPreviousSiblingWorker(activeSpan, context.UserCancellationToken); }); return result == UIThreadOperationStatus.Completed ? span : activeSpan; } } private static SnapshotSpan GetSpanOfPreviousSiblingWorker(SnapshotSpan activeSpan, CancellationToken cancellationToken) { // Find node that covers the entire span. var node = FindLeafNode(activeSpan, cancellationToken); if (node != null) { // Get ancestor with a wider span. var parent = GetEnclosingNode(node.Value); if (parent != null) { // Find node immediately before the current in the children collection. var nodeOrToken = parent.Value .ChildNodesAndTokens() .Reverse() .SkipWhile(child => child != node) .Skip(1) .FirstOrNull(); if (nodeOrToken.HasValue) { node = nodeOrToken.Value; } else { // If this is the first node, move to the parent so that the user can continue // navigation at the higher level. node = parent.Value; } } } return node == null ? activeSpan : node.Value.Span.ToSnapshotSpan(activeSpan.Snapshot); } private static Document GetDocument(SnapshotPoint point) { var textLength = point.Snapshot.Length; if (textLength == 0) { return null; } return point.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); } /// <summary> /// Finds deepest node that covers given <see cref="SnapshotSpan"/>. /// </summary> private static SyntaxNodeOrToken? FindLeafNode(SnapshotSpan span, CancellationToken cancellationToken) { if (!TryFindLeafToken(span.Start, out var token, cancellationToken)) { return null; } SyntaxNodeOrToken? node = token; while (node != null && (span.End.Position > node.Value.Span.End)) { node = GetEnclosingNode(node.Value); } return node; } /// <summary> /// Given position in a text buffer returns the leaf syntax node it belongs to. /// </summary> private static bool TryFindLeafToken(SnapshotPoint point, out SyntaxToken token, CancellationToken cancellationToken) { var syntaxTree = GetDocument(point).GetSyntaxTreeSynchronously(cancellationToken); if (syntaxTree != null) { token = syntaxTree.GetRoot(cancellationToken).FindToken(point, true); return true; } token = default; return false; } /// <summary> /// Returns first ancestor of the node which has a span wider than node's span. /// If none exist, returns the last available ancestor. /// </summary> private static SyntaxNodeOrToken SkipSameSpanParents(SyntaxNodeOrToken node) { while (node.Parent != null && node.Parent.Span == node.Span) { node = node.Parent; } return node; } /// <summary> /// Finds node enclosing current from navigation point of view (that is, some immediate ancestors /// may be skipped during this process). /// </summary> private static SyntaxNodeOrToken? GetEnclosingNode(SyntaxNodeOrToken node) { var parent = SkipSameSpanParents(node).Parent; if (parent != null) { return parent; } else { return null; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.TextStructureNavigation { internal partial class AbstractTextStructureNavigatorProvider { private class TextStructureNavigator : ITextStructureNavigator { private readonly ITextBuffer _subjectBuffer; private readonly ITextStructureNavigator _naturalLanguageNavigator; private readonly AbstractTextStructureNavigatorProvider _provider; private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; internal TextStructureNavigator( ITextBuffer subjectBuffer, ITextStructureNavigator naturalLanguageNavigator, AbstractTextStructureNavigatorProvider provider, IUIThreadOperationExecutor uIThreadOperationExecutor) { Contract.ThrowIfNull(subjectBuffer); Contract.ThrowIfNull(naturalLanguageNavigator); Contract.ThrowIfNull(provider); _subjectBuffer = subjectBuffer; _naturalLanguageNavigator = naturalLanguageNavigator; _provider = provider; _uiThreadOperationExecutor = uIThreadOperationExecutor; } public IContentType ContentType => _subjectBuffer.ContentType; public TextExtent GetExtentOfWord(SnapshotPoint currentPosition) { using (Logger.LogBlock(FunctionId.TextStructureNavigator_GetExtentOfWord, CancellationToken.None)) { var result = default(TextExtent); _uiThreadOperationExecutor.Execute( title: EditorFeaturesResources.Text_Navigation, defaultDescription: EditorFeaturesResources.Finding_word_extent, allowCancellation: true, showProgress: false, action: context => { result = GetExtentOfWordWorker(currentPosition, context.UserCancellationToken); }); return result; } } private TextExtent GetExtentOfWordWorker(SnapshotPoint position, CancellationToken cancellationToken) { var textLength = position.Snapshot.Length; if (textLength == 0) { return _naturalLanguageNavigator.GetExtentOfWord(position); } // If at the end of the file, go back one character so stuff works if (position == textLength && position > 0) { position -= 1; } // If we're at the EOL position, return the line break's extent var line = position.Snapshot.GetLineFromPosition(position); if (position >= line.End && position < line.EndIncludingLineBreak) { return new TextExtent(new SnapshotSpan(line.End, line.EndIncludingLineBreak - line.End), isSignificant: false); } var document = GetDocument(position); if (document != null) { var root = document.GetSyntaxRootSynchronously(cancellationToken); var trivia = root.FindTrivia(position, findInsideTrivia: true); if (trivia != default) { if (trivia.Span.Start == position && _provider.ShouldSelectEntireTriviaFromStart(trivia)) { // We want to select the entire comment return new TextExtent(trivia.Span.ToSnapshotSpan(position.Snapshot), isSignificant: true); } } var token = root.FindToken(position, findInsideTrivia: true); // If end of file, go back a token if (token.Span.Length == 0 && token.Span.Start == textLength) { token = token.GetPreviousToken(); } if (token.Span.Length > 0 && token.Span.Contains(position) && !_provider.IsWithinNaturalLanguage(token, position)) { // Cursor position is in our domain - handle it. return _provider.GetExtentOfWordFromToken(token, position); } } // Fall back to natural language navigator do its thing. return _naturalLanguageNavigator.GetExtentOfWord(position); } public SnapshotSpan GetSpanOfEnclosing(SnapshotSpan activeSpan) { using (Logger.LogBlock(FunctionId.TextStructureNavigator_GetSpanOfEnclosing, CancellationToken.None)) { var span = default(SnapshotSpan); var result = _uiThreadOperationExecutor.Execute( title: EditorFeaturesResources.Text_Navigation, defaultDescription: EditorFeaturesResources.Finding_enclosing_span, allowCancellation: true, showProgress: false, action: context => { span = GetSpanOfEnclosingWorker(activeSpan, context.UserCancellationToken); }); return result == UIThreadOperationStatus.Completed ? span : activeSpan; } } private static SnapshotSpan GetSpanOfEnclosingWorker(SnapshotSpan activeSpan, CancellationToken cancellationToken) { // Find node that covers the entire span. var node = FindLeafNode(activeSpan, cancellationToken); if (node != null && activeSpan.Length == node.Value.Span.Length) { // Go one level up so the span widens. node = GetEnclosingNode(node.Value); } return node == null ? activeSpan : node.Value.Span.ToSnapshotSpan(activeSpan.Snapshot); } public SnapshotSpan GetSpanOfFirstChild(SnapshotSpan activeSpan) { using (Logger.LogBlock(FunctionId.TextStructureNavigator_GetSpanOfFirstChild, CancellationToken.None)) { var span = default(SnapshotSpan); var result = _uiThreadOperationExecutor.Execute( title: EditorFeaturesResources.Text_Navigation, defaultDescription: EditorFeaturesResources.Finding_enclosing_span, allowCancellation: true, showProgress: false, action: context => { span = GetSpanOfFirstChildWorker(activeSpan, context.UserCancellationToken); }); return result == UIThreadOperationStatus.Completed ? span : activeSpan; } } private static SnapshotSpan GetSpanOfFirstChildWorker(SnapshotSpan activeSpan, CancellationToken cancellationToken) { // Find node that covers the entire span. var node = FindLeafNode(activeSpan, cancellationToken); if (node != null) { // Take first child if possible, otherwise default to node itself. var firstChild = node.Value.ChildNodesAndTokens().FirstOrNull(); if (firstChild.HasValue) { node = firstChild.Value; } } return node == null ? activeSpan : node.Value.Span.ToSnapshotSpan(activeSpan.Snapshot); } public SnapshotSpan GetSpanOfNextSibling(SnapshotSpan activeSpan) { using (Logger.LogBlock(FunctionId.TextStructureNavigator_GetSpanOfNextSibling, CancellationToken.None)) { var span = default(SnapshotSpan); var result = _uiThreadOperationExecutor.Execute( title: EditorFeaturesResources.Text_Navigation, defaultDescription: EditorFeaturesResources.Finding_span_of_next_sibling, allowCancellation: true, showProgress: false, action: context => { span = GetSpanOfNextSiblingWorker(activeSpan, context.UserCancellationToken); }); return result == UIThreadOperationStatus.Completed ? span : activeSpan; } } private static SnapshotSpan GetSpanOfNextSiblingWorker(SnapshotSpan activeSpan, CancellationToken cancellationToken) { // Find node that covers the entire span. var node = FindLeafNode(activeSpan, cancellationToken); if (node != null) { // Get ancestor with a wider span. var parent = GetEnclosingNode(node.Value); if (parent != null) { // Find node immediately after the current in the children collection. var nodeOrToken = parent.Value .ChildNodesAndTokens() .SkipWhile(child => child != node) .Skip(1) .FirstOrNull(); if (nodeOrToken.HasValue) { node = nodeOrToken.Value; } else { // If this is the last node, move to the parent so that the user can continue // navigation at the higher level. node = parent.Value; } } } return node == null ? activeSpan : node.Value.Span.ToSnapshotSpan(activeSpan.Snapshot); } public SnapshotSpan GetSpanOfPreviousSibling(SnapshotSpan activeSpan) { using (Logger.LogBlock(FunctionId.TextStructureNavigator_GetSpanOfPreviousSibling, CancellationToken.None)) { var span = default(SnapshotSpan); var result = _uiThreadOperationExecutor.Execute( title: EditorFeaturesResources.Text_Navigation, defaultDescription: EditorFeaturesResources.Finding_span_of_previous_sibling, allowCancellation: true, showProgress: false, action: context => { span = GetSpanOfPreviousSiblingWorker(activeSpan, context.UserCancellationToken); }); return result == UIThreadOperationStatus.Completed ? span : activeSpan; } } private static SnapshotSpan GetSpanOfPreviousSiblingWorker(SnapshotSpan activeSpan, CancellationToken cancellationToken) { // Find node that covers the entire span. var node = FindLeafNode(activeSpan, cancellationToken); if (node != null) { // Get ancestor with a wider span. var parent = GetEnclosingNode(node.Value); if (parent != null) { // Find node immediately before the current in the children collection. var nodeOrToken = parent.Value .ChildNodesAndTokens() .Reverse() .SkipWhile(child => child != node) .Skip(1) .FirstOrNull(); if (nodeOrToken.HasValue) { node = nodeOrToken.Value; } else { // If this is the first node, move to the parent so that the user can continue // navigation at the higher level. node = parent.Value; } } } return node == null ? activeSpan : node.Value.Span.ToSnapshotSpan(activeSpan.Snapshot); } private static Document GetDocument(SnapshotPoint point) { var textLength = point.Snapshot.Length; if (textLength == 0) { return null; } return point.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); } /// <summary> /// Finds deepest node that covers given <see cref="SnapshotSpan"/>. /// </summary> private static SyntaxNodeOrToken? FindLeafNode(SnapshotSpan span, CancellationToken cancellationToken) { if (!TryFindLeafToken(span.Start, out var token, cancellationToken)) { return null; } SyntaxNodeOrToken? node = token; while (node != null && (span.End.Position > node.Value.Span.End)) { node = GetEnclosingNode(node.Value); } return node; } /// <summary> /// Given position in a text buffer returns the leaf syntax node it belongs to. /// </summary> private static bool TryFindLeafToken(SnapshotPoint point, out SyntaxToken token, CancellationToken cancellationToken) { var syntaxTree = GetDocument(point).GetSyntaxTreeSynchronously(cancellationToken); if (syntaxTree != null) { token = syntaxTree.GetRoot(cancellationToken).FindToken(point, true); return true; } token = default; return false; } /// <summary> /// Returns first ancestor of the node which has a span wider than node's span. /// If none exist, returns the last available ancestor. /// </summary> private static SyntaxNodeOrToken SkipSameSpanParents(SyntaxNodeOrToken node) { while (node.Parent != null && node.Parent.Span == node.Span) { node = node.Parent; } return node; } /// <summary> /// Finds node enclosing current from navigation point of view (that is, some immediate ancestors /// may be skipped during this process). /// </summary> private static SyntaxNodeOrToken? GetEnclosingNode(SyntaxNodeOrToken node) { var parent = SkipSameSpanParents(node).Parent; if (parent != null) { return parent; } else { return null; } } } } }
-1
dotnet/roslyn
55,354
Add IFieldSymbol.FixedSize API
Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
333fred
2021-08-02T22:15:12Z
2021-08-03T21:43:37Z
76bdda7fe502a74f91aee0feb2fe251039be4e82
a81b07d0d5a6b5c5430443fc843e4a730399c946
Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
./src/Analyzers/VisualBasic/CodeFixes/RemoveUnusedMembers/VisualBasicRemoveUnusedMembersCodeFixProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.RemoveUnusedMembers Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnusedMembers <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.RemoveUnusedMembers), [Shared]> Friend Class VisualBasicRemoveUnusedMembersCodeFixProvider Inherits AbstractRemoveUnusedMembersCodeFixProvider(Of FieldDeclarationSyntax) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub ''' <summary> ''' This method adjusts the <paramref name="declarators"/> to remove based on whether or not all variable declarators ''' within a field declaration should be removed, ''' i.e. if all the fields declared within a field declaration are unused, ''' we can remove the entire field declaration instead of individual variable declarators. ''' </summary> Protected Overrides Sub AdjustAndAddAppropriateDeclaratorsToRemove(fieldDeclarators As HashSet(Of FieldDeclarationSyntax), declarators As HashSet(Of SyntaxNode)) For Each variableDeclarator In fieldDeclarators.SelectMany(Function(f) f.Declarators) AdjustAndAddAppropriateDeclaratorsToRemove( parentDeclaration:=variableDeclarator, childDeclarators:=variableDeclarator.Names, declarators:=declarators) Next For Each fieldDeclarator In fieldDeclarators AdjustAndAddAppropriateDeclaratorsToRemove( parentDeclaration:=fieldDeclarator, childDeclarators:=fieldDeclarator.Declarators, declarators:=declarators) Next End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.RemoveUnusedMembers Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnusedMembers <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.RemoveUnusedMembers), [Shared]> Friend Class VisualBasicRemoveUnusedMembersCodeFixProvider Inherits AbstractRemoveUnusedMembersCodeFixProvider(Of FieldDeclarationSyntax) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub ''' <summary> ''' This method adjusts the <paramref name="declarators"/> to remove based on whether or not all variable declarators ''' within a field declaration should be removed, ''' i.e. if all the fields declared within a field declaration are unused, ''' we can remove the entire field declaration instead of individual variable declarators. ''' </summary> Protected Overrides Sub AdjustAndAddAppropriateDeclaratorsToRemove(fieldDeclarators As HashSet(Of FieldDeclarationSyntax), declarators As HashSet(Of SyntaxNode)) For Each variableDeclarator In fieldDeclarators.SelectMany(Function(f) f.Declarators) AdjustAndAddAppropriateDeclaratorsToRemove( parentDeclaration:=variableDeclarator, childDeclarators:=variableDeclarator.Names, declarators:=declarators) Next For Each fieldDeclarator In fieldDeclarators AdjustAndAddAppropriateDeclaratorsToRemove( parentDeclaration:=fieldDeclarator, childDeclarators:=fieldDeclarator.Declarators, declarators:=declarators) Next End Sub End Class End Namespace
-1
dotnet/roslyn
55,354
Add IFieldSymbol.FixedSize API
Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
333fred
2021-08-02T22:15:12Z
2021-08-03T21:43:37Z
76bdda7fe502a74f91aee0feb2fe251039be4e82
a81b07d0d5a6b5c5430443fc843e4a730399c946
Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
./src/Features/Core/Portable/Diagnostics/EngineV2/DiagnosticIncrementalAnalyzer.ActiveFileState.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Diagnostics.EngineV2 { internal partial class DiagnosticIncrementalAnalyzer { /// <summary> /// state that is responsible to hold onto local diagnostics data regarding active/opened files (depends on host) /// in memory. /// </summary> private sealed class ActiveFileState { // file state this is for public readonly DocumentId DocumentId; // analysis data for each kind private DocumentAnalysisData _syntax = DocumentAnalysisData.Empty; private DocumentAnalysisData _semantic = DocumentAnalysisData.Empty; public ActiveFileState(DocumentId documentId) => DocumentId = documentId; public bool IsEmpty => _syntax.Items.IsEmpty && _semantic.Items.IsEmpty; public void ResetVersion() { // reset version of cached data so that we can recalculate new data (ex, OnDocumentReset) _syntax = new DocumentAnalysisData(VersionStamp.Default, _syntax.Items); _semantic = new DocumentAnalysisData(VersionStamp.Default, _semantic.Items); } public DocumentAnalysisData GetAnalysisData(AnalysisKind kind) => kind switch { AnalysisKind.Syntax => _syntax, AnalysisKind.Semantic => _semantic, _ => throw ExceptionUtilities.UnexpectedValue(kind) }; public void Save(AnalysisKind kind, DocumentAnalysisData data) { Contract.ThrowIfFalse(data.OldItems.IsDefault); switch (kind) { case AnalysisKind.Syntax: _syntax = data; return; case AnalysisKind.Semantic: _semantic = data; return; default: throw ExceptionUtilities.UnexpectedValue(kind); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2 { internal partial class DiagnosticIncrementalAnalyzer { /// <summary> /// state that is responsible to hold onto local diagnostics data regarding active/opened files (depends on host) /// in memory. /// </summary> private sealed class ActiveFileState { // file state this is for public readonly DocumentId DocumentId; // analysis data for each kind private DocumentAnalysisData _syntax = DocumentAnalysisData.Empty; private DocumentAnalysisData _semantic = DocumentAnalysisData.Empty; public ActiveFileState(DocumentId documentId) => DocumentId = documentId; public bool IsEmpty => _syntax.Items.IsEmpty && _semantic.Items.IsEmpty; public void ResetVersion() { // reset version of cached data so that we can recalculate new data (ex, OnDocumentReset) _syntax = new DocumentAnalysisData(VersionStamp.Default, _syntax.Items); _semantic = new DocumentAnalysisData(VersionStamp.Default, _semantic.Items); } public DocumentAnalysisData GetAnalysisData(AnalysisKind kind) => kind switch { AnalysisKind.Syntax => _syntax, AnalysisKind.Semantic => _semantic, _ => throw ExceptionUtilities.UnexpectedValue(kind) }; public void Save(AnalysisKind kind, DocumentAnalysisData data) { Contract.ThrowIfFalse(data.OldItems.IsDefault); switch (kind) { case AnalysisKind.Syntax: _syntax = data; return; case AnalysisKind.Semantic: _semantic = data; return; default: throw ExceptionUtilities.UnexpectedValue(kind); } } } } }
-1
dotnet/roslyn
55,354
Add IFieldSymbol.FixedSize API
Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
333fred
2021-08-02T22:15:12Z
2021-08-03T21:43:37Z
76bdda7fe502a74f91aee0feb2fe251039be4e82
a81b07d0d5a6b5c5430443fc843e4a730399c946
Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
./src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PEPropertyOrEventHelpers.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Helper methods that exist to share code between properties and events. ''' </summary> Friend Class PEPropertyOrEventHelpers Friend Shared Function GetPropertiesForExplicitlyImplementedAccessor(accessor As MethodSymbol) As ISet(Of PropertySymbol) Return GetSymbolsForExplicitlyImplementedAccessor(Of PropertySymbol)(accessor) End Function Friend Shared Function GetEventsForExplicitlyImplementedAccessor(accessor As MethodSymbol) As ISet(Of EventSymbol) Return GetSymbolsForExplicitlyImplementedAccessor(Of EventSymbol)(accessor) End Function ' CONSIDER: the 99% case is a very small set. A list might be more efficient in such cases. Private Shared Function GetSymbolsForExplicitlyImplementedAccessor(Of T As Symbol)(accessor As MethodSymbol) As ISet(Of T) If accessor Is Nothing Then Return SpecializedCollections.EmptySet(Of T)() End If Dim implementedAccessors As ImmutableArray(Of MethodSymbol) = accessor.ExplicitInterfaceImplementations If implementedAccessors.Length = 0 Then Return SpecializedCollections.EmptySet(Of T)() End If Dim symbolsForExplicitlyImplementedAccessors = New HashSet(Of T)() For Each implementedAccessor In implementedAccessors Dim associatedProperty = TryCast(implementedAccessor.AssociatedSymbol, T) If associatedProperty IsNot Nothing Then symbolsForExplicitlyImplementedAccessors.Add(associatedProperty) End If Next Return symbolsForExplicitlyImplementedAccessors End Function ' Properties and events from metadata do not have explicit accessibility. Instead, ' the accessibility reported for the PEPropertySymbol or PEEventSymbol is the most ' restrictive level that is no more restrictive than the getter/adder and setter/remover. Friend Shared Function GetDeclaredAccessibilityFromAccessors(accessor1 As MethodSymbol, accessor2 As MethodSymbol) As Accessibility If accessor1 Is Nothing Then Return If((accessor2 Is Nothing), Accessibility.NotApplicable, accessor2.DeclaredAccessibility) ElseIf accessor2 Is Nothing Then Return accessor1.DeclaredAccessibility End If Dim accessibility1 = accessor1.DeclaredAccessibility Dim accessibility2 = accessor2.DeclaredAccessibility Dim minAccessibility = If((accessibility1 > accessibility2), accessibility2, accessibility1) Dim maxAccessibility = If((accessibility1 > accessibility2), accessibility1, accessibility2) Return If(((minAccessibility = Accessibility.[Protected]) AndAlso (maxAccessibility = Accessibility.Friend)), Accessibility.ProtectedOrFriend, maxAccessibility) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Helper methods that exist to share code between properties and events. ''' </summary> Friend Class PEPropertyOrEventHelpers Friend Shared Function GetPropertiesForExplicitlyImplementedAccessor(accessor As MethodSymbol) As ISet(Of PropertySymbol) Return GetSymbolsForExplicitlyImplementedAccessor(Of PropertySymbol)(accessor) End Function Friend Shared Function GetEventsForExplicitlyImplementedAccessor(accessor As MethodSymbol) As ISet(Of EventSymbol) Return GetSymbolsForExplicitlyImplementedAccessor(Of EventSymbol)(accessor) End Function ' CONSIDER: the 99% case is a very small set. A list might be more efficient in such cases. Private Shared Function GetSymbolsForExplicitlyImplementedAccessor(Of T As Symbol)(accessor As MethodSymbol) As ISet(Of T) If accessor Is Nothing Then Return SpecializedCollections.EmptySet(Of T)() End If Dim implementedAccessors As ImmutableArray(Of MethodSymbol) = accessor.ExplicitInterfaceImplementations If implementedAccessors.Length = 0 Then Return SpecializedCollections.EmptySet(Of T)() End If Dim symbolsForExplicitlyImplementedAccessors = New HashSet(Of T)() For Each implementedAccessor In implementedAccessors Dim associatedProperty = TryCast(implementedAccessor.AssociatedSymbol, T) If associatedProperty IsNot Nothing Then symbolsForExplicitlyImplementedAccessors.Add(associatedProperty) End If Next Return symbolsForExplicitlyImplementedAccessors End Function ' Properties and events from metadata do not have explicit accessibility. Instead, ' the accessibility reported for the PEPropertySymbol or PEEventSymbol is the most ' restrictive level that is no more restrictive than the getter/adder and setter/remover. Friend Shared Function GetDeclaredAccessibilityFromAccessors(accessor1 As MethodSymbol, accessor2 As MethodSymbol) As Accessibility If accessor1 Is Nothing Then Return If((accessor2 Is Nothing), Accessibility.NotApplicable, accessor2.DeclaredAccessibility) ElseIf accessor2 Is Nothing Then Return accessor1.DeclaredAccessibility End If Dim accessibility1 = accessor1.DeclaredAccessibility Dim accessibility2 = accessor2.DeclaredAccessibility Dim minAccessibility = If((accessibility1 > accessibility2), accessibility2, accessibility1) Dim maxAccessibility = If((accessibility1 > accessibility2), accessibility1, accessibility2) Return If(((minAccessibility = Accessibility.[Protected]) AndAlso (maxAccessibility = Accessibility.Friend)), Accessibility.ProtectedOrFriend, maxAccessibility) End Function End Class End Namespace
-1
dotnet/roslyn
55,354
Add IFieldSymbol.FixedSize API
Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
333fred
2021-08-02T22:15:12Z
2021-08-03T21:43:37Z
76bdda7fe502a74f91aee0feb2fe251039be4e82
a81b07d0d5a6b5c5430443fc843e4a730399c946
Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/MefLanguageServices.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; [assembly: DebuggerTypeProxy(typeof(MefLanguageServices.LazyServiceMetadataDebuggerProxy), Target = typeof(ImmutableArray<Lazy<ILanguageService, WorkspaceServiceMetadata>>))] namespace Microsoft.CodeAnalysis.Host.Mef { internal sealed class MefLanguageServices : HostLanguageServices { private readonly MefWorkspaceServices _workspaceServices; private readonly string _language; private readonly ImmutableArray<Lazy<ILanguageService, LanguageServiceMetadata>> _services; private ImmutableDictionary<Type, Lazy<ILanguageService, LanguageServiceMetadata>> _serviceMap = ImmutableDictionary<Type, Lazy<ILanguageService, LanguageServiceMetadata>>.Empty; public MefLanguageServices( MefWorkspaceServices workspaceServices, string language) { _workspaceServices = workspaceServices; _language = language; var hostServices = workspaceServices.HostExportProvider; var services = hostServices.GetExports<ILanguageService, LanguageServiceMetadata>(); var factories = hostServices.GetExports<ILanguageServiceFactory, LanguageServiceMetadata>() .Select(lz => new Lazy<ILanguageService, LanguageServiceMetadata>(() => lz.Value.CreateLanguageService(this), lz.Metadata)); _services = services.Concat(factories).Where(lz => lz.Metadata.Language == language).ToImmutableArray(); } public override HostWorkspaceServices WorkspaceServices => _workspaceServices; public override string Language => _language; public bool HasServices { get { return _services.Length > 0; } } public override TLanguageService GetService<TLanguageService>() { if (TryGetService(typeof(TLanguageService), out var service)) { return (TLanguageService)service.Value; } else { return default; } } internal bool TryGetService(Type serviceType, out Lazy<ILanguageService, LanguageServiceMetadata> service) { if (!_serviceMap.TryGetValue(serviceType, out service)) { service = ImmutableInterlocked.GetOrAdd(ref _serviceMap, serviceType, svctype => { // PERF: Hoist AssemblyQualifiedName out of inner lambda to avoid repeated string allocations. var assemblyQualifiedName = svctype.AssemblyQualifiedName; return PickLanguageService(_services.Where(lz => lz.Metadata.ServiceType == assemblyQualifiedName)); }); } return service != null; } private Lazy<ILanguageService, LanguageServiceMetadata> PickLanguageService(IEnumerable<Lazy<ILanguageService, LanguageServiceMetadata>> services) { Lazy<ILanguageService, LanguageServiceMetadata> service; #if !CODE_STYLE // test layer overrides everything else if (TryGetServiceByLayer(ServiceLayer.Test, services, out service)) { return service; } #endif // workspace specific kind is best if (TryGetServiceByLayer(_workspaceServices.Workspace.Kind, services, out service)) { return service; } // host layer overrides editor, desktop or default if (TryGetServiceByLayer(ServiceLayer.Host, services, out service)) { return service; } // editor layer overrides desktop or default if (TryGetServiceByLayer(ServiceLayer.Editor, services, out service)) { return service; } // desktop layer overrides default if (TryGetServiceByLayer(ServiceLayer.Desktop, services, out service)) { return service; } // that just leaves default if (TryGetServiceByLayer(ServiceLayer.Default, services, out service)) { return service; } // no service return null; } private static bool TryGetServiceByLayer(string layer, IEnumerable<Lazy<ILanguageService, LanguageServiceMetadata>> services, out Lazy<ILanguageService, LanguageServiceMetadata> service) { service = services.SingleOrDefault(lz => lz.Metadata.Layer == layer); return service != null; } internal sealed class LazyServiceMetadataDebuggerProxy { private readonly ImmutableArray<Lazy<ILanguageService, LanguageServiceMetadata>> _services; public LazyServiceMetadataDebuggerProxy(ImmutableArray<Lazy<ILanguageService, LanguageServiceMetadata>> services) => _services = services; public (string type, string layer)[] Metadata => _services.Select(s => (s.Metadata.ServiceType, s.Metadata.Layer)).ToArray(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; [assembly: DebuggerTypeProxy(typeof(MefLanguageServices.LazyServiceMetadataDebuggerProxy), Target = typeof(ImmutableArray<Lazy<ILanguageService, WorkspaceServiceMetadata>>))] namespace Microsoft.CodeAnalysis.Host.Mef { internal sealed class MefLanguageServices : HostLanguageServices { private readonly MefWorkspaceServices _workspaceServices; private readonly string _language; private readonly ImmutableArray<Lazy<ILanguageService, LanguageServiceMetadata>> _services; private ImmutableDictionary<Type, Lazy<ILanguageService, LanguageServiceMetadata>> _serviceMap = ImmutableDictionary<Type, Lazy<ILanguageService, LanguageServiceMetadata>>.Empty; public MefLanguageServices( MefWorkspaceServices workspaceServices, string language) { _workspaceServices = workspaceServices; _language = language; var hostServices = workspaceServices.HostExportProvider; var services = hostServices.GetExports<ILanguageService, LanguageServiceMetadata>(); var factories = hostServices.GetExports<ILanguageServiceFactory, LanguageServiceMetadata>() .Select(lz => new Lazy<ILanguageService, LanguageServiceMetadata>(() => lz.Value.CreateLanguageService(this), lz.Metadata)); _services = services.Concat(factories).Where(lz => lz.Metadata.Language == language).ToImmutableArray(); } public override HostWorkspaceServices WorkspaceServices => _workspaceServices; public override string Language => _language; public bool HasServices { get { return _services.Length > 0; } } public override TLanguageService GetService<TLanguageService>() { if (TryGetService(typeof(TLanguageService), out var service)) { return (TLanguageService)service.Value; } else { return default; } } internal bool TryGetService(Type serviceType, out Lazy<ILanguageService, LanguageServiceMetadata> service) { if (!_serviceMap.TryGetValue(serviceType, out service)) { service = ImmutableInterlocked.GetOrAdd(ref _serviceMap, serviceType, svctype => { // PERF: Hoist AssemblyQualifiedName out of inner lambda to avoid repeated string allocations. var assemblyQualifiedName = svctype.AssemblyQualifiedName; return PickLanguageService(_services.Where(lz => lz.Metadata.ServiceType == assemblyQualifiedName)); }); } return service != null; } private Lazy<ILanguageService, LanguageServiceMetadata> PickLanguageService(IEnumerable<Lazy<ILanguageService, LanguageServiceMetadata>> services) { Lazy<ILanguageService, LanguageServiceMetadata> service; #if !CODE_STYLE // test layer overrides everything else if (TryGetServiceByLayer(ServiceLayer.Test, services, out service)) { return service; } #endif // workspace specific kind is best if (TryGetServiceByLayer(_workspaceServices.Workspace.Kind, services, out service)) { return service; } // host layer overrides editor, desktop or default if (TryGetServiceByLayer(ServiceLayer.Host, services, out service)) { return service; } // editor layer overrides desktop or default if (TryGetServiceByLayer(ServiceLayer.Editor, services, out service)) { return service; } // desktop layer overrides default if (TryGetServiceByLayer(ServiceLayer.Desktop, services, out service)) { return service; } // that just leaves default if (TryGetServiceByLayer(ServiceLayer.Default, services, out service)) { return service; } // no service return null; } private static bool TryGetServiceByLayer(string layer, IEnumerable<Lazy<ILanguageService, LanguageServiceMetadata>> services, out Lazy<ILanguageService, LanguageServiceMetadata> service) { service = services.SingleOrDefault(lz => lz.Metadata.Layer == layer); return service != null; } internal sealed class LazyServiceMetadataDebuggerProxy { private readonly ImmutableArray<Lazy<ILanguageService, LanguageServiceMetadata>> _services; public LazyServiceMetadataDebuggerProxy(ImmutableArray<Lazy<ILanguageService, LanguageServiceMetadata>> services) => _services = services; public (string type, string layer)[] Metadata => _services.Select(s => (s.Metadata.ServiceType, s.Metadata.Layer)).ToArray(); } } }
-1
dotnet/roslyn
55,354
Add IFieldSymbol.FixedSize API
Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
333fred
2021-08-02T22:15:12Z
2021-08-03T21:43:37Z
76bdda7fe502a74f91aee0feb2fe251039be4e82
a81b07d0d5a6b5c5430443fc843e4a730399c946
Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
./src/VisualStudio/Core/Def/Implementation/TableDataSource/Suppression/VisualStudioDiagnosticListSuppressionStateService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ComponentModel.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes.Suppression; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Shell.TableManager; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { /// <summary> /// Service to maintain information about the suppression state of specific set of items in the error list. /// </summary> [Export(typeof(IVisualStudioDiagnosticListSuppressionStateService))] internal class VisualStudioDiagnosticListSuppressionStateService : IVisualStudioDiagnosticListSuppressionStateService { private readonly VisualStudioWorkspace _workspace; private readonly IVsUIShell _shellService; private readonly IWpfTableControl _tableControl; private int _selectedActiveItems; private int _selectedSuppressedItems; private int _selectedRoslynItems; private int _selectedCompilerDiagnosticItems; private int _selectedNoLocationDiagnosticItems; private int _selectedNonSuppressionStateItems; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioDiagnosticListSuppressionStateService( SVsServiceProvider serviceProvider, VisualStudioWorkspace workspace) { _workspace = workspace; _shellService = (IVsUIShell)serviceProvider.GetService(typeof(SVsUIShell)); var errorList = serviceProvider.GetService(typeof(SVsErrorList)) as IErrorList; _tableControl = errorList?.TableControl; ClearState(); InitializeFromTableControlIfNeeded(); } private int SelectedItems => _selectedActiveItems + _selectedSuppressedItems + _selectedNonSuppressionStateItems; // If we can suppress either in source or in suppression file, we enable suppress context menu. public bool CanSuppressSelectedEntries => CanSuppressSelectedEntriesInSource || CanSuppressSelectedEntriesInSuppressionFiles; // If at least one suppressed item is selected, we enable remove suppressions. public bool CanRemoveSuppressionsSelectedEntries => _selectedSuppressedItems > 0; // If at least one Roslyn active item with location is selected, we enable suppress in source. // Note that we do not support suppress in source when mix of Roslyn and non-Roslyn items are selected as in-source suppression has different meaning and implementation for these. public bool CanSuppressSelectedEntriesInSource => _selectedActiveItems > 0 && _selectedRoslynItems == _selectedActiveItems && (_selectedRoslynItems - _selectedNoLocationDiagnosticItems) > 0; // If at least one Roslyn active item is selected, we enable suppress in suppression file. // Also, compiler diagnostics cannot be suppressed in suppression file, so there must be at least one non-compiler item. public bool CanSuppressSelectedEntriesInSuppressionFiles => _selectedActiveItems > 0 && (_selectedRoslynItems - _selectedCompilerDiagnosticItems) > 0; private void ClearState() { _selectedActiveItems = 0; _selectedSuppressedItems = 0; _selectedRoslynItems = 0; _selectedCompilerDiagnosticItems = 0; _selectedNoLocationDiagnosticItems = 0; _selectedNonSuppressionStateItems = 0; } private void InitializeFromTableControlIfNeeded() { if (_tableControl == null) { return; } if (SelectedItems == _tableControl.SelectedEntries.Count()) { // We already have up-to-date state data, so don't need to re-compute. return; } ClearState(); if (ProcessEntries(_tableControl.SelectedEntries, added: true)) { UpdateQueryStatus(); } } /// <summary> /// Updates suppression state information when the selected entries change in the error list. /// </summary> public void ProcessSelectionChanged(TableSelectionChangedEventArgs e) { var hasAddedSuppressionStateEntry = ProcessEntries(e.AddedEntries, added: true); var hasRemovedSuppressionStateEntry = ProcessEntries(e.RemovedEntries, added: false); // If any entry that supports suppression state was ever involved, update query status since each item in the error list // can have different context menu. if (hasAddedSuppressionStateEntry || hasRemovedSuppressionStateEntry) { UpdateQueryStatus(); } InitializeFromTableControlIfNeeded(); } private bool ProcessEntries(IEnumerable<ITableEntryHandle> entryHandles, bool added) { var hasSuppressionStateEntry = false; foreach (var entryHandle in entryHandles) { if (EntrySupportsSuppressionState(entryHandle, out var isRoslynEntry, out var isSuppressedEntry, out var isCompilerDiagnosticEntry, out var isNoLocationDiagnosticEntry)) { hasSuppressionStateEntry = true; HandleSuppressionStateEntry(isRoslynEntry, isSuppressedEntry, isCompilerDiagnosticEntry, isNoLocationDiagnosticEntry, added); } else { HandleNonSuppressionStateEntry(added); } } return hasSuppressionStateEntry; } private static bool EntrySupportsSuppressionState(ITableEntryHandle entryHandle, out bool isRoslynEntry, out bool isSuppressedEntry, out bool isCompilerDiagnosticEntry, out bool isNoLocationDiagnosticEntry) { isNoLocationDiagnosticEntry = !entryHandle.TryGetValue(StandardTableColumnDefinitions.DocumentName, out string filePath) || string.IsNullOrEmpty(filePath); var roslynSnapshot = GetEntriesSnapshot(entryHandle, out var index); if (roslynSnapshot == null) { isRoslynEntry = false; isCompilerDiagnosticEntry = false; return IsNonRoslynEntrySupportingSuppressionState(entryHandle, out isSuppressedEntry); } var diagnosticData = roslynSnapshot?.GetItem(index)?.Data; if (!IsEntryWithConfigurableSuppressionState(diagnosticData)) { isRoslynEntry = false; isSuppressedEntry = false; isCompilerDiagnosticEntry = false; return false; } isRoslynEntry = true; isSuppressedEntry = diagnosticData.IsSuppressed; isCompilerDiagnosticEntry = SuppressionHelpers.IsCompilerDiagnostic(diagnosticData); return true; } private static bool IsNonRoslynEntrySupportingSuppressionState(ITableEntryHandle entryHandle, out bool isSuppressedEntry) { if (entryHandle.TryGetValue(StandardTableKeyNames.SuppressionState, out SuppressionState suppressionStateValue)) { isSuppressedEntry = suppressionStateValue == SuppressionState.Suppressed; return true; } isSuppressedEntry = false; return false; } /// <summary> /// Returns true if an entry's suppression state can be modified. /// </summary> /// <returns></returns> private static bool IsEntryWithConfigurableSuppressionState(DiagnosticData entry) { // Compiler diagnostics with severity 'Error' are not configurable. // Additionally, diagnostics coming from build are from a snapshot (as opposed to live diagnostics) and cannot be configured. return entry != null && !SuppressionHelpers.IsNotConfigurableDiagnostic(entry) && !entry.IsBuildDiagnostic(); } private static AbstractTableEntriesSnapshot<DiagnosticTableItem> GetEntriesSnapshot(ITableEntryHandle entryHandle, out int index) { if (!entryHandle.TryGetSnapshot(out var snapshot, out index)) { return null; } return snapshot as AbstractTableEntriesSnapshot<DiagnosticTableItem>; } /// <summary> /// Gets <see cref="DiagnosticData"/> objects for selected error list entries. /// For remove suppression, the method also returns selected external source diagnostics. /// </summary> public async Task<ImmutableArray<DiagnosticData>> GetSelectedItemsAsync(bool isAddSuppression, CancellationToken cancellationToken) { var builder = ArrayBuilder<DiagnosticData>.GetInstance(); Dictionary<string, Project> projectNameToProjectMapOpt = null; Dictionary<Project, ImmutableDictionary<string, Document>> filePathToDocumentMapOpt = null; foreach (var entryHandle in _tableControl.SelectedEntries) { cancellationToken.ThrowIfCancellationRequested(); DiagnosticData diagnosticData = null; var roslynSnapshot = GetEntriesSnapshot(entryHandle, out var index); if (roslynSnapshot != null) { diagnosticData = roslynSnapshot.GetItem(index)?.Data; } else if (!isAddSuppression) { // For suppression removal, we also need to handle FxCop entries. if (!IsNonRoslynEntrySupportingSuppressionState(entryHandle, out var isSuppressedEntry) || !isSuppressedEntry) { continue; } string filePath = null; var line = -1; // FxCop only supports line, not column. DiagnosticDataLocation location = null; if (entryHandle.TryGetValue(StandardTableColumnDefinitions.ErrorCode, out string errorCode) && !string.IsNullOrEmpty(errorCode) && entryHandle.TryGetValue(StandardTableColumnDefinitions.ErrorCategory, out string category) && !string.IsNullOrEmpty(category) && entryHandle.TryGetValue(StandardTableColumnDefinitions.Text, out string message) && !string.IsNullOrEmpty(message) && entryHandle.TryGetValue(StandardTableColumnDefinitions.ProjectName, out string projectName) && !string.IsNullOrEmpty(projectName)) { if (projectNameToProjectMapOpt == null) { projectNameToProjectMapOpt = new Dictionary<string, Project>(); foreach (var p in _workspace.CurrentSolution.Projects) { projectNameToProjectMapOpt[p.Name] = p; } } cancellationToken.ThrowIfCancellationRequested(); if (!projectNameToProjectMapOpt.TryGetValue(projectName, out var project)) { // bail out continue; } Document document = null; var hasLocation = (entryHandle.TryGetValue(StandardTableColumnDefinitions.DocumentName, out filePath) && !string.IsNullOrEmpty(filePath)) && (entryHandle.TryGetValue(StandardTableColumnDefinitions.Line, out line) && line >= 0); if (hasLocation) { if (string.IsNullOrEmpty(filePath) || line < 0) { // bail out continue; } filePathToDocumentMapOpt ??= new Dictionary<Project, ImmutableDictionary<string, Document>>(); if (!filePathToDocumentMapOpt.TryGetValue(project, out var filePathMap)) { filePathMap = await GetFilePathToDocumentMapAsync(project, cancellationToken).ConfigureAwait(false); filePathToDocumentMapOpt[project] = filePathMap; } if (!filePathMap.TryGetValue(filePath, out document)) { // bail out continue; } var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var linePosition = new LinePosition(line, 0); var linePositionSpan = new LinePositionSpan(start: linePosition, end: linePosition); var textSpan = (await tree.GetTextAsync(cancellationToken).ConfigureAwait(false)).Lines.GetTextSpan(linePositionSpan); location = new DiagnosticDataLocation(document.Id, textSpan, filePath, originalStartLine: linePosition.Line, originalStartColumn: linePosition.Character, originalEndLine: linePosition.Line, originalEndColumn: linePosition.Character); } Contract.ThrowIfNull(project); Contract.ThrowIfFalse((document != null) == (location != null)); // Create a diagnostic with correct values for fields we care about: id, category, message, isSuppressed, location // and default values for the rest of the fields (not used by suppression fixer). diagnosticData = new DiagnosticData( id: errorCode, category: category, message: message, enuMessageForBingSearch: message, severity: DiagnosticSeverity.Warning, defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, warningLevel: 1, isSuppressed: isSuppressedEntry, title: message, location: location, customTags: SuppressionHelpers.SynthesizedExternalSourceDiagnosticCustomTags, properties: ImmutableDictionary<string, string>.Empty, projectId: project.Id); } } if (IsEntryWithConfigurableSuppressionState(diagnosticData)) { builder.Add(diagnosticData); } } return builder.ToImmutableAndFree(); } private static async Task<ImmutableDictionary<string, Document>> GetFilePathToDocumentMapAsync(Project project, CancellationToken cancellationToken) { var builder = ImmutableDictionary.CreateBuilder<string, Document>(); foreach (var document in project.Documents) { cancellationToken.ThrowIfCancellationRequested(); var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var filePath = tree.FilePath; if (filePath != null) { builder.Add(filePath, document); } } return builder.ToImmutable(); } private static void UpdateSelectedItems(bool added, ref int count) { if (added) { count++; } else { count--; } } private void HandleSuppressionStateEntry(bool isRoslynEntry, bool isSuppressedEntry, bool isCompilerDiagnosticEntry, bool isNoLocationDiagnosticEntry, bool added) { if (isRoslynEntry) { UpdateSelectedItems(added, ref _selectedRoslynItems); } if (isCompilerDiagnosticEntry) { UpdateSelectedItems(added, ref _selectedCompilerDiagnosticItems); } if (isNoLocationDiagnosticEntry) { UpdateSelectedItems(added, ref _selectedNoLocationDiagnosticItems); } if (isSuppressedEntry) { UpdateSelectedItems(added, ref _selectedSuppressedItems); } else { UpdateSelectedItems(added, ref _selectedActiveItems); } } private void HandleNonSuppressionStateEntry(bool added) => UpdateSelectedItems(added, ref _selectedNonSuppressionStateItems); private void UpdateQueryStatus() { // Force the shell to refresh the QueryStatus for all the command since default behavior is it only does query // when focus on error list has changed, not individual items. if (_shellService != null) { _shellService.UpdateCommandUI(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; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes.Suppression; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Shell.TableManager; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { /// <summary> /// Service to maintain information about the suppression state of specific set of items in the error list. /// </summary> [Export(typeof(IVisualStudioDiagnosticListSuppressionStateService))] internal class VisualStudioDiagnosticListSuppressionStateService : IVisualStudioDiagnosticListSuppressionStateService { private readonly VisualStudioWorkspace _workspace; private readonly IVsUIShell _shellService; private readonly IWpfTableControl _tableControl; private int _selectedActiveItems; private int _selectedSuppressedItems; private int _selectedRoslynItems; private int _selectedCompilerDiagnosticItems; private int _selectedNoLocationDiagnosticItems; private int _selectedNonSuppressionStateItems; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioDiagnosticListSuppressionStateService( SVsServiceProvider serviceProvider, VisualStudioWorkspace workspace) { _workspace = workspace; _shellService = (IVsUIShell)serviceProvider.GetService(typeof(SVsUIShell)); var errorList = serviceProvider.GetService(typeof(SVsErrorList)) as IErrorList; _tableControl = errorList?.TableControl; ClearState(); InitializeFromTableControlIfNeeded(); } private int SelectedItems => _selectedActiveItems + _selectedSuppressedItems + _selectedNonSuppressionStateItems; // If we can suppress either in source or in suppression file, we enable suppress context menu. public bool CanSuppressSelectedEntries => CanSuppressSelectedEntriesInSource || CanSuppressSelectedEntriesInSuppressionFiles; // If at least one suppressed item is selected, we enable remove suppressions. public bool CanRemoveSuppressionsSelectedEntries => _selectedSuppressedItems > 0; // If at least one Roslyn active item with location is selected, we enable suppress in source. // Note that we do not support suppress in source when mix of Roslyn and non-Roslyn items are selected as in-source suppression has different meaning and implementation for these. public bool CanSuppressSelectedEntriesInSource => _selectedActiveItems > 0 && _selectedRoslynItems == _selectedActiveItems && (_selectedRoslynItems - _selectedNoLocationDiagnosticItems) > 0; // If at least one Roslyn active item is selected, we enable suppress in suppression file. // Also, compiler diagnostics cannot be suppressed in suppression file, so there must be at least one non-compiler item. public bool CanSuppressSelectedEntriesInSuppressionFiles => _selectedActiveItems > 0 && (_selectedRoslynItems - _selectedCompilerDiagnosticItems) > 0; private void ClearState() { _selectedActiveItems = 0; _selectedSuppressedItems = 0; _selectedRoslynItems = 0; _selectedCompilerDiagnosticItems = 0; _selectedNoLocationDiagnosticItems = 0; _selectedNonSuppressionStateItems = 0; } private void InitializeFromTableControlIfNeeded() { if (_tableControl == null) { return; } if (SelectedItems == _tableControl.SelectedEntries.Count()) { // We already have up-to-date state data, so don't need to re-compute. return; } ClearState(); if (ProcessEntries(_tableControl.SelectedEntries, added: true)) { UpdateQueryStatus(); } } /// <summary> /// Updates suppression state information when the selected entries change in the error list. /// </summary> public void ProcessSelectionChanged(TableSelectionChangedEventArgs e) { var hasAddedSuppressionStateEntry = ProcessEntries(e.AddedEntries, added: true); var hasRemovedSuppressionStateEntry = ProcessEntries(e.RemovedEntries, added: false); // If any entry that supports suppression state was ever involved, update query status since each item in the error list // can have different context menu. if (hasAddedSuppressionStateEntry || hasRemovedSuppressionStateEntry) { UpdateQueryStatus(); } InitializeFromTableControlIfNeeded(); } private bool ProcessEntries(IEnumerable<ITableEntryHandle> entryHandles, bool added) { var hasSuppressionStateEntry = false; foreach (var entryHandle in entryHandles) { if (EntrySupportsSuppressionState(entryHandle, out var isRoslynEntry, out var isSuppressedEntry, out var isCompilerDiagnosticEntry, out var isNoLocationDiagnosticEntry)) { hasSuppressionStateEntry = true; HandleSuppressionStateEntry(isRoslynEntry, isSuppressedEntry, isCompilerDiagnosticEntry, isNoLocationDiagnosticEntry, added); } else { HandleNonSuppressionStateEntry(added); } } return hasSuppressionStateEntry; } private static bool EntrySupportsSuppressionState(ITableEntryHandle entryHandle, out bool isRoslynEntry, out bool isSuppressedEntry, out bool isCompilerDiagnosticEntry, out bool isNoLocationDiagnosticEntry) { isNoLocationDiagnosticEntry = !entryHandle.TryGetValue(StandardTableColumnDefinitions.DocumentName, out string filePath) || string.IsNullOrEmpty(filePath); var roslynSnapshot = GetEntriesSnapshot(entryHandle, out var index); if (roslynSnapshot == null) { isRoslynEntry = false; isCompilerDiagnosticEntry = false; return IsNonRoslynEntrySupportingSuppressionState(entryHandle, out isSuppressedEntry); } var diagnosticData = roslynSnapshot?.GetItem(index)?.Data; if (!IsEntryWithConfigurableSuppressionState(diagnosticData)) { isRoslynEntry = false; isSuppressedEntry = false; isCompilerDiagnosticEntry = false; return false; } isRoslynEntry = true; isSuppressedEntry = diagnosticData.IsSuppressed; isCompilerDiagnosticEntry = SuppressionHelpers.IsCompilerDiagnostic(diagnosticData); return true; } private static bool IsNonRoslynEntrySupportingSuppressionState(ITableEntryHandle entryHandle, out bool isSuppressedEntry) { if (entryHandle.TryGetValue(StandardTableKeyNames.SuppressionState, out SuppressionState suppressionStateValue)) { isSuppressedEntry = suppressionStateValue == SuppressionState.Suppressed; return true; } isSuppressedEntry = false; return false; } /// <summary> /// Returns true if an entry's suppression state can be modified. /// </summary> /// <returns></returns> private static bool IsEntryWithConfigurableSuppressionState(DiagnosticData entry) { // Compiler diagnostics with severity 'Error' are not configurable. // Additionally, diagnostics coming from build are from a snapshot (as opposed to live diagnostics) and cannot be configured. return entry != null && !SuppressionHelpers.IsNotConfigurableDiagnostic(entry) && !entry.IsBuildDiagnostic(); } private static AbstractTableEntriesSnapshot<DiagnosticTableItem> GetEntriesSnapshot(ITableEntryHandle entryHandle, out int index) { if (!entryHandle.TryGetSnapshot(out var snapshot, out index)) { return null; } return snapshot as AbstractTableEntriesSnapshot<DiagnosticTableItem>; } /// <summary> /// Gets <see cref="DiagnosticData"/> objects for selected error list entries. /// For remove suppression, the method also returns selected external source diagnostics. /// </summary> public async Task<ImmutableArray<DiagnosticData>> GetSelectedItemsAsync(bool isAddSuppression, CancellationToken cancellationToken) { var builder = ArrayBuilder<DiagnosticData>.GetInstance(); Dictionary<string, Project> projectNameToProjectMapOpt = null; Dictionary<Project, ImmutableDictionary<string, Document>> filePathToDocumentMapOpt = null; foreach (var entryHandle in _tableControl.SelectedEntries) { cancellationToken.ThrowIfCancellationRequested(); DiagnosticData diagnosticData = null; var roslynSnapshot = GetEntriesSnapshot(entryHandle, out var index); if (roslynSnapshot != null) { diagnosticData = roslynSnapshot.GetItem(index)?.Data; } else if (!isAddSuppression) { // For suppression removal, we also need to handle FxCop entries. if (!IsNonRoslynEntrySupportingSuppressionState(entryHandle, out var isSuppressedEntry) || !isSuppressedEntry) { continue; } string filePath = null; var line = -1; // FxCop only supports line, not column. DiagnosticDataLocation location = null; if (entryHandle.TryGetValue(StandardTableColumnDefinitions.ErrorCode, out string errorCode) && !string.IsNullOrEmpty(errorCode) && entryHandle.TryGetValue(StandardTableColumnDefinitions.ErrorCategory, out string category) && !string.IsNullOrEmpty(category) && entryHandle.TryGetValue(StandardTableColumnDefinitions.Text, out string message) && !string.IsNullOrEmpty(message) && entryHandle.TryGetValue(StandardTableColumnDefinitions.ProjectName, out string projectName) && !string.IsNullOrEmpty(projectName)) { if (projectNameToProjectMapOpt == null) { projectNameToProjectMapOpt = new Dictionary<string, Project>(); foreach (var p in _workspace.CurrentSolution.Projects) { projectNameToProjectMapOpt[p.Name] = p; } } cancellationToken.ThrowIfCancellationRequested(); if (!projectNameToProjectMapOpt.TryGetValue(projectName, out var project)) { // bail out continue; } Document document = null; var hasLocation = (entryHandle.TryGetValue(StandardTableColumnDefinitions.DocumentName, out filePath) && !string.IsNullOrEmpty(filePath)) && (entryHandle.TryGetValue(StandardTableColumnDefinitions.Line, out line) && line >= 0); if (hasLocation) { if (string.IsNullOrEmpty(filePath) || line < 0) { // bail out continue; } filePathToDocumentMapOpt ??= new Dictionary<Project, ImmutableDictionary<string, Document>>(); if (!filePathToDocumentMapOpt.TryGetValue(project, out var filePathMap)) { filePathMap = await GetFilePathToDocumentMapAsync(project, cancellationToken).ConfigureAwait(false); filePathToDocumentMapOpt[project] = filePathMap; } if (!filePathMap.TryGetValue(filePath, out document)) { // bail out continue; } var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var linePosition = new LinePosition(line, 0); var linePositionSpan = new LinePositionSpan(start: linePosition, end: linePosition); var textSpan = (await tree.GetTextAsync(cancellationToken).ConfigureAwait(false)).Lines.GetTextSpan(linePositionSpan); location = new DiagnosticDataLocation(document.Id, textSpan, filePath, originalStartLine: linePosition.Line, originalStartColumn: linePosition.Character, originalEndLine: linePosition.Line, originalEndColumn: linePosition.Character); } Contract.ThrowIfNull(project); Contract.ThrowIfFalse((document != null) == (location != null)); // Create a diagnostic with correct values for fields we care about: id, category, message, isSuppressed, location // and default values for the rest of the fields (not used by suppression fixer). diagnosticData = new DiagnosticData( id: errorCode, category: category, message: message, enuMessageForBingSearch: message, severity: DiagnosticSeverity.Warning, defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, warningLevel: 1, isSuppressed: isSuppressedEntry, title: message, location: location, customTags: SuppressionHelpers.SynthesizedExternalSourceDiagnosticCustomTags, properties: ImmutableDictionary<string, string>.Empty, projectId: project.Id); } } if (IsEntryWithConfigurableSuppressionState(diagnosticData)) { builder.Add(diagnosticData); } } return builder.ToImmutableAndFree(); } private static async Task<ImmutableDictionary<string, Document>> GetFilePathToDocumentMapAsync(Project project, CancellationToken cancellationToken) { var builder = ImmutableDictionary.CreateBuilder<string, Document>(); foreach (var document in project.Documents) { cancellationToken.ThrowIfCancellationRequested(); var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var filePath = tree.FilePath; if (filePath != null) { builder.Add(filePath, document); } } return builder.ToImmutable(); } private static void UpdateSelectedItems(bool added, ref int count) { if (added) { count++; } else { count--; } } private void HandleSuppressionStateEntry(bool isRoslynEntry, bool isSuppressedEntry, bool isCompilerDiagnosticEntry, bool isNoLocationDiagnosticEntry, bool added) { if (isRoslynEntry) { UpdateSelectedItems(added, ref _selectedRoslynItems); } if (isCompilerDiagnosticEntry) { UpdateSelectedItems(added, ref _selectedCompilerDiagnosticItems); } if (isNoLocationDiagnosticEntry) { UpdateSelectedItems(added, ref _selectedNoLocationDiagnosticItems); } if (isSuppressedEntry) { UpdateSelectedItems(added, ref _selectedSuppressedItems); } else { UpdateSelectedItems(added, ref _selectedActiveItems); } } private void HandleNonSuppressionStateEntry(bool added) => UpdateSelectedItems(added, ref _selectedNonSuppressionStateItems); private void UpdateQueryStatus() { // Force the shell to refresh the QueryStatus for all the command since default behavior is it only does query // when focus on error list has changed, not individual items. if (_shellService != null) { _shellService.UpdateCommandUI(0); } } } }
-1
dotnet/roslyn
55,354
Add IFieldSymbol.FixedSize API
Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
333fred
2021-08-02T22:15:12Z
2021-08-03T21:43:37Z
76bdda7fe502a74f91aee0feb2fe251039be4e82
a81b07d0d5a6b5c5430443fc843e4a730399c946
Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
./src/Compilers/CSharp/Portable/Binder/LookupSymbolsInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class LookupSymbolsInfo : AbstractLookupSymbolsInfo<Symbol> { // TODO: tune pool size. private const int poolSize = 64; private static readonly ObjectPool<LookupSymbolsInfo> s_pool = new ObjectPool<LookupSymbolsInfo>(() => new LookupSymbolsInfo(), poolSize); private LookupSymbolsInfo() : base(StringComparer.Ordinal) { } // To implement Poolable, you need two things: // 1) Expose Freeing primitive. public void Free() { // Note that poolables are not finalizable. If one gets collected - no big deal. this.Clear(); s_pool.Free(this); } // 2) Expose the way to get an instance. public static LookupSymbolsInfo GetInstance() { var info = s_pool.Allocate(); Debug.Assert(info.Count == 0); return info; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class LookupSymbolsInfo : AbstractLookupSymbolsInfo<Symbol> { // TODO: tune pool size. private const int poolSize = 64; private static readonly ObjectPool<LookupSymbolsInfo> s_pool = new ObjectPool<LookupSymbolsInfo>(() => new LookupSymbolsInfo(), poolSize); private LookupSymbolsInfo() : base(StringComparer.Ordinal) { } // To implement Poolable, you need two things: // 1) Expose Freeing primitive. public void Free() { // Note that poolables are not finalizable. If one gets collected - no big deal. this.Clear(); s_pool.Free(this); } // 2) Expose the way to get an instance. public static LookupSymbolsInfo GetInstance() { var info = s_pool.Allocate(); Debug.Assert(info.Count == 0); return info; } } }
-1
dotnet/roslyn
55,354
Add IFieldSymbol.FixedSize API
Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
333fred
2021-08-02T22:15:12Z
2021-08-03T21:43:37Z
76bdda7fe502a74f91aee0feb2fe251039be4e82
a81b07d0d5a6b5c5430443fc843e4a730399c946
Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
./src/VisualStudio/Core/Impl/CodeModel/ExternalElements/ExternalCodeFunction.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE.CodeFunction))] public sealed class ExternalCodeFunction : AbstractExternalCodeMember, ICodeElementContainer<ExternalCodeParameter>, EnvDTE.CodeFunction, EnvDTE80.CodeFunction2 { internal static EnvDTE.CodeFunction Create(CodeModelState state, ProjectId projectId, IMethodSymbol symbol) { var element = new ExternalCodeFunction(state, projectId, symbol); return (EnvDTE.CodeFunction)ComAggregate.CreateAggregatedObject(element); } private ExternalCodeFunction(CodeModelState state, ProjectId projectId, IMethodSymbol symbol) : base(state, projectId, symbol) { } private IMethodSymbol MethodSymbol { get { return (IMethodSymbol)LookupSymbol(); } } EnvDTE.CodeElements ICodeElementContainer<ExternalCodeParameter>.GetCollection() => this.Parameters; public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementFunction; } } public EnvDTE.vsCMFunction FunctionKind { get { // TODO: Verify VB implementation switch (MethodSymbol.MethodKind) { case MethodKind.Constructor: return EnvDTE.vsCMFunction.vsCMFunctionConstructor; case MethodKind.Destructor: return EnvDTE.vsCMFunction.vsCMFunctionDestructor; case MethodKind.UserDefinedOperator: case MethodKind.Conversion: return EnvDTE.vsCMFunction.vsCMFunctionOperator; case MethodKind.Ordinary: return EnvDTE.vsCMFunction.vsCMFunctionFunction; default: throw Exceptions.ThrowEFail(); } } } public bool IsOverloaded { get { var symbol = (IMethodSymbol)LookupSymbol(); // Only methods and constructors can be overloaded if (symbol.MethodKind != MethodKind.Ordinary && symbol.MethodKind != MethodKind.Constructor) { return false; } var methodsOfName = symbol.ContainingType.GetMembers(symbol.Name) .Where(m => m.Kind == SymbolKind.Method); return methodsOfName.Count() > 1; } } public EnvDTE.CodeElements Overloads { get { return ExternalOverloadsCollection.Create(this.State, this, this.ProjectId); } } public EnvDTE.CodeTypeRef Type { get { // TODO: What if ReturnType is null? return CodeTypeRef.Create(this.State, this, this.ProjectId, MethodSymbol.ReturnType); } set { throw Exceptions.ThrowEFail(); } } public bool IsGeneric { get { return MethodSymbol.IsGenericMethod; } } public EnvDTE80.vsCMOverrideKind OverrideKind { get { // TODO: Verify VB implementation var symbol = MethodSymbol; var result = EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNone; if (symbol.IsAbstract) { result = EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract; } if (symbol.IsVirtual) { result = EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual; } if (symbol.IsOverride) { result = EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride; } if (symbol.HidesBaseMethodsByName) { result = EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNew; } if (symbol.IsSealed) { result = EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed; } return result; } set { throw Exceptions.ThrowEFail(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE.CodeFunction))] public sealed class ExternalCodeFunction : AbstractExternalCodeMember, ICodeElementContainer<ExternalCodeParameter>, EnvDTE.CodeFunction, EnvDTE80.CodeFunction2 { internal static EnvDTE.CodeFunction Create(CodeModelState state, ProjectId projectId, IMethodSymbol symbol) { var element = new ExternalCodeFunction(state, projectId, symbol); return (EnvDTE.CodeFunction)ComAggregate.CreateAggregatedObject(element); } private ExternalCodeFunction(CodeModelState state, ProjectId projectId, IMethodSymbol symbol) : base(state, projectId, symbol) { } private IMethodSymbol MethodSymbol { get { return (IMethodSymbol)LookupSymbol(); } } EnvDTE.CodeElements ICodeElementContainer<ExternalCodeParameter>.GetCollection() => this.Parameters; public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementFunction; } } public EnvDTE.vsCMFunction FunctionKind { get { // TODO: Verify VB implementation switch (MethodSymbol.MethodKind) { case MethodKind.Constructor: return EnvDTE.vsCMFunction.vsCMFunctionConstructor; case MethodKind.Destructor: return EnvDTE.vsCMFunction.vsCMFunctionDestructor; case MethodKind.UserDefinedOperator: case MethodKind.Conversion: return EnvDTE.vsCMFunction.vsCMFunctionOperator; case MethodKind.Ordinary: return EnvDTE.vsCMFunction.vsCMFunctionFunction; default: throw Exceptions.ThrowEFail(); } } } public bool IsOverloaded { get { var symbol = (IMethodSymbol)LookupSymbol(); // Only methods and constructors can be overloaded if (symbol.MethodKind != MethodKind.Ordinary && symbol.MethodKind != MethodKind.Constructor) { return false; } var methodsOfName = symbol.ContainingType.GetMembers(symbol.Name) .Where(m => m.Kind == SymbolKind.Method); return methodsOfName.Count() > 1; } } public EnvDTE.CodeElements Overloads { get { return ExternalOverloadsCollection.Create(this.State, this, this.ProjectId); } } public EnvDTE.CodeTypeRef Type { get { // TODO: What if ReturnType is null? return CodeTypeRef.Create(this.State, this, this.ProjectId, MethodSymbol.ReturnType); } set { throw Exceptions.ThrowEFail(); } } public bool IsGeneric { get { return MethodSymbol.IsGenericMethod; } } public EnvDTE80.vsCMOverrideKind OverrideKind { get { // TODO: Verify VB implementation var symbol = MethodSymbol; var result = EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNone; if (symbol.IsAbstract) { result = EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract; } if (symbol.IsVirtual) { result = EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual; } if (symbol.IsOverride) { result = EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride; } if (symbol.HidesBaseMethodsByName) { result = EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNew; } if (symbol.IsSealed) { result = EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed; } return result; } set { throw Exceptions.ThrowEFail(); } } } }
-1
dotnet/roslyn
55,354
Add IFieldSymbol.FixedSize API
Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
333fred
2021-08-02T22:15:12Z
2021-08-03T21:43:37Z
76bdda7fe502a74f91aee0feb2fe251039be4e82
a81b07d0d5a6b5c5430443fc843e4a730399c946
Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
./src/Compilers/Test/Core/ThrowingTraceListener.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.CodeAnalysis { // To enable this for a process, add the following to the app.config for the project: // // <configuration> // <system.diagnostics> // <trace> // <listeners> // <remove name="Default" /> // <add name="ThrowingTraceListener" type="Microsoft.CodeAnalysis.ThrowingTraceListener, Roslyn.Test.Utilities" /> // </listeners> // </trace> // </system.diagnostics> //</configuration> public sealed class ThrowingTraceListener : TraceListener { public override void Fail(string? message, string? detailMessage) { throw new InvalidOperationException( (string.IsNullOrEmpty(message) ? "Assertion failed" : message) + (string.IsNullOrEmpty(detailMessage) ? "" : Environment.NewLine + detailMessage)); } public override void Write(object? o) { } public override void Write(object? o, string? category) { } public override void Write(string? message) { } public override void Write(string? message, string? category) { } public override void WriteLine(object? o) { } public override void WriteLine(object? o, string? category) { } public override void WriteLine(string? message) { } public override void WriteLine(string? message, string? category) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.CodeAnalysis { // To enable this for a process, add the following to the app.config for the project: // // <configuration> // <system.diagnostics> // <trace> // <listeners> // <remove name="Default" /> // <add name="ThrowingTraceListener" type="Microsoft.CodeAnalysis.ThrowingTraceListener, Roslyn.Test.Utilities" /> // </listeners> // </trace> // </system.diagnostics> //</configuration> public sealed class ThrowingTraceListener : TraceListener { public override void Fail(string? message, string? detailMessage) { throw new InvalidOperationException( (string.IsNullOrEmpty(message) ? "Assertion failed" : message) + (string.IsNullOrEmpty(detailMessage) ? "" : Environment.NewLine + detailMessage)); } public override void Write(object? o) { } public override void Write(object? o, string? category) { } public override void Write(string? message) { } public override void Write(string? message, string? category) { } public override void WriteLine(object? o) { } public override void WriteLine(object? o, string? category) { } public override void WriteLine(string? message) { } public override void WriteLine(string? message, string? category) { } } }
-1
dotnet/roslyn
55,354
Add IFieldSymbol.FixedSize API
Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
333fred
2021-08-02T22:15:12Z
2021-08-03T21:43:37Z
76bdda7fe502a74f91aee0feb2fe251039be4e82
a81b07d0d5a6b5c5430443fc843e4a730399c946
Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Utilities/TypeStyle/CSharpTypeStyleHelper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #else using Microsoft.CodeAnalysis.Options; #endif namespace Microsoft.CodeAnalysis.CSharp.Utilities { internal struct TypeStyleResult { private readonly CSharpTypeStyleHelper _helper; private readonly TypeSyntax _typeName; private readonly SemanticModel _semanticModel; private readonly OptionSet _optionSet; private readonly CancellationToken _cancellationToken; /// <summary> /// Whether or not converting would transition the code to the style the user prefers. i.e. if the user likes /// <c>var</c> for everything, and you have <c>int i = 0</c> then <see cref="IsStylePreferred"/> will be /// <see langword="true"/>. However, if the user likes <c>var</c> for everything and you have <c>var i = 0</c>, /// then it's still possible to convert that, it would just be <see langword="false"/> for /// <see cref="IsStylePreferred"/> because it goes against the user's preferences. /// </summary> /// <remarks> /// <para>In general, most features should only convert the type if <see cref="IsStylePreferred"/> is /// <see langword="true"/>. The one exception is the refactoring, which is explicitly there to still let people /// convert things quickly, even if it's going against their stated style.</para> /// </remarks> public readonly bool IsStylePreferred; public readonly ReportDiagnostic Severity; public TypeStyleResult(CSharpTypeStyleHelper helper, TypeSyntax typeName, SemanticModel semanticModel, OptionSet optionSet, bool isStylePreferred, ReportDiagnostic severity, CancellationToken cancellationToken) : this() { _helper = helper; _typeName = typeName; _semanticModel = semanticModel; _optionSet = optionSet; _cancellationToken = cancellationToken; IsStylePreferred = isStylePreferred; Severity = severity; } public bool CanConvert() => _helper.TryAnalyzeVariableDeclaration(_typeName, _semanticModel, _optionSet, _cancellationToken); } internal abstract partial class CSharpTypeStyleHelper { protected abstract bool IsStylePreferred(in State state); public virtual TypeStyleResult AnalyzeTypeName( TypeSyntax typeName, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken) { if (typeName?.FirstAncestorOrSelf<SyntaxNode>(a => a.IsKind(SyntaxKind.DeclarationExpression, SyntaxKind.VariableDeclaration, SyntaxKind.ForEachStatement)) is not { } declaration) { return default; } var state = new State( declaration, semanticModel, optionSet, cancellationToken); var isStylePreferred = this.IsStylePreferred(in state); var severity = state.GetDiagnosticSeverityPreference(); return new TypeStyleResult( this, typeName, semanticModel, optionSet, isStylePreferred, severity, cancellationToken); } internal abstract bool TryAnalyzeVariableDeclaration( TypeSyntax typeName, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken); protected abstract bool AssignmentSupportsStylePreference(SyntaxToken identifier, TypeSyntax typeName, ExpressionSyntax initializer, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken); internal TypeSyntax? FindAnalyzableType(SyntaxNode node, SemanticModel semanticModel, CancellationToken cancellationToken) { Debug.Assert(node.IsKind(SyntaxKind.VariableDeclaration, SyntaxKind.ForEachStatement, SyntaxKind.DeclarationExpression)); return node switch { VariableDeclarationSyntax variableDeclaration => ShouldAnalyzeVariableDeclaration(variableDeclaration, cancellationToken) ? variableDeclaration.Type : null, ForEachStatementSyntax forEachStatement => ShouldAnalyzeForEachStatement(forEachStatement, semanticModel, cancellationToken) ? forEachStatement.Type : null, DeclarationExpressionSyntax declarationExpression => ShouldAnalyzeDeclarationExpression(declarationExpression, semanticModel, cancellationToken) ? declarationExpression.Type : null, _ => null, }; } public virtual bool ShouldAnalyzeVariableDeclaration(VariableDeclarationSyntax variableDeclaration, CancellationToken cancellationToken) { // implicit type is applicable only for local variables and // such declarations cannot have multiple declarators and // must have an initializer. var isSupportedParentKind = variableDeclaration.IsParentKind( SyntaxKind.LocalDeclarationStatement, SyntaxKind.ForStatement, SyntaxKind.UsingStatement); return isSupportedParentKind && variableDeclaration.Variables.Count == 1 && variableDeclaration.Variables.Single().Initializer.IsKind(SyntaxKind.EqualsValueClause); } protected virtual bool ShouldAnalyzeForEachStatement(ForEachStatementSyntax forEachStatement, SemanticModel semanticModel, CancellationToken cancellationToken) => true; protected virtual bool ShouldAnalyzeDeclarationExpression(DeclarationExpressionSyntax declaration, SemanticModel semanticModel, CancellationToken cancellationToken) { // Ensure that deconstruction assignment or foreach variable statement have a non-null deconstruct method. DeconstructionInfo? deconstructionInfoOpt = null; switch (declaration.Parent) { case AssignmentExpressionSyntax assignmentExpression: if (assignmentExpression.IsDeconstruction()) { deconstructionInfoOpt = semanticModel.GetDeconstructionInfo(assignmentExpression); } break; case ForEachVariableStatementSyntax forEachVariableStatement: deconstructionInfoOpt = semanticModel.GetDeconstructionInfo(forEachVariableStatement); break; } return !deconstructionInfoOpt.HasValue || !deconstructionInfoOpt.Value.Nested.IsEmpty || deconstructionInfoOpt.Value.Method != null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #else using Microsoft.CodeAnalysis.Options; #endif namespace Microsoft.CodeAnalysis.CSharp.Utilities { internal struct TypeStyleResult { private readonly CSharpTypeStyleHelper _helper; private readonly TypeSyntax _typeName; private readonly SemanticModel _semanticModel; private readonly OptionSet _optionSet; private readonly CancellationToken _cancellationToken; /// <summary> /// Whether or not converting would transition the code to the style the user prefers. i.e. if the user likes /// <c>var</c> for everything, and you have <c>int i = 0</c> then <see cref="IsStylePreferred"/> will be /// <see langword="true"/>. However, if the user likes <c>var</c> for everything and you have <c>var i = 0</c>, /// then it's still possible to convert that, it would just be <see langword="false"/> for /// <see cref="IsStylePreferred"/> because it goes against the user's preferences. /// </summary> /// <remarks> /// <para>In general, most features should only convert the type if <see cref="IsStylePreferred"/> is /// <see langword="true"/>. The one exception is the refactoring, which is explicitly there to still let people /// convert things quickly, even if it's going against their stated style.</para> /// </remarks> public readonly bool IsStylePreferred; public readonly ReportDiagnostic Severity; public TypeStyleResult(CSharpTypeStyleHelper helper, TypeSyntax typeName, SemanticModel semanticModel, OptionSet optionSet, bool isStylePreferred, ReportDiagnostic severity, CancellationToken cancellationToken) : this() { _helper = helper; _typeName = typeName; _semanticModel = semanticModel; _optionSet = optionSet; _cancellationToken = cancellationToken; IsStylePreferred = isStylePreferred; Severity = severity; } public bool CanConvert() => _helper.TryAnalyzeVariableDeclaration(_typeName, _semanticModel, _optionSet, _cancellationToken); } internal abstract partial class CSharpTypeStyleHelper { protected abstract bool IsStylePreferred(in State state); public virtual TypeStyleResult AnalyzeTypeName( TypeSyntax typeName, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken) { if (typeName?.FirstAncestorOrSelf<SyntaxNode>(a => a.IsKind(SyntaxKind.DeclarationExpression, SyntaxKind.VariableDeclaration, SyntaxKind.ForEachStatement)) is not { } declaration) { return default; } var state = new State( declaration, semanticModel, optionSet, cancellationToken); var isStylePreferred = this.IsStylePreferred(in state); var severity = state.GetDiagnosticSeverityPreference(); return new TypeStyleResult( this, typeName, semanticModel, optionSet, isStylePreferred, severity, cancellationToken); } internal abstract bool TryAnalyzeVariableDeclaration( TypeSyntax typeName, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken); protected abstract bool AssignmentSupportsStylePreference(SyntaxToken identifier, TypeSyntax typeName, ExpressionSyntax initializer, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken); internal TypeSyntax? FindAnalyzableType(SyntaxNode node, SemanticModel semanticModel, CancellationToken cancellationToken) { Debug.Assert(node.IsKind(SyntaxKind.VariableDeclaration, SyntaxKind.ForEachStatement, SyntaxKind.DeclarationExpression)); return node switch { VariableDeclarationSyntax variableDeclaration => ShouldAnalyzeVariableDeclaration(variableDeclaration, cancellationToken) ? variableDeclaration.Type : null, ForEachStatementSyntax forEachStatement => ShouldAnalyzeForEachStatement(forEachStatement, semanticModel, cancellationToken) ? forEachStatement.Type : null, DeclarationExpressionSyntax declarationExpression => ShouldAnalyzeDeclarationExpression(declarationExpression, semanticModel, cancellationToken) ? declarationExpression.Type : null, _ => null, }; } public virtual bool ShouldAnalyzeVariableDeclaration(VariableDeclarationSyntax variableDeclaration, CancellationToken cancellationToken) { // implicit type is applicable only for local variables and // such declarations cannot have multiple declarators and // must have an initializer. var isSupportedParentKind = variableDeclaration.IsParentKind( SyntaxKind.LocalDeclarationStatement, SyntaxKind.ForStatement, SyntaxKind.UsingStatement); return isSupportedParentKind && variableDeclaration.Variables.Count == 1 && variableDeclaration.Variables.Single().Initializer.IsKind(SyntaxKind.EqualsValueClause); } protected virtual bool ShouldAnalyzeForEachStatement(ForEachStatementSyntax forEachStatement, SemanticModel semanticModel, CancellationToken cancellationToken) => true; protected virtual bool ShouldAnalyzeDeclarationExpression(DeclarationExpressionSyntax declaration, SemanticModel semanticModel, CancellationToken cancellationToken) { // Ensure that deconstruction assignment or foreach variable statement have a non-null deconstruct method. DeconstructionInfo? deconstructionInfoOpt = null; switch (declaration.Parent) { case AssignmentExpressionSyntax assignmentExpression: if (assignmentExpression.IsDeconstruction()) { deconstructionInfoOpt = semanticModel.GetDeconstructionInfo(assignmentExpression); } break; case ForEachVariableStatementSyntax forEachVariableStatement: deconstructionInfoOpt = semanticModel.GetDeconstructionInfo(forEachVariableStatement); break; } return !deconstructionInfoOpt.HasValue || !deconstructionInfoOpt.Value.Nested.IsEmpty || deconstructionInfoOpt.Value.Method != null; } } }
-1
dotnet/roslyn
55,354
Add IFieldSymbol.FixedSize API
Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
333fred
2021-08-02T22:15:12Z
2021-08-03T21:43:37Z
76bdda7fe502a74f91aee0feb2fe251039be4e82
a81b07d0d5a6b5c5430443fc843e4a730399c946
Add IFieldSymbol.FixedSize API. Closes https://github.com/dotnet/roslyn/issues/54799 by exposing existing internal functionality.
./src/VisualStudio/Core/Def/Implementation/Library/ILibraryService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Host; using Microsoft.VisualStudio.LanguageServices.Implementation.Library.VsNavInfo; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library { internal interface ILibraryService : ILanguageService { NavInfoFactory NavInfoFactory { 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 disable using Microsoft.CodeAnalysis.Host; using Microsoft.VisualStudio.LanguageServices.Implementation.Library.VsNavInfo; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library { internal interface ILibraryService : ILanguageService { NavInfoFactory NavInfoFactory { get; } } }
-1