2 // generic.cs: Generics support
4 // Authors: Martin Baulig (martin@ximian.com)
5 // Miguel de Icaza (miguel@ximian.com)
6 // Marek Safar (marek.safar@gmail.com)
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
10 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004-2008 Novell, Inc
14 using System.Reflection;
15 using System.Reflection.Emit;
16 using System.Globalization;
17 using System.Collections.Generic;
21 namespace Mono.CSharp {
25 // Don't add or modify internal values, they are used as -/+ calculation signs
33 public enum SpecialConstraint
41 public class SpecialContraintExpr : FullNamedExpression
43 public SpecialContraintExpr (SpecialConstraint constraint, Location loc)
46 this.Constraint = constraint;
49 public SpecialConstraint Constraint { get; private set; }
51 protected override Expression DoResolve (ResolveContext rc)
53 throw new NotImplementedException ();
58 // A set of parsed constraints for a type parameter
60 public class Constraints
62 SimpleMemberName tparam;
63 List<FullNamedExpression> constraints;
68 public Constraints (SimpleMemberName tparam, List<FullNamedExpression> constraints, Location loc)
71 this.constraints = constraints;
77 public Location Location {
83 public SimpleMemberName TypeParameter {
91 public static bool CheckConflictingInheritedConstraint (TypeParameterSpec spec, TypeSpec bb, IMemberContext context, Location loc)
93 if (spec.HasSpecialClass && bb.IsStruct) {
94 context.Compiler.Report.Error (455, loc,
95 "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
96 spec.Name, "class", bb.GetSignatureForError ());
101 return CheckConflictingInheritedConstraint (spec, spec.BaseType, bb, context, loc);
104 static bool CheckConflictingInheritedConstraint (TypeParameterSpec spec, TypeSpec ba, TypeSpec bb, IMemberContext context, Location loc)
109 if (TypeSpec.IsBaseClass (ba, bb, false) || TypeSpec.IsBaseClass (bb, ba, false))
112 context.Compiler.Report.Error (455, loc,
113 "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
114 spec.Name, ba.GetSignatureForError (), bb.GetSignatureForError ());
118 public void CheckGenericConstraints (IMemberContext context)
120 foreach (var c in constraints) {
121 var ge = c as GenericTypeExpr;
123 ge.CheckConstraints (context);
128 // Resolve the constraints types with only possible early checks, return
129 // value `false' is reserved for recursive failure
131 public bool Resolve (IMemberContext context, TypeParameter tp)
141 List<TypeParameterSpec> tparam_types = null;
142 bool iface_found = false;
144 spec.BaseType = TypeManager.object_type;
146 for (int i = 0; i < constraints.Count; ++i) {
147 var constraint = constraints[i];
149 if (constraint is SpecialContraintExpr) {
150 spec.SpecialConstraint |= ((SpecialContraintExpr) constraint).Constraint;
151 if (spec.HasSpecialStruct)
152 spec.BaseType = TypeManager.value_type;
154 // Set to null as it does not have a type
155 constraints[i] = null;
159 var type_expr = constraints[i] = constraint.ResolveAsTypeTerminal (context, false);
160 if (type_expr == null)
163 var gexpr = type_expr as GenericTypeExpr;
164 if (gexpr != null && gexpr.HasDynamicArguments ()) {
165 context.Compiler.Report.Error (1968, constraint.Location,
166 "A constraint cannot be the dynamic type `{0}'", gexpr.GetSignatureForError ());
170 var type = type_expr.Type;
172 if (!context.CurrentMemberDefinition.IsAccessibleAs (type)) {
173 context.Compiler.Report.SymbolRelatedToPreviousError (type);
174 context.Compiler.Report.Error (703, loc,
175 "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
176 type.GetSignatureForError (), context.GetSignatureForError ());
179 if (type.IsInterface) {
180 if (!spec.AddInterface (type)) {
181 context.Compiler.Report.Error (405, constraint.Location,
182 "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
190 var constraint_tp = type as TypeParameterSpec;
191 if (constraint_tp != null) {
192 if (tparam_types == null) {
193 tparam_types = new List<TypeParameterSpec> (2);
194 } else if (tparam_types.Contains (constraint_tp)) {
195 context.Compiler.Report.Error (405, constraint.Location,
196 "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
201 // Checks whether each generic method parameter constraint type
202 // is valid with respect to T
204 if (tp.IsMethodTypeParameter) {
205 TypeManager.CheckTypeVariance (type, Variance.Contravariant, context);
208 var tp_def = constraint_tp.MemberDefinition as TypeParameter;
209 if (tp_def != null && !tp_def.ResolveConstraints (context)) {
210 context.Compiler.Report.Error (454, constraint.Location,
211 "Circular constraint dependency involving `{0}' and `{1}'",
212 constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
217 // Checks whether there are no conflicts between type parameter constraints
223 // A and B are not convertible and only 1 class constraint is allowed
225 if (constraint_tp.HasTypeConstraint) {
226 if (spec.HasTypeConstraint || spec.HasSpecialStruct) {
227 if (!CheckConflictingInheritedConstraint (spec, constraint_tp.BaseType, context, constraint.Location))
230 for (int ii = 0; ii < tparam_types.Count; ++ii) {
231 if (!tparam_types[ii].HasTypeConstraint)
234 if (!CheckConflictingInheritedConstraint (spec, tparam_types[ii].BaseType, constraint_tp.BaseType, context, constraint.Location))
240 if (constraint_tp.HasSpecialStruct) {
241 context.Compiler.Report.Error (456, constraint.Location,
242 "Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
243 constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
247 tparam_types.Add (constraint_tp);
251 if (iface_found || spec.HasTypeConstraint) {
252 context.Compiler.Report.Error (406, constraint.Location,
253 "The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
254 type.GetSignatureForError ());
257 if (spec.HasSpecialStruct || spec.HasSpecialClass) {
258 context.Compiler.Report.Error (450, type_expr.Location,
259 "`{0}': cannot specify both a constraint class and the `class' or `struct' constraint",
260 type.GetSignatureForError ());
263 if (type == InternalType.Dynamic) {
264 context.Compiler.Report.Error (1967, constraint.Location, "A constraint cannot be the dynamic type");
268 if (type.IsSealed || !type.IsClass) {
269 context.Compiler.Report.Error (701, loc,
270 "`{0}' is not a valid constraint. A constraint must be an interface, a non-sealed class or a type parameter",
271 TypeManager.CSharpName (type));
276 context.Compiler.Report.Error (717, constraint.Location,
277 "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
278 type.GetSignatureForError ());
279 } else if (type == TypeManager.array_type || type == TypeManager.delegate_type ||
280 type == TypeManager.enum_type || type == TypeManager.value_type ||
281 type == TypeManager.object_type || type == TypeManager.multicast_delegate_type) {
282 context.Compiler.Report.Error (702, constraint.Location,
283 "A constraint cannot be special class `{0}'", type.GetSignatureForError ());
287 spec.BaseType = type;
290 if (tparam_types != null)
291 spec.TypeArguments = tparam_types.ToArray ();
298 public void VerifyClsCompliance (Report report)
300 foreach (var c in constraints)
305 if (!c.Type.IsCLSCompliant ()) {
306 report.SymbolRelatedToPreviousError (c.Type);
307 report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
308 c.Type.GetSignatureForError ());
315 // A type parameter for a generic type or generic method definition
317 public class TypeParameter : MemberCore, ITypeDefinition
319 static readonly string[] attribute_target = new string [] { "type parameter" };
321 Constraints constraints;
322 GenericTypeParameterBuilder builder;
323 TypeParameterSpec spec;
325 public TypeParameter (DeclSpace parent, int index, MemberName name, Constraints constraints, Attributes attrs, Variance variance)
326 : base (parent, name, attrs)
328 this.constraints = constraints;
329 this.spec = new TypeParameterSpec (null, index, this, SpecialConstraint.None, variance, null);
332 public TypeParameter (TypeParameterSpec spec, DeclSpace parent, TypeSpec parentSpec, MemberName name, Attributes attrs)
333 : base (parent, name, attrs)
335 this.spec = new TypeParameterSpec (parentSpec, spec.DeclaredPosition, spec.MemberDefinition, spec.SpecialConstraint, spec.Variance, null) {
336 BaseType = spec.BaseType,
337 InterfacesDefined = spec.InterfacesDefined,
338 TypeArguments = spec.TypeArguments
344 public override AttributeTargets AttributeTargets {
346 return AttributeTargets.GenericParameter;
350 public override string DocCommentHeader {
352 throw new InvalidOperationException (
353 "Unexpected attempt to get doc comment from " + this.GetType ());
357 public bool IsMethodTypeParameter {
359 return spec.IsMethodOwned;
363 public string Namespace {
369 public TypeParameterSpec Type {
375 public int TypeParametersCount {
381 public TypeParameterSpec[] TypeParameters {
387 public override string[] ValidAttributeTargets {
389 return attribute_target;
393 public Variance Variance {
395 return spec.Variance;
402 // This is called for each part of a partial generic type definition.
404 // If partial type parameters constraints are not null and we don't
405 // already have constraints they become our constraints. If we already
406 // have constraints, we must check that they're the same.
408 public bool AddPartialConstraints (TypeContainer part, TypeParameter tp)
411 throw new InvalidOperationException ();
413 var new_constraints = tp.constraints;
414 if (new_constraints == null)
417 // TODO: could create spec only
418 //tp.Define (null, -1, part.Definition);
419 tp.spec.DeclaringType = part.Definition;
420 if (!tp.ResolveConstraints (part))
423 if (constraints != null)
424 return spec.HasSameConstraintsDefinition (tp.Type);
426 // Copy constraint from resolved part to partial container
427 spec.SpecialConstraint = tp.spec.SpecialConstraint;
428 spec.InterfacesDefined = tp.spec.InterfacesDefined;
429 spec.TypeArguments = tp.spec.TypeArguments;
430 spec.BaseType = tp.spec.BaseType;
435 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
437 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
440 public void CheckGenericConstraints ()
442 if (constraints != null)
443 constraints.CheckGenericConstraints (this);
446 public TypeParameter CreateHoistedCopy (TypeContainer declaringType, TypeSpec declaringSpec)
448 return new TypeParameter (spec, declaringType, declaringSpec, MemberName, null);
451 public override bool Define ()
457 // This is the first method which is called during the resolving
458 // process; we're called immediately after creating the type parameters
459 // with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
462 public void Define (GenericTypeParameterBuilder type, TypeSpec declaringType)
465 throw new InternalErrorException ();
468 spec.DeclaringType = declaringType;
469 spec.SetMetaInfo (type);
472 public void EmitConstraints (GenericTypeParameterBuilder builder)
474 var attr = GenericParameterAttributes.None;
475 if (spec.Variance == Variance.Contravariant)
476 attr |= GenericParameterAttributes.Contravariant;
477 else if (spec.Variance == Variance.Covariant)
478 attr |= GenericParameterAttributes.Covariant;
480 if (spec.HasSpecialClass)
481 attr |= GenericParameterAttributes.ReferenceTypeConstraint;
482 else if (spec.HasSpecialStruct)
483 attr |= GenericParameterAttributes.NotNullableValueTypeConstraint | GenericParameterAttributes.DefaultConstructorConstraint;
485 if (spec.HasSpecialConstructor)
486 attr |= GenericParameterAttributes.DefaultConstructorConstraint;
488 if (spec.BaseType != TypeManager.object_type)
489 builder.SetBaseTypeConstraint (spec.BaseType.GetMetaInfo ());
491 if (spec.InterfacesDefined != null)
492 builder.SetInterfaceConstraints (spec.InterfacesDefined.Select (l => l.GetMetaInfo ()).ToArray ());
494 if (spec.TypeArguments != null)
495 builder.SetInterfaceConstraints (spec.TypeArguments.Select (l => l.GetMetaInfo ()).ToArray ());
497 builder.SetGenericParameterAttributes (attr);
500 public override void Emit ()
502 EmitConstraints (builder);
504 if (OptAttributes != null)
505 OptAttributes.Emit ();
510 public void ErrorInvalidVariance (IMemberContext mc, Variance expected)
512 Report.SymbolRelatedToPreviousError (mc.CurrentMemberDefinition);
513 string input_variance = Variance == Variance.Contravariant ? "contravariant" : "covariant";
514 string gtype_variance;
516 case Variance.Contravariant: gtype_variance = "contravariantly"; break;
517 case Variance.Covariant: gtype_variance = "covariantly"; break;
518 default: gtype_variance = "invariantly"; break;
521 Delegate d = mc as Delegate;
522 string parameters = d != null ? d.Parameters.GetSignatureForError () : "";
524 Report.Error (1961, Location,
525 "The {2} type parameter `{0}' must be {3} valid on `{1}{4}'",
526 GetSignatureForError (), mc.GetSignatureForError (), input_variance, gtype_variance, parameters);
529 public TypeSpec GetAttributeCoClass ()
534 public string GetAttributeDefaultMember ()
536 throw new NotSupportedException ();
539 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
541 throw new NotSupportedException ();
544 public override string GetSignatureForError ()
546 return MemberName.Name;
549 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
551 throw new NotSupportedException ("Not supported for compiled definition");
555 // Resolves all type parameter constraints
557 public bool ResolveConstraints (IMemberContext context)
559 if (constraints != null)
560 return constraints.Resolve (context, this);
562 if (spec.BaseType == null)
563 spec.BaseType = TypeManager.object_type;
568 public static TypeParameter FindTypeParameter (TypeParameter[] tparams, string name)
570 foreach (var tp in tparams) {
578 public override bool IsClsComplianceRequired ()
583 public new void VerifyClsCompliance ()
585 if (constraints != null)
586 constraints.VerifyClsCompliance (Report);
590 [System.Diagnostics.DebuggerDisplay ("{DisplayDebugInfo()}")]
591 public class TypeParameterSpec : TypeSpec
593 public static readonly new TypeParameterSpec[] EmptyTypes = new TypeParameterSpec[0];
596 SpecialConstraint spec;
599 TypeSpec[] ifaces_defined;
602 // Creates type owned type parameter
604 public TypeParameterSpec (TypeSpec declaringType, int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, Type info)
605 : base (MemberKind.TypeParameter, declaringType, definition, info, Modifiers.PUBLIC)
607 this.variance = variance;
609 state &= ~StateFlags.Obsolete_Undetected;
614 // Creates method owned type parameter
616 public TypeParameterSpec (int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, Type info)
617 : this (null, index, definition, spec, variance, info)
623 public int DeclaredPosition {
629 public bool HasSpecialConstructor {
631 return (spec & SpecialConstraint.Constructor) != 0;
635 public bool HasSpecialClass {
637 return (spec & SpecialConstraint.Class) != 0;
641 public bool HasSpecialStruct {
643 return (spec & SpecialConstraint.Struct) != 0;
647 public bool HasTypeConstraint {
649 return BaseType != TypeManager.object_type && BaseType != TypeManager.value_type;
653 public override IList<TypeSpec> Interfaces {
655 if ((state & StateFlags.InterfacesExpanded) == 0) {
656 if (ifaces != null) {
657 for (int i = 0; i < ifaces.Count; ++i ) {
658 var iface_type = ifaces[i];
659 if (iface_type.Interfaces != null) {
660 if (ifaces_defined == null)
661 ifaces_defined = ifaces.ToArray ();
663 for (int ii = 0; ii < iface_type.Interfaces.Count; ++ii) {
664 var ii_iface_type = iface_type.Interfaces [ii];
666 AddInterface (ii_iface_type);
672 if (ifaces_defined == null && ifaces != null)
673 ifaces_defined = ifaces.ToArray ();
675 state |= StateFlags.InterfacesExpanded;
683 // Unexpanded interfaces list
685 public TypeSpec[] InterfacesDefined {
687 if (ifaces_defined == null && ifaces != null)
688 ifaces_defined = ifaces.ToArray ();
690 return ifaces_defined;
693 ifaces_defined = value;
697 public bool IsConstrained {
699 return spec != SpecialConstraint.None || ifaces != null || targs != null || HasTypeConstraint;
704 // Returns whether the type parameter is "known to be a reference type"
706 public bool IsReferenceType {
708 return (spec & SpecialConstraint.Class) != 0 || HasTypeConstraint;
712 public bool IsValueType { // TODO: Do I need this ?
714 // TODO MemberCache: probably wrong
715 return HasSpecialStruct;
719 public override string Name {
721 return definition.Name;
725 public bool IsMethodOwned {
727 return DeclaringType == null;
731 public SpecialConstraint SpecialConstraint {
741 // Types used to inflate the generic type
743 public new TypeSpec[] TypeArguments {
752 public Variance Variance {
760 public void ChangeTypeArgumentToBaseType (int index)
762 BaseType = targs [index];
763 if (targs.Length == 1) {
766 var copy = new TypeSpec[targs.Length - 1];
768 Array.Copy (targs, copy, index);
770 Array.Copy (targs, index + 1, copy, index, targs.Length - index - 1);
775 public string DisplayDebugInfo ()
777 var s = GetSignatureForError ();
778 return IsMethodOwned ? s + "!!" : s + "!";
782 // Finds effective base class
784 public TypeSpec GetEffectiveBase ()
786 if (HasSpecialStruct) {
787 return TypeManager.value_type;
790 if (BaseType != null && targs == null)
794 if (HasTypeConstraint) {
795 Array.Resize (ref types, types.Length + 1);
796 types[types.Length - 1] = BaseType;
800 return Convert.FindMostEncompassedType (types.Select (l => l.BaseType));
802 return TypeManager.object_type;
805 public override string GetSignatureForError ()
811 // Constraints have to match by definition but not position, used by
812 // partial classes or methods
814 public bool HasSameConstraintsDefinition (TypeParameterSpec other)
816 if (spec != other.spec)
819 if (BaseType != other.BaseType)
822 if (!TypeSpecComparer.Override.IsSame (InterfacesDefined, other.InterfacesDefined))
825 if (!TypeSpecComparer.Override.IsSame (targs, other.targs))
832 // Constraints have to match by using same set of types, used by
833 // implicit interface implementation
835 public bool HasSameConstraintsImplementation (TypeParameterSpec other)
837 if (spec != other.spec)
841 // It can be same base type or inflated type parameter
843 // interface I<T> { void Foo<U> where U : T; }
844 // class A : I<int> { void Foo<X> where X : int {} }
847 if (!TypeSpecComparer.Override.IsEqual (BaseType, other.BaseType)) {
848 if (other.targs == null)
852 foreach (var otarg in other.targs) {
853 if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
863 // Check interfaces implementation -> definition
864 if (InterfacesDefined != null) {
865 foreach (var iface in InterfacesDefined) {
867 if (other.InterfacesDefined != null) {
868 foreach (var oiface in other.InterfacesDefined) {
869 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
879 if (other.targs != null) {
880 foreach (var otarg in other.targs) {
881 if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
893 // Check interfaces implementation <- definition
894 if (other.InterfacesDefined != null) {
895 if (InterfacesDefined == null)
898 foreach (var oiface in other.InterfacesDefined) {
900 foreach (var iface in InterfacesDefined) {
901 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
912 // Check type parameters implementation -> definition
914 if (other.targs == null)
917 foreach (var targ in targs) {
919 foreach (var otarg in other.targs) {
920 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
931 // Check type parameters implementation <- definition
932 if (other.targs != null) {
933 foreach (var otarg in other.targs) {
934 // Ignore inflated type arguments, were checked above
935 if (!otarg.IsGenericParameter)
942 foreach (var targ in targs) {
943 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
957 public static TypeParameterSpec[] InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec[] tparams)
959 return InflateConstraints (tparams, l => l, inflator);
962 public static TypeParameterSpec[] InflateConstraints<T> (TypeParameterSpec[] tparams, Func<T, TypeParameterInflator> inflatorFactory, T arg)
964 TypeParameterSpec[] constraints = null;
965 TypeParameterInflator? inflator = null;
967 for (int i = 0; i < tparams.Length; ++i) {
969 if (tp.HasTypeConstraint || tp.Interfaces != null || tp.TypeArguments != null) {
970 if (constraints == null) {
971 constraints = new TypeParameterSpec[tparams.Length];
972 Array.Copy (tparams, constraints, constraints.Length);
976 // Using a factory to avoid possibly expensive inflator build up
978 if (inflator == null)
979 inflator = inflatorFactory (arg);
981 constraints[i] = (TypeParameterSpec) constraints[i].InflateMember (inflator.Value);
985 if (constraints == null)
986 constraints = tparams;
991 public void InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec tps)
993 tps.BaseType = inflator.Inflate (BaseType);
994 if (ifaces != null) {
995 tps.ifaces = new List<TypeSpec> (ifaces.Count);
996 for (int i = 0; i < ifaces.Count; ++i)
997 tps.ifaces.Add (inflator.Inflate (ifaces[i]));
1000 if (targs != null) {
1001 tps.targs = new TypeSpec[targs.Length];
1002 for (int i = 0; i < targs.Length; ++i)
1003 tps.targs[i] = inflator.Inflate (targs[i]);
1007 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1009 var tps = (TypeParameterSpec) MemberwiseClone ();
1010 InflateConstraints (inflator, tps);
1015 // Populates type parameter members using type parameter constraints
1016 // The trick here is to be called late enough but not too late to
1017 // populate member cache with all members from other types
1019 protected override void InitializeMemberCache (bool onlyTypes)
1021 cache = new MemberCache ();
1022 if (ifaces != null) {
1023 foreach (var iface_type in Interfaces) {
1024 cache.AddInterface (iface_type);
1029 public bool IsConvertibleToInterface (TypeSpec iface)
1031 if (Interfaces != null) {
1032 foreach (var t in Interfaces) {
1038 if (TypeArguments != null) {
1039 foreach (var t in TypeArguments) {
1040 if (((TypeParameterSpec) t).IsConvertibleToInterface (iface))
1048 public override TypeSpec Mutate (TypeParameterMutator mutator)
1050 return mutator.Mutate (this);
1054 public struct TypeParameterInflator
1056 readonly TypeSpec type;
1057 readonly TypeParameterSpec[] tparams;
1058 readonly TypeSpec[] targs;
1060 public TypeParameterInflator (TypeParameterInflator nested, TypeSpec type)
1061 : this (type, nested.tparams, nested.targs)
1065 public TypeParameterInflator (TypeSpec type, TypeParameterSpec[] tparams, TypeSpec[] targs)
1067 if (tparams.Length != targs.Length)
1068 throw new ArgumentException ("Invalid arguments");
1070 this.tparams = tparams;
1077 public TypeSpec TypeInstance {
1078 get { return type; }
1082 // Type parameters to inflate
1084 public TypeParameterSpec[] TypeParameters {
1092 public TypeSpec Inflate (TypeSpec type)
1094 var tp = type as TypeParameterSpec;
1096 return Inflate (tp);
1098 var ac = type as ArrayContainer;
1100 var et = Inflate (ac.Element);
1101 if (et != ac.Element)
1102 return ArrayContainer.MakeType (et, ac.Rank);
1108 // When inflating a nested type, inflate its parent first
1109 // in case it's using same type parameters (was inflated within the type)
1113 if (type.IsNested) {
1114 var parent = Inflate (type.DeclaringType);
1117 // Keep the inflated type arguments
1119 targs = type.TypeArguments;
1122 // Parent was inflated, find the same type on inflated type
1123 // to use same cache for nested types on same generic parent
1125 type = MemberCache.FindNestedType (parent, type.Name, type.Arity);
1128 // Handle the tricky case where parent shares local type arguments
1129 // which means inflating inflated type
1132 // public static Nested<T> Foo () { return null; }
1134 // public class Nested<U> {}
1137 // return type of Test<string>.Foo() has to be Test<string>.Nested<string>
1139 if (targs.Length > 0) {
1140 var inflated_targs = new TypeSpec[targs.Length];
1141 for (; i < targs.Length; ++i)
1142 inflated_targs[i] = Inflate (targs[i]);
1144 type = type.MakeGenericType (inflated_targs);
1150 // Nothing to do for non-generic type
1151 if (type.Arity == 0)
1154 targs = new TypeSpec[type.Arity];
1157 // Inflating using outside type arguments, var v = new Foo<int> (), class Foo<T> {}
1159 if (type is InflatedTypeSpec) {
1160 for (; i < targs.Length; ++i)
1161 targs[i] = Inflate (type.TypeArguments[i]);
1163 type = type.GetDefinition ();
1166 // Inflating parent using inside type arguments, class Foo<T> { ITest<T> foo; }
1168 var args = type.MemberDefinition.TypeParameters;
1169 foreach (var ds_tp in args)
1170 targs[i++] = Inflate (ds_tp);
1173 return type.MakeGenericType (targs);
1176 public TypeSpec Inflate (TypeParameterSpec tp)
1178 for (int i = 0; i < tparams.Length; ++i)
1179 if (tparams [i] == tp)
1182 // This can happen when inflating nested types
1183 // without type arguments specified
1189 // Before emitting any code we have to change all MVAR references to VAR
1190 // when the method is of generic type and has hoisted variables
1192 public class TypeParameterMutator
1194 TypeParameter[] mvar;
1195 TypeParameter[] var;
1196 Dictionary<TypeSpec, TypeSpec> mutated_typespec = new Dictionary<TypeSpec, TypeSpec> ();
1198 public TypeParameterMutator (TypeParameter[] mvar, TypeParameter[] var)
1200 if (mvar.Length != var.Length)
1201 throw new ArgumentException ();
1209 public TypeParameter[] MethodTypeParameters {
1217 public static TypeSpec GetMemberDeclaringType (TypeSpec type)
1219 if (type is InflatedTypeSpec) {
1220 if (type.DeclaringType == null)
1221 return type.GetDefinition ();
1223 var parent = GetMemberDeclaringType (type.DeclaringType);
1224 type = MemberCache.GetMember<TypeSpec> (parent, type);
1230 public TypeSpec Mutate (TypeSpec ts)
1233 if (mutated_typespec.TryGetValue (ts, out value))
1236 value = ts.Mutate (this);
1237 mutated_typespec.Add (ts, value);
1241 public TypeParameterSpec Mutate (TypeParameterSpec tp)
1243 for (int i = 0; i < mvar.Length; ++i) {
1244 if (mvar[i].Type == tp)
1251 public TypeSpec[] Mutate (TypeSpec[] targs)
1253 TypeSpec[] mutated = new TypeSpec[targs.Length];
1254 bool changed = false;
1255 for (int i = 0; i < targs.Length; ++i) {
1256 mutated[i] = Mutate (targs[i]);
1257 changed |= targs[i] != mutated[i];
1260 return changed ? mutated : targs;
1265 /// A TypeExpr which already resolved to a type parameter.
1267 public class TypeParameterExpr : TypeExpr {
1269 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1271 this.type = type_parameter.Type;
1272 this.eclass = ExprClass.TypeParameter;
1276 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
1278 throw new NotSupportedException ();
1281 public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
1286 public override bool CheckAccessLevel (IMemberContext ds)
1292 public class InflatedTypeSpec : TypeSpec
1295 TypeParameterSpec[] constraints;
1296 readonly TypeSpec open_type;
1298 public InflatedTypeSpec (TypeSpec openType, TypeSpec declaringType, TypeSpec[] targs)
1299 : base (openType.Kind, declaringType, openType.MemberDefinition, null, openType.Modifiers)
1302 throw new ArgumentNullException ("targs");
1304 // this.state = openType.state;
1305 this.open_type = openType;
1308 foreach (var arg in targs) {
1309 if (arg.HasDynamicElement || arg == InternalType.Dynamic) {
1310 state |= StateFlags.HasDynamicElement;
1318 public override TypeSpec BaseType {
1320 if (cache == null || (state & StateFlags.PendingBaseTypeInflate) != 0)
1321 InitializeMemberCache (true);
1323 return base.BaseType;
1328 // Inflated type parameters with constraints array, mapping with type arguments is based on index
1330 public TypeParameterSpec[] Constraints {
1332 if (constraints == null) {
1333 constraints = TypeParameterSpec.InflateConstraints (MemberDefinition.TypeParameters, l => l.CreateLocalInflator (), this);
1340 public override IList<TypeSpec> Interfaces {
1343 InitializeMemberCache (true);
1345 return base.Interfaces;
1350 // Types used to inflate the generic type
1352 public override TypeSpec[] TypeArguments {
1360 TypeParameterInflator CreateLocalInflator ()
1362 TypeParameterSpec[] tparams_full;
1363 TypeSpec[] targs_full = targs;
1366 // Special case is needed when we are inflating an open type (nested type definition)
1367 // on inflated parent. Consider following case
1369 // Foo<T>.Bar<U> => Foo<string>.Bar<U>
1371 // Any later inflation of Foo<string>.Bar<U> has to also inflate T if used inside Bar<U>
1373 List<TypeSpec> merged_targs = null;
1374 List<TypeParameterSpec> merged_tparams = null;
1376 var type = DeclaringType;
1379 if (type.TypeArguments.Length > 0) {
1380 if (merged_targs == null) {
1381 merged_targs = new List<TypeSpec> ();
1382 merged_tparams = new List<TypeParameterSpec> ();
1383 if (targs.Length > 0) {
1384 merged_targs.AddRange (targs);
1385 merged_tparams.AddRange (open_type.MemberDefinition.TypeParameters);
1388 merged_tparams.AddRange (type.MemberDefinition.TypeParameters);
1389 merged_targs.AddRange (type.TypeArguments);
1391 type = type.DeclaringType;
1392 } while (type != null);
1394 if (merged_targs != null) {
1395 // Type arguments are not in the right order but it should not matter in this case
1396 targs_full = merged_targs.ToArray ();
1397 tparams_full = merged_tparams.ToArray ();
1398 } else if (targs.Length == 0) {
1399 tparams_full = TypeParameterSpec.EmptyTypes;
1401 tparams_full = open_type.MemberDefinition.TypeParameters;
1403 } else if (targs.Length == 0) {
1404 tparams_full = TypeParameterSpec.EmptyTypes;
1406 tparams_full = open_type.MemberDefinition.TypeParameters;
1409 return new TypeParameterInflator (this, tparams_full, targs_full);
1412 Type CreateMetaInfo (TypeParameterMutator mutator)
1415 // Converts nested type arguments into right order
1416 // Foo<string, bool>.Bar<int> => string, bool, int
1418 var all = new List<Type> ();
1419 TypeSpec type = this;
1420 TypeSpec definition = type;
1422 if (type.GetDefinition().IsGeneric) {
1424 type.TypeArguments != TypeSpec.EmptyTypes ?
1425 type.TypeArguments.Select (l => l.GetMetaInfo ()) :
1426 type.MemberDefinition.TypeParameters.Select (l => l.GetMetaInfo ()));
1429 definition = definition.GetDefinition ();
1430 type = type.DeclaringType;
1431 } while (type != null);
1433 return definition.GetMetaInfo ().MakeGenericType (all.ToArray ());
1436 public override ObsoleteAttribute GetAttributeObsolete ()
1438 return open_type.GetAttributeObsolete ();
1441 protected override bool IsNotCLSCompliant ()
1443 if (base.IsNotCLSCompliant ())
1446 foreach (var ta in TypeArguments) {
1447 if (ta.MemberDefinition.IsNotCLSCompliant ())
1454 public override TypeSpec GetDefinition ()
1459 public override Type GetMetaInfo ()
1462 info = CreateMetaInfo (null);
1467 public override string GetSignatureForError ()
1469 if (TypeManager.IsNullableType (open_type))
1470 return targs[0].GetSignatureForError () + "?";
1472 return base.GetSignatureForError ();
1475 protected override string GetTypeNameSignature ()
1477 if (targs.Length == 0 || MemberDefinition is AnonymousTypeClass)
1480 return "<" + TypeManager.CSharpName (targs) + ">";
1483 protected override void InitializeMemberCache (bool onlyTypes)
1486 cache = new MemberCache (onlyTypes ? open_type.MemberCacheTypes : open_type.MemberCache);
1488 var inflator = CreateLocalInflator ();
1491 // Two stage inflate due to possible nested types recursive
1501 // When resolving type of `b' members of `B' cannot be
1502 // inflated because are not yet available in membercache
1504 if ((state & StateFlags.PendingMemberCacheMembers) == 0) {
1505 open_type.MemberCacheTypes.InflateTypes (cache, inflator);
1508 // Inflate any implemented interfaces
1510 if (open_type.Interfaces != null) {
1511 ifaces = new List<TypeSpec> (open_type.Interfaces.Count);
1512 foreach (var iface in open_type.Interfaces) {
1513 var iface_inflated = inflator.Inflate (iface);
1514 AddInterface (iface_inflated);
1519 // Handles the tricky case of recursive nested base generic type
1521 // class A<T> : Base<A<T>.Nested> {
1525 // When inflating A<T>. base type is not yet known, secondary
1526 // inflation is required (not common case) once base scope
1529 if (open_type.BaseType == null) {
1531 state |= StateFlags.PendingBaseTypeInflate;
1533 BaseType = inflator.Inflate (open_type.BaseType);
1535 } else if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1536 BaseType = inflator.Inflate (open_type.BaseType);
1537 state &= ~StateFlags.PendingBaseTypeInflate;
1541 state |= StateFlags.PendingMemberCacheMembers;
1545 var tc = open_type.MemberDefinition as TypeContainer;
1546 if (tc != null && !tc.HasMembersDefined)
1547 throw new InternalErrorException ("Inflating MemberCache with undefined members");
1549 if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1550 BaseType = inflator.Inflate (open_type.BaseType);
1551 state &= ~StateFlags.PendingBaseTypeInflate;
1554 state &= ~StateFlags.PendingMemberCacheMembers;
1555 open_type.MemberCache.InflateMembers (cache, open_type, inflator);
1558 public override TypeSpec Mutate (TypeParameterMutator mutator)
1560 var targs = TypeArguments;
1562 targs = mutator.Mutate (targs);
1564 var decl = DeclaringType;
1565 if (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
1566 decl = mutator.Mutate (decl);
1568 if (targs == TypeArguments && decl == DeclaringType)
1571 var mutated = (InflatedTypeSpec) MemberwiseClone ();
1572 if (decl != DeclaringType) {
1573 // Gets back MethodInfo in case of metaInfo was inflated
1574 //mutated.info = MemberCache.GetMember<TypeSpec> (DeclaringType.GetDefinition (), this).info;
1576 mutated.declaringType = decl;
1577 mutated.state |= StateFlags.PendingMetaInflate;
1580 if (targs != null) {
1581 mutated.targs = targs;
1582 mutated.info = null;
1591 // Tracks the type arguments when instantiating a generic type. It's used
1592 // by both type arguments and type parameters
1594 public class TypeArguments
1596 List<FullNamedExpression> args;
1599 public TypeArguments (params FullNamedExpression[] types)
1601 this.args = new List<FullNamedExpression> (types);
1604 public void Add (FullNamedExpression type)
1609 // TODO: Kill this monster
1610 public TypeParameterName[] GetDeclarations ()
1612 return args.ConvertAll (i => (TypeParameterName) i).ToArray ();
1616 /// We may only be used after Resolve() is called and return the fully
1619 // TODO: Not needed, just return type from resolve
1620 public TypeSpec[] Arguments {
1632 public virtual bool IsEmpty {
1638 public string GetSignatureForError()
1640 StringBuilder sb = new StringBuilder ();
1641 for (int i = 0; i < Count; ++i) {
1644 sb.Append (expr.GetSignatureForError ());
1650 return sb.ToString ();
1654 /// Resolve the type arguments.
1656 public virtual bool Resolve (IMemberContext ec)
1659 return atypes.Length != 0;
1661 int count = args.Count;
1664 atypes = new TypeSpec [count];
1666 for (int i = 0; i < count; i++){
1667 TypeExpr te = args[i].ResolveAsTypeTerminal (ec, false);
1673 atypes[i] = te.Type;
1675 if (te.Type.IsStatic) {
1676 ec.Compiler.Report.Error (718, te.Location, "`{0}': static classes cannot be used as generic arguments",
1677 te.GetSignatureForError ());
1681 if (te.Type.IsPointer || TypeManager.IsSpecialType (te.Type)) {
1682 ec.Compiler.Report.Error (306, te.Location,
1683 "The type `{0}' may not be used as a type argument",
1684 te.GetSignatureForError ());
1690 atypes = TypeSpec.EmptyTypes;
1695 public TypeArguments Clone ()
1697 TypeArguments copy = new TypeArguments ();
1698 foreach (var ta in args)
1705 public class UnboundTypeArguments : TypeArguments
1707 public UnboundTypeArguments (int arity)
1708 : base (new FullNamedExpression[arity])
1712 public override bool IsEmpty {
1718 public override bool Resolve (IMemberContext ec)
1720 // Nothing to be resolved
1725 public class TypeParameterName : SimpleName
1727 Attributes attributes;
1730 public TypeParameterName (string name, Attributes attrs, Location loc)
1731 : this (name, attrs, Variance.None, loc)
1735 public TypeParameterName (string name, Attributes attrs, Variance variance, Location loc)
1739 this.variance = variance;
1742 public Attributes OptAttributes {
1748 public Variance Variance {
1756 // A type expression of generic type with type arguments
1758 class GenericTypeExpr : TypeExpr
1762 bool constraints_checked;
1765 /// Instantiate the generic type `t' with the type arguments `args'.
1766 /// Use this constructor if you already know the fully resolved
1769 public GenericTypeExpr (TypeSpec open_type, TypeArguments args, Location l)
1771 this.open_type = open_type;
1776 public TypeArguments TypeArguments {
1777 get { return args; }
1780 public override string GetSignatureForError ()
1782 return TypeManager.CSharpName (type);
1785 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
1787 if (!args.Resolve (ec))
1790 TypeSpec[] atypes = args.Arguments;
1793 // Now bind the parameters
1795 type = open_type.MakeGenericType (atypes);
1798 // Check constraints when context is not method/base type
1800 if (!ec.HasUnresolvedConstraints)
1801 CheckConstraints (ec);
1807 // Checks the constraints of open generic type against type
1808 // arguments. Has to be called after all members have been defined
1810 public bool CheckConstraints (IMemberContext ec)
1812 if (constraints_checked)
1815 constraints_checked = true;
1817 var gtype = (InflatedTypeSpec) type;
1818 var constraints = gtype.Constraints;
1819 if (constraints == null)
1822 return new ConstraintChecker(ec).CheckAll (open_type, args.Arguments, constraints, loc);
1825 public override bool CheckAccessLevel (IMemberContext mc)
1827 DeclSpace c = mc.CurrentMemberDefinition as DeclSpace;
1829 c = mc.CurrentMemberDefinition.Parent;
1831 return c.CheckAccessLevel (open_type);
1834 public bool HasDynamicArguments ()
1836 return HasDynamicArguments (args.Arguments);
1839 static bool HasDynamicArguments (TypeSpec[] args)
1841 for (int i = 0; i < args.Length; ++i) {
1844 if (item == InternalType.Dynamic)
1847 if (TypeManager.IsGenericType (item))
1848 return HasDynamicArguments (TypeManager.GetTypeArguments (item));
1851 while (item.IsArray) {
1852 item = ((ArrayContainer) item).Element;
1855 if (item == InternalType.Dynamic)
1863 public override bool Equals (object obj)
1865 GenericTypeExpr cobj = obj as GenericTypeExpr;
1869 if ((type == null) || (cobj.type == null))
1872 return type == cobj.type;
1875 public override int GetHashCode ()
1877 return base.GetHashCode ();
1882 // Generic type with unbound type arguments, used for typeof (G<,,>)
1884 class GenericOpenTypeExpr : TypeExpr
1886 public GenericOpenTypeExpr (TypeSpec type, /*UnboundTypeArguments args,*/ Location loc)
1888 this.type = type.GetDefinition ();
1892 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
1898 struct ConstraintChecker
1901 bool ignore_inferred_dynamic;
1903 public ConstraintChecker (IMemberContext ctx)
1906 ignore_inferred_dynamic = false;
1911 public bool IgnoreInferredDynamic {
1913 return ignore_inferred_dynamic;
1916 ignore_inferred_dynamic = value;
1923 // Checks all type arguments againts type parameters constraints
1924 // NOTE: It can run in probing mode when `mc' is null
1926 public bool CheckAll (MemberSpec context, TypeSpec[] targs, TypeParameterSpec[] tparams, Location loc)
1928 for (int i = 0; i < tparams.Length; i++) {
1929 if (ignore_inferred_dynamic && targs[i] == InternalType.Dynamic)
1932 if (!CheckConstraint (context, targs [i], tparams [i], loc))
1939 bool CheckConstraint (MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, Location loc)
1942 // First, check the `class' and `struct' constraints.
1944 if (tparam.HasSpecialClass && !TypeManager.IsReferenceType (atype)) {
1946 mc.Compiler.Report.Error (452, loc,
1947 "The type `{0}' must be a reference type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
1948 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
1954 if (tparam.HasSpecialStruct && (!TypeManager.IsValueType (atype) || TypeManager.IsNullableType (atype))) {
1956 mc.Compiler.Report.Error (453, loc,
1957 "The type `{0}' must be a non-nullable value type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
1958 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
1967 // Check the class constraint
1969 if (tparam.HasTypeConstraint) {
1970 if (!CheckConversion (mc, context, atype, tparam, tparam.BaseType, loc)) {
1979 // Check the interfaces constraints
1981 if (tparam.Interfaces != null) {
1982 if (TypeManager.IsNullableType (atype)) {
1986 mc.Compiler.Report.Error (313, loc,
1987 "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. The nullable type `{0}' never satisfies interface constraint",
1988 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
1991 foreach (TypeSpec iface in tparam.Interfaces) {
1992 if (!CheckConversion (mc, context, atype, tparam, iface, loc)) {
2003 // Check the type parameter constraint
2005 if (tparam.TypeArguments != null) {
2006 foreach (var ta in tparam.TypeArguments) {
2007 if (!CheckConversion (mc, context, atype, tparam, ta, loc)) {
2017 // Finally, check the constructor constraint.
2019 if (!tparam.HasSpecialConstructor)
2022 if (!HasDefaultConstructor (atype)) {
2024 mc.Compiler.Report.SymbolRelatedToPreviousError (atype);
2025 mc.Compiler.Report.Error (310, loc,
2026 "The type `{0}' must have a public parameterless constructor in order to use it as parameter `{1}' in the generic type or method `{2}'",
2027 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2035 static bool HasDynamicTypeArgument (TypeSpec[] targs)
2037 for (int i = 0; i < targs.Length; ++i) {
2038 var targ = targs [i];
2039 if (targ == InternalType.Dynamic)
2042 if (HasDynamicTypeArgument (targ.TypeArguments))
2049 bool CheckConversion (IMemberContext mc, MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, TypeSpec ttype, Location loc)
2051 if (TypeManager.IsValueType (atype)) {
2052 if (atype == ttype || Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
2055 var expr = new EmptyExpression (atype);
2057 if (atype.IsGenericParameter) {
2058 if (Convert.ImplicitTypeParameterConversion (expr, ttype) != null)
2062 if (Convert.ImplicitStandardConversionExists (expr, ttype))
2067 // When partial/full type inference finds a dynamic type argument delay
2068 // the constraint check to runtime, it can succeed for real underlying
2071 if (ignore_inferred_dynamic && HasDynamicTypeArgument (ttype.TypeArguments))
2075 mc.Compiler.Report.SymbolRelatedToPreviousError (tparam);
2076 if (TypeManager.IsValueType (atype)) {
2077 mc.Compiler.Report.Error (315, loc,
2078 "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. There is no boxing conversion from `{0}' to `{3}'",
2079 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2080 } else if (atype.IsGenericParameter) {
2081 mc.Compiler.Report.Error (314, loc,
2082 "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. There is no boxing or type parameter conversion from `{0}' to `{3}'",
2083 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2085 mc.Compiler.Report.Error (311, loc,
2086 "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. There is no implicit reference conversion from `{0}' to `{3}'",
2087 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2094 bool HasDefaultConstructor (TypeSpec atype)
2096 var tp = atype as TypeParameterSpec;
2098 return tp.HasSpecialConstructor || tp.HasSpecialStruct;
2101 if (atype.IsStruct || atype.IsEnum)
2104 if (atype.IsAbstract)
2107 var tdef = atype.GetDefinition ();
2110 // In some circumstances MemberCache is not yet populated and members
2111 // cannot be defined yet (recursive type new constraints)
2113 // class A<T> where T : B<T>, new () {}
2114 // class B<T> where T : A<T>, new () {}
2116 var tc = tdef.MemberDefinition as Class;
2118 if (tc.InstanceConstructors == null) {
2119 // Default ctor will be generated later
2123 foreach (var c in tc.InstanceConstructors) {
2124 if (c.ParameterInfo.IsEmpty) {
2125 if ((c.ModFlags & Modifiers.PUBLIC) != 0)
2133 var found = MemberCache.FindMember (tdef,
2134 MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters),
2135 BindingRestriction.DeclaredOnly | BindingRestriction.InstanceOnly);
2137 return found != null && (found.Modifiers & Modifiers.PUBLIC) != 0;
2142 /// A generic method definition.
2144 public class GenericMethod : DeclSpace
2146 ParametersCompiled parameters;
2148 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
2149 FullNamedExpression return_type, ParametersCompiled parameters)
2150 : base (ns, parent, name, null)
2152 this.parameters = parameters;
2155 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name, TypeParameter[] tparams,
2156 FullNamedExpression return_type, ParametersCompiled parameters)
2157 : this (ns, parent, name, return_type, parameters)
2159 this.type_params = tparams;
2162 public override TypeParameter[] CurrentTypeParameters {
2164 return base.type_params;
2168 public override TypeBuilder DefineType ()
2170 throw new Exception ();
2173 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2175 throw new NotSupportedException ();
2178 public override bool Define ()
2180 throw new NotSupportedException ();
2184 /// Define and resolve the type parameters.
2185 /// We're called from Method.Define().
2187 public bool Define (MethodOrOperator m)
2189 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
2190 string[] snames = new string [names.Length];
2191 var block = m.Block;
2192 for (int i = 0; i < names.Length; i++) {
2193 string type_argument_name = names[i].Name;
2195 if (block == null) {
2196 int idx = parameters.GetParameterIndexByName (type_argument_name);
2200 b = new ToplevelBlock (Compiler, Location);
2202 b.Error_AlreadyDeclaredTypeParameter (type_argument_name, parameters[i].Location);
2205 INamedBlockVariable variable = null;
2206 block.GetLocalName (type_argument_name, m.Block, ref variable);
2207 if (variable != null)
2208 variable.Block.Error_AlreadyDeclaredTypeParameter (type_argument_name, variable.Location);
2211 snames[i] = type_argument_name;
2214 GenericTypeParameterBuilder[] gen_params = m.MethodBuilder.DefineGenericParameters (snames);
2215 for (int i = 0; i < TypeParameters.Length; i++)
2216 TypeParameters [i].Define (gen_params [i], null);
2221 public void EmitAttributes ()
2223 if (OptAttributes != null)
2224 OptAttributes.Emit ();
2227 public override string GetSignatureForError ()
2229 return base.GetSignatureForError () + parameters.GetSignatureForError ();
2232 public override AttributeTargets AttributeTargets {
2234 return AttributeTargets.Method | AttributeTargets.ReturnValue;
2238 public override string DocCommentHeader {
2239 get { return "M:"; }
2242 public new void VerifyClsCompliance ()
2244 foreach (TypeParameter tp in TypeParameters) {
2245 tp.VerifyClsCompliance ();
2250 public partial class TypeManager
2252 public static Variance CheckTypeVariance (TypeSpec t, Variance expected, IMemberContext member)
2254 var tp = t as TypeParameterSpec;
2256 Variance v = tp.Variance;
2257 if (expected == Variance.None && v != expected ||
2258 expected == Variance.Covariant && v == Variance.Contravariant ||
2259 expected == Variance.Contravariant && v == Variance.Covariant) {
2260 ((TypeParameter)tp.MemberDefinition).ErrorInvalidVariance (member, expected);
2266 if (t.TypeArguments.Length > 0) {
2267 var targs_definition = t.MemberDefinition.TypeParameters;
2268 TypeSpec[] targs = GetTypeArguments (t);
2269 for (int i = 0; i < targs.Length; ++i) {
2270 Variance v = targs_definition[i].Variance;
2271 CheckTypeVariance (targs[i], (Variance) ((int)v * (int)expected), member);
2278 return CheckTypeVariance (GetElementType (t), expected, member);
2280 return Variance.None;
2285 // Implements C# type inference
2290 // Tracks successful rate of type inference
2292 int score = int.MaxValue;
2293 readonly Arguments arguments;
2294 readonly int arg_count;
2296 public TypeInference (Arguments arguments)
2298 this.arguments = arguments;
2299 if (arguments != null)
2300 arg_count = arguments.Count;
2303 public int InferenceScore {
2309 public TypeSpec[] InferMethodArguments (ResolveContext ec, MethodSpec method)
2311 var method_generic_args = method.GenericDefinition.TypeParameters;
2312 TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2313 if (!context.UnfixedVariableExists)
2314 return TypeSpec.EmptyTypes;
2316 AParametersCollection pd = method.Parameters;
2317 if (!InferInPhases (ec, context, pd))
2320 return context.InferredTypeArguments;
2324 // Implements method type arguments inference
2326 bool InferInPhases (ResolveContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
2328 int params_arguments_start;
2329 if (methodParameters.HasParams) {
2330 params_arguments_start = methodParameters.Count - 1;
2332 params_arguments_start = arg_count;
2335 TypeSpec [] ptypes = methodParameters.Types;
2338 // The first inference phase
2340 TypeSpec method_parameter = null;
2341 for (int i = 0; i < arg_count; i++) {
2342 Argument a = arguments [i];
2346 if (i < params_arguments_start) {
2347 method_parameter = methodParameters.Types [i];
2348 } else if (i == params_arguments_start) {
2349 if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2350 method_parameter = methodParameters.Types [params_arguments_start];
2352 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2354 ptypes = (TypeSpec[]) ptypes.Clone ();
2355 ptypes [i] = method_parameter;
2359 // When a lambda expression, an anonymous method
2360 // is used an explicit argument type inference takes a place
2362 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2364 if (am.ExplicitTypeInference (ec, tic, method_parameter))
2370 score -= tic.ExactInference (a.Type, method_parameter);
2374 if (a.Expr.Type == InternalType.Null)
2377 if (TypeManager.IsValueType (method_parameter)) {
2378 score -= tic.LowerBoundInference (a.Type, method_parameter);
2383 // Otherwise an output type inference is made
2385 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2389 // Part of the second phase but because it happens only once
2390 // we don't need to call it in cycle
2392 bool fixed_any = false;
2393 if (!tic.FixIndependentTypeArguments (ec, ptypes, ref fixed_any))
2396 return DoSecondPhase (ec, tic, ptypes, !fixed_any);
2399 bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, TypeSpec[] methodParameters, bool fixDependent)
2401 bool fixed_any = false;
2402 if (fixDependent && !tic.FixDependentTypes (ec, ref fixed_any))
2405 // If no further unfixed type variables exist, type inference succeeds
2406 if (!tic.UnfixedVariableExists)
2409 if (!fixed_any && fixDependent)
2412 // For all arguments where the corresponding argument output types
2413 // contain unfixed type variables but the input types do not,
2414 // an output type inference is made
2415 for (int i = 0; i < arg_count; i++) {
2417 // Align params arguments
2418 TypeSpec t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
2420 if (!TypeManager.IsDelegateType (t_i)) {
2421 if (t_i.GetDefinition () != TypeManager.expression_type)
2424 t_i = TypeManager.GetTypeArguments (t_i) [0];
2427 var mi = Delegate.GetInvokeMethod (ec.Compiler, t_i);
2428 TypeSpec rtype = mi.ReturnType;
2430 if (tic.IsReturnTypeNonDependent (ec, mi, rtype))
2431 score -= tic.OutputTypeInference (ec, arguments [i].Expr, t_i);
2435 return DoSecondPhase (ec, tic, methodParameters, true);
2439 public class TypeInferenceContext
2448 class BoundInfo : IEquatable<BoundInfo>
2450 public readonly TypeSpec Type;
2451 public readonly BoundKind Kind;
2453 public BoundInfo (TypeSpec type, BoundKind kind)
2459 public override int GetHashCode ()
2461 return Type.GetHashCode ();
2464 #region IEquatable<BoundInfo> Members
2466 public bool Equals (BoundInfo other)
2468 return Type == other.Type && Kind == other.Kind;
2474 readonly TypeSpec[] tp_args;
2475 readonly TypeSpec[] fixed_types;
2476 readonly List<BoundInfo>[] bounds;
2479 // TODO MemberCache: Could it be TypeParameterSpec[] ??
2480 public TypeInferenceContext (TypeSpec[] typeArguments)
2482 if (typeArguments.Length == 0)
2483 throw new ArgumentException ("Empty generic arguments");
2485 fixed_types = new TypeSpec [typeArguments.Length];
2486 for (int i = 0; i < typeArguments.Length; ++i) {
2487 if (typeArguments [i].IsGenericParameter) {
2488 if (bounds == null) {
2489 bounds = new List<BoundInfo> [typeArguments.Length];
2490 tp_args = new TypeSpec [typeArguments.Length];
2492 tp_args [i] = typeArguments [i];
2494 fixed_types [i] = typeArguments [i];
2500 // Used together with AddCommonTypeBound fo implement
2501 // 7.4.2.13 Finding the best common type of a set of expressions
2503 public TypeInferenceContext ()
2505 fixed_types = new TypeSpec [1];
2506 tp_args = new TypeSpec [1];
2507 tp_args[0] = InternalType.Arglist; // it can be any internal type
2508 bounds = new List<BoundInfo> [1];
2511 public TypeSpec[] InferredTypeArguments {
2517 public void AddCommonTypeBound (TypeSpec type)
2519 AddToBounds (new BoundInfo (type, BoundKind.Lower), 0);
2522 void AddToBounds (BoundInfo bound, int index)
2525 // Some types cannot be used as type arguments
2527 if (bound.Type == TypeManager.void_type || bound.Type.IsPointer)
2530 var a = bounds [index];
2532 a = new List<BoundInfo> (2);
2538 if (a.Contains (bound))
2544 bool AllTypesAreFixed (TypeSpec[] types)
2546 foreach (TypeSpec t in types) {
2547 if (t.IsGenericParameter) {
2553 if (TypeManager.IsGenericType (t))
2554 return AllTypesAreFixed (TypeManager.GetTypeArguments (t));
2561 // 26.3.3.8 Exact Inference
2563 public int ExactInference (TypeSpec u, TypeSpec v)
2565 // If V is an array type
2570 // TODO MemberCache: GetMetaInfo ()
2571 if (u.GetMetaInfo ().GetArrayRank () != v.GetMetaInfo ().GetArrayRank ())
2574 return ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
2577 // If V is constructed type and U is constructed type
2578 if (TypeManager.IsGenericType (v)) {
2579 if (!TypeManager.IsGenericType (u))
2582 TypeSpec [] ga_u = TypeManager.GetTypeArguments (u);
2583 TypeSpec [] ga_v = TypeManager.GetTypeArguments (v);
2584 if (ga_u.Length != ga_v.Length)
2588 for (int i = 0; i < ga_u.Length; ++i)
2589 score += ExactInference (ga_u [i], ga_v [i]);
2591 return score > 0 ? 1 : 0;
2594 // If V is one of the unfixed type arguments
2595 int pos = IsUnfixed (v);
2599 AddToBounds (new BoundInfo (u, BoundKind.Exact), pos);
2603 public bool FixAllTypes (ResolveContext ec)
2605 for (int i = 0; i < tp_args.Length; ++i) {
2606 if (!FixType (ec, i))
2613 // All unfixed type variables Xi are fixed for which all of the following hold:
2614 // a, There is at least one type variable Xj that depends on Xi
2615 // b, Xi has a non-empty set of bounds
2617 public bool FixDependentTypes (ResolveContext ec, ref bool fixed_any)
2619 for (int i = 0; i < tp_args.Length; ++i) {
2620 if (fixed_types[i] != null)
2623 if (bounds[i] == null)
2626 if (!FixType (ec, i))
2636 // All unfixed type variables Xi which depend on no Xj are fixed
2638 public bool FixIndependentTypeArguments (ResolveContext ec, TypeSpec[] methodParameters, ref bool fixed_any)
2640 var types_to_fix = new List<TypeSpec> (tp_args);
2641 for (int i = 0; i < methodParameters.Length; ++i) {
2642 TypeSpec t = methodParameters[i];
2644 if (!TypeManager.IsDelegateType (t)) {
2645 if (TypeManager.expression_type == null || t.MemberDefinition != TypeManager.expression_type.MemberDefinition)
2648 t = TypeManager.GetTypeArguments (t) [0];
2651 if (t.IsGenericParameter)
2654 var invoke = Delegate.GetInvokeMethod (ec.Compiler, t);
2655 TypeSpec rtype = invoke.ReturnType;
2656 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
2659 // Remove dependent types, they cannot be fixed yet
2660 RemoveDependentTypes (types_to_fix, rtype);
2663 foreach (TypeSpec t in types_to_fix) {
2667 int idx = IsUnfixed (t);
2668 if (idx >= 0 && !FixType (ec, idx)) {
2673 fixed_any = types_to_fix.Count > 0;
2680 public bool FixType (ResolveContext ec, int i)
2682 // It's already fixed
2683 if (fixed_types[i] != null)
2684 throw new InternalErrorException ("Type argument has been already fixed");
2689 var candidates = bounds [i];
2690 if (candidates == null)
2693 if (candidates.Count == 1) {
2694 TypeSpec t = candidates[0].Type;
2695 if (t == InternalType.Null)
2698 fixed_types [i] = t;
2703 // Determines a unique type from which there is
2704 // a standard implicit conversion to all the other
2707 TypeSpec best_candidate = null;
2709 int candidates_count = candidates.Count;
2710 for (int ci = 0; ci < candidates_count; ++ci) {
2711 BoundInfo bound = candidates [ci];
2712 for (cii = 0; cii < candidates_count; ++cii) {
2716 BoundInfo cbound = candidates[cii];
2718 // Same type parameters with different bounds
2719 if (cbound.Type == bound.Type) {
2720 if (bound.Kind != BoundKind.Exact)
2726 if (bound.Kind == BoundKind.Exact || cbound.Kind == BoundKind.Exact) {
2727 if (cbound.Kind == BoundKind.Lower) {
2728 if (!Convert.ImplicitConversionExists (ec, new TypeExpression (cbound.Type, Location.Null), bound.Type)) {
2734 if (cbound.Kind == BoundKind.Upper) {
2735 if (!Convert.ImplicitConversionExists (ec, new TypeExpression (bound.Type, Location.Null), cbound.Type)) {
2742 if (bound.Kind != BoundKind.Exact) {
2743 if (!Convert.ImplicitConversionExists (ec, new TypeExpression (bound.Type, Location.Null), cbound.Type)) {
2754 if (bound.Kind == BoundKind.Lower) {
2755 if (cbound.Kind == BoundKind.Lower) {
2756 if (!Convert.ImplicitConversionExists (ec, new TypeExpression (cbound.Type, Location.Null), bound.Type)) {
2760 if (!Convert.ImplicitConversionExists (ec, new TypeExpression (bound.Type, Location.Null), cbound.Type)) {
2770 if (bound.Kind == BoundKind.Upper) {
2771 if (!Convert.ImplicitConversionExists (ec, new TypeExpression (bound.Type, Location.Null), cbound.Type)) {
2775 throw new NotImplementedException ("variance conversion");
2779 if (cii != candidates_count)
2783 // We already have the best candidate, break if thet are different
2785 // Dynamic is never ambiguous as we prefer dynamic over other best candidate types
2787 if (best_candidate != null) {
2789 if (best_candidate == InternalType.Dynamic)
2792 if (bound.Type != InternalType.Dynamic && best_candidate != bound.Type)
2796 best_candidate = bound.Type;
2799 if (best_candidate == null)
2802 fixed_types[i] = best_candidate;
2807 // Uses inferred or partially infered types to inflate delegate type argument. Returns
2808 // null when type parameter has not been fixed
2810 public TypeSpec InflateGenericArgument (TypeSpec parameter)
2812 var tp = parameter as TypeParameterSpec;
2815 // Type inference works on generic arguments (MVAR) only
2817 if (!tp.IsMethodOwned)
2821 // Ensure the type parameter belongs to same container
2823 if (tp.DeclaredPosition < tp_args.Length && tp_args[tp.DeclaredPosition] == parameter)
2824 return fixed_types[tp.DeclaredPosition] ?? parameter;
2829 var gt = parameter as InflatedTypeSpec;
2831 var inflated_targs = new TypeSpec [gt.TypeArguments.Length];
2832 for (int ii = 0; ii < inflated_targs.Length; ++ii) {
2833 var inflated = InflateGenericArgument (gt.TypeArguments [ii]);
2834 if (inflated == null)
2837 inflated_targs[ii] = inflated;
2840 return gt.GetDefinition ().MakeGenericType (inflated_targs);
2847 // Tests whether all delegate input arguments are fixed and generic output type
2848 // requires output type inference
2850 public bool IsReturnTypeNonDependent (ResolveContext ec, MethodSpec invoke, TypeSpec returnType)
2852 if (returnType.IsGenericParameter) {
2853 if (IsFixed (returnType))
2855 } else if (TypeManager.IsGenericType (returnType)) {
2856 if (TypeManager.IsDelegateType (returnType)) {
2857 invoke = Delegate.GetInvokeMethod (ec.Compiler, returnType);
2858 return IsReturnTypeNonDependent (ec, invoke, invoke.ReturnType);
2861 TypeSpec[] g_args = TypeManager.GetTypeArguments (returnType);
2863 // At least one unfixed return type has to exist
2864 if (AllTypesAreFixed (g_args))
2870 // All generic input arguments have to be fixed
2871 AParametersCollection d_parameters = invoke.Parameters;
2872 return AllTypesAreFixed (d_parameters.Types);
2875 bool IsFixed (TypeSpec type)
2877 return IsUnfixed (type) == -1;
2880 int IsUnfixed (TypeSpec type)
2882 if (!type.IsGenericParameter)
2885 for (int i = 0; i < tp_args.Length; ++i) {
2886 if (tp_args[i] == type) {
2887 if (fixed_types[i] != null)
2898 // 26.3.3.9 Lower-bound Inference
2900 public int LowerBoundInference (TypeSpec u, TypeSpec v)
2902 return LowerBoundInference (u, v, false);
2906 // Lower-bound (false) or Upper-bound (true) inference based on inversed argument
2908 int LowerBoundInference (TypeSpec u, TypeSpec v, bool inversed)
2910 // If V is one of the unfixed type arguments
2911 int pos = IsUnfixed (v);
2913 AddToBounds (new BoundInfo (u, inversed ? BoundKind.Upper : BoundKind.Lower), pos);
2917 // If U is an array type
2918 var u_ac = u as ArrayContainer;
2920 var v_ac = v as ArrayContainer;
2922 if (u_ac.Rank != v_ac.Rank)
2925 if (TypeManager.IsValueType (u_ac.Element))
2926 return ExactInference (u_ac.Element, v_ac.Element);
2928 return LowerBoundInference (u_ac.Element, v_ac.Element, inversed);
2934 if (TypeManager.IsGenericType (v)) {
2935 TypeSpec g_v = v.GetDefinition ();
2936 if (g_v != TypeManager.generic_ilist_type &&
2937 g_v != TypeManager.generic_icollection_type &&
2938 g_v != TypeManager.generic_ienumerable_type)
2941 var v_i = TypeManager.GetTypeArguments (v) [0];
2942 if (TypeManager.IsValueType (u_ac.Element))
2943 return ExactInference (u_ac.Element, v_i);
2945 return LowerBoundInference (u_ac.Element, v_i);
2947 } else if (TypeManager.IsGenericType (v)) {
2949 // if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
2950 // such that U is identical to, inherits from (directly or indirectly),
2951 // or implements (directly or indirectly) C<U1..Uk>
2953 var u_candidates = new List<TypeSpec> ();
2954 var open_v = v.MemberDefinition;
2956 for (TypeSpec t = u; t != null; t = t.BaseType) {
2957 if (open_v == t.MemberDefinition)
2958 u_candidates.Add (t);
2961 // Using this trick for dynamic type inference, the spec says the type arguments are "unknown" but
2962 // that would complicate the process a lot, instead I treat them as dynamic
2964 if (t == InternalType.Dynamic)
2965 u_candidates.Add (t);
2967 if (t.Interfaces != null) {
2968 foreach (var iface in t.Interfaces) {
2969 if (open_v == iface.MemberDefinition)
2970 u_candidates.Add (iface);
2975 TypeSpec [] unique_candidate_targs = null;
2976 TypeSpec[] ga_v = TypeManager.GetTypeArguments (v);
2977 foreach (TypeSpec u_candidate in u_candidates) {
2979 // The unique set of types U1..Uk means that if we have an interface I<T>,
2980 // class U : I<int>, I<long> then no type inference is made when inferring
2981 // type I<T> by applying type U because T could be int or long
2983 if (unique_candidate_targs != null) {
2984 TypeSpec[] second_unique_candidate_targs = TypeManager.GetTypeArguments (u_candidate);
2985 if (TypeSpecComparer.Equals (unique_candidate_targs, second_unique_candidate_targs)) {
2986 unique_candidate_targs = second_unique_candidate_targs;
2991 // This should always cause type inference failure
2998 // A candidate is dynamic type expression, to simplify things use dynamic
2999 // for all type parameter of this type. For methods like this one
3001 // void M<T, U> (IList<T>, IList<U[]>)
3003 // dynamic becomes both T and U when the arguments are of dynamic type
3005 if (u_candidate == InternalType.Dynamic) {
3006 unique_candidate_targs = new TypeSpec[ga_v.Length];
3007 for (int i = 0; i < unique_candidate_targs.Length; ++i)
3008 unique_candidate_targs[i] = u_candidate;
3010 unique_candidate_targs = TypeManager.GetTypeArguments (u_candidate);
3014 if (unique_candidate_targs != null) {
3015 var ga_open_v = open_v.TypeParameters;
3017 for (int i = 0; i < unique_candidate_targs.Length; ++i) {
3018 Variance variance = ga_open_v [i].Variance;
3020 TypeSpec u_i = unique_candidate_targs [i];
3021 if (variance == Variance.None || TypeManager.IsValueType (u_i)) {
3022 if (ExactInference (u_i, ga_v [i]) == 0)
3025 bool upper_bound = (variance == Variance.Contravariant && !inversed) ||
3026 (variance == Variance.Covariant && inversed);
3028 if (LowerBoundInference (u_i, ga_v [i], upper_bound) == 0)
3040 // 26.3.3.6 Output Type Inference
3042 public int OutputTypeInference (ResolveContext ec, Expression e, TypeSpec t)
3044 // If e is a lambda or anonymous method with inferred return type
3045 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
3047 TypeSpec rt = ame.InferReturnType (ec, this, t);
3048 var invoke = Delegate.GetInvokeMethod (ec.Compiler, t);
3051 AParametersCollection pd = invoke.Parameters;
3052 return ame.Parameters.Count == pd.Count ? 1 : 0;
3055 TypeSpec rtype = invoke.ReturnType;
3056 return LowerBoundInference (rt, rtype) + 1;
3060 // if E is a method group and T is a delegate type or expression tree type
3061 // return type Tb with parameter types T1..Tk and return type Tb, and overload
3062 // resolution of E with the types T1..Tk yields a single method with return type U,
3063 // then a lower-bound inference is made from U for Tb.
3065 if (e is MethodGroupExpr) {
3066 if (!TypeManager.IsDelegateType (t)) {
3067 if (TypeManager.expression_type == null || t.MemberDefinition != TypeManager.expression_type.MemberDefinition)
3070 t = TypeManager.GetTypeArguments (t)[0];
3073 var invoke = Delegate.GetInvokeMethod (ec.Compiler, t);
3074 TypeSpec rtype = invoke.ReturnType;
3076 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
3079 // LAMESPEC: Standard does not specify that all methodgroup arguments
3080 // has to be fixed but it does not specify how to do recursive type inference
3081 // either. We choose the simple option and infer return type only
3082 // if all delegate generic arguments are fixed.
3083 TypeSpec[] param_types = new TypeSpec [invoke.Parameters.Count];
3084 for (int i = 0; i < param_types.Length; ++i) {
3085 var inflated = InflateGenericArgument (invoke.Parameters.Types[i]);
3086 if (inflated == null)
3089 if (IsUnfixed (inflated) >= 0)
3092 param_types[i] = inflated;
3095 MethodGroupExpr mg = (MethodGroupExpr) e;
3096 Arguments args = DelegateCreation.CreateDelegateMethodArguments (invoke.Parameters, param_types, e.Location);
3097 mg = mg.OverloadResolve (ec, ref args, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
3101 return LowerBoundInference (mg.BestCandidateReturnType, rtype) + 1;
3105 // if e is an expression with type U, then
3106 // a lower-bound inference is made from U for T
3108 return LowerBoundInference (e.Type, t) * 2;
3111 void RemoveDependentTypes (List<TypeSpec> types, TypeSpec returnType)
3113 int idx = IsUnfixed (returnType);
3119 if (TypeManager.IsGenericType (returnType)) {
3120 foreach (TypeSpec t in TypeManager.GetTypeArguments (returnType)) {
3121 RemoveDependentTypes (types, t);
3126 public bool UnfixedVariableExists {
3128 foreach (TypeSpec ut in fixed_types) {