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.Collections.Generic;
19 using MetaType = IKVM.Reflection.Type;
20 using IKVM.Reflection;
21 using IKVM.Reflection.Emit;
23 using MetaType = System.Type;
24 using System.Reflection;
25 using System.Reflection.Emit;
28 namespace Mono.CSharp {
32 // Don't add or modify internal values, they are used as -/+ calculation signs
40 public enum SpecialConstraint
48 public class SpecialContraintExpr : FullNamedExpression
50 public SpecialContraintExpr (SpecialConstraint constraint, Location loc)
53 this.Constraint = constraint;
56 public SpecialConstraint Constraint { get; private set; }
58 protected override Expression DoResolve (ResolveContext rc)
60 throw new NotImplementedException ();
65 // A set of parsed constraints for a type parameter
67 public class Constraints
69 SimpleMemberName tparam;
70 List<FullNamedExpression> constraints;
75 public Constraints (SimpleMemberName tparam, List<FullNamedExpression> constraints, Location loc)
78 this.constraints = constraints;
84 public Location Location {
90 public SimpleMemberName TypeParameter {
98 public static bool CheckConflictingInheritedConstraint (TypeParameterSpec spec, TypeSpec bb, IMemberContext context, Location loc)
100 if (spec.HasSpecialClass && bb.IsStruct) {
101 context.Compiler.Report.Error (455, loc,
102 "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
103 spec.Name, "class", bb.GetSignatureForError ());
108 return CheckConflictingInheritedConstraint (spec, spec.BaseType, bb, context, loc);
111 static bool CheckConflictingInheritedConstraint (TypeParameterSpec spec, TypeSpec ba, TypeSpec bb, IMemberContext context, Location loc)
116 if (TypeSpec.IsBaseClass (ba, bb, false) || TypeSpec.IsBaseClass (bb, ba, false))
119 context.Compiler.Report.Error (455, loc,
120 "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
121 spec.Name, ba.GetSignatureForError (), bb.GetSignatureForError ());
125 public void CheckGenericConstraints (IMemberContext context)
127 foreach (var c in constraints) {
128 var ge = c as GenericTypeExpr;
130 ge.CheckConstraints (context);
135 // Resolve the constraints types with only possible early checks, return
136 // value `false' is reserved for recursive failure
138 public bool Resolve (IMemberContext context, TypeParameter tp)
148 List<TypeParameterSpec> tparam_types = null;
149 bool iface_found = false;
151 spec.BaseType = TypeManager.object_type;
153 for (int i = 0; i < constraints.Count; ++i) {
154 var constraint = constraints[i];
156 if (constraint is SpecialContraintExpr) {
157 spec.SpecialConstraint |= ((SpecialContraintExpr) constraint).Constraint;
158 if (spec.HasSpecialStruct)
159 spec.BaseType = TypeManager.value_type;
161 // Set to null as it does not have a type
162 constraints[i] = null;
166 var type_expr = constraints[i] = constraint.ResolveAsTypeTerminal (context, false);
167 if (type_expr == null)
170 var gexpr = type_expr as GenericTypeExpr;
171 if (gexpr != null && gexpr.HasDynamicArguments ()) {
172 context.Compiler.Report.Error (1968, constraint.Location,
173 "A constraint cannot be the dynamic type `{0}'", gexpr.GetSignatureForError ());
177 var type = type_expr.Type;
179 if (!context.CurrentMemberDefinition.IsAccessibleAs (type)) {
180 context.Compiler.Report.SymbolRelatedToPreviousError (type);
181 context.Compiler.Report.Error (703, loc,
182 "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
183 type.GetSignatureForError (), context.GetSignatureForError ());
186 if (type.IsInterface) {
187 if (!spec.AddInterface (type)) {
188 context.Compiler.Report.Error (405, constraint.Location,
189 "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
197 var constraint_tp = type as TypeParameterSpec;
198 if (constraint_tp != null) {
199 if (tparam_types == null) {
200 tparam_types = new List<TypeParameterSpec> (2);
201 } else if (tparam_types.Contains (constraint_tp)) {
202 context.Compiler.Report.Error (405, constraint.Location,
203 "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
208 // Checks whether each generic method parameter constraint type
209 // is valid with respect to T
211 if (tp.IsMethodTypeParameter) {
212 TypeManager.CheckTypeVariance (type, Variance.Contravariant, context);
215 var tp_def = constraint_tp.MemberDefinition as TypeParameter;
216 if (tp_def != null && !tp_def.ResolveConstraints (context)) {
217 context.Compiler.Report.Error (454, constraint.Location,
218 "Circular constraint dependency involving `{0}' and `{1}'",
219 constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
224 // Checks whether there are no conflicts between type parameter constraints
230 // A and B are not convertible and only 1 class constraint is allowed
232 if (constraint_tp.HasTypeConstraint) {
233 if (spec.HasTypeConstraint || spec.HasSpecialStruct) {
234 if (!CheckConflictingInheritedConstraint (spec, constraint_tp.BaseType, context, constraint.Location))
237 for (int ii = 0; ii < tparam_types.Count; ++ii) {
238 if (!tparam_types[ii].HasTypeConstraint)
241 if (!CheckConflictingInheritedConstraint (spec, tparam_types[ii].BaseType, constraint_tp.BaseType, context, constraint.Location))
247 if (constraint_tp.HasSpecialStruct) {
248 context.Compiler.Report.Error (456, constraint.Location,
249 "Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
250 constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
254 tparam_types.Add (constraint_tp);
258 if (iface_found || spec.HasTypeConstraint) {
259 context.Compiler.Report.Error (406, constraint.Location,
260 "The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
261 type.GetSignatureForError ());
264 if (spec.HasSpecialStruct || spec.HasSpecialClass) {
265 context.Compiler.Report.Error (450, type_expr.Location,
266 "`{0}': cannot specify both a constraint class and the `class' or `struct' constraint",
267 type.GetSignatureForError ());
270 if (type == InternalType.Dynamic) {
271 context.Compiler.Report.Error (1967, constraint.Location, "A constraint cannot be the dynamic type");
275 if (type.IsSealed || !type.IsClass) {
276 context.Compiler.Report.Error (701, loc,
277 "`{0}' is not a valid constraint. A constraint must be an interface, a non-sealed class or a type parameter",
278 TypeManager.CSharpName (type));
283 context.Compiler.Report.Error (717, constraint.Location,
284 "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
285 type.GetSignatureForError ());
286 } else if (type == TypeManager.array_type || type == TypeManager.delegate_type ||
287 type == TypeManager.enum_type || type == TypeManager.value_type ||
288 type == TypeManager.object_type || type == TypeManager.multicast_delegate_type) {
289 context.Compiler.Report.Error (702, constraint.Location,
290 "A constraint cannot be special class `{0}'", type.GetSignatureForError ());
294 spec.BaseType = type;
297 if (tparam_types != null)
298 spec.TypeArguments = tparam_types.ToArray ();
305 public void VerifyClsCompliance (Report report)
307 foreach (var c in constraints)
312 if (!c.Type.IsCLSCompliant ()) {
313 report.SymbolRelatedToPreviousError (c.Type);
314 report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
315 c.Type.GetSignatureForError ());
322 // A type parameter for a generic type or generic method definition
324 public class TypeParameter : MemberCore, ITypeDefinition
326 static readonly string[] attribute_target = new string [] { "type parameter" };
328 Constraints constraints;
329 GenericTypeParameterBuilder builder;
330 TypeParameterSpec spec;
332 public TypeParameter (DeclSpace parent, int index, MemberName name, Constraints constraints, Attributes attrs, Variance variance)
333 : base (parent, name, attrs)
335 this.constraints = constraints;
336 this.spec = new TypeParameterSpec (null, index, this, SpecialConstraint.None, variance, null);
339 public TypeParameter (TypeParameterSpec spec, DeclSpace parent, TypeSpec parentSpec, MemberName name, Attributes attrs)
340 : base (parent, name, attrs)
342 this.spec = new TypeParameterSpec (parentSpec, spec.DeclaredPosition, spec.MemberDefinition, spec.SpecialConstraint, spec.Variance, null) {
343 BaseType = spec.BaseType,
344 InterfacesDefined = spec.InterfacesDefined,
345 TypeArguments = spec.TypeArguments
351 public override AttributeTargets AttributeTargets {
353 return AttributeTargets.GenericParameter;
357 public IAssemblyDefinition DeclaringAssembly {
359 return Module.DeclaringAssembly;
363 public override string DocCommentHeader {
365 throw new InvalidOperationException (
366 "Unexpected attempt to get doc comment from " + this.GetType ());
370 public bool IsMethodTypeParameter {
372 return spec.IsMethodOwned;
376 public string Namespace {
382 public TypeParameterSpec Type {
388 public int TypeParametersCount {
394 public TypeParameterSpec[] TypeParameters {
400 public override string[] ValidAttributeTargets {
402 return attribute_target;
406 public Variance Variance {
408 return spec.Variance;
415 // This is called for each part of a partial generic type definition.
417 // If partial type parameters constraints are not null and we don't
418 // already have constraints they become our constraints. If we already
419 // have constraints, we must check that they're the same.
421 public bool AddPartialConstraints (TypeContainer part, TypeParameter tp)
424 throw new InvalidOperationException ();
426 var new_constraints = tp.constraints;
427 if (new_constraints == null)
430 // TODO: could create spec only
431 //tp.Define (null, -1, part.Definition);
432 tp.spec.DeclaringType = part.Definition;
433 if (!tp.ResolveConstraints (part))
436 if (constraints != null)
437 return spec.HasSameConstraintsDefinition (tp.Type);
439 // Copy constraint from resolved part to partial container
440 spec.SpecialConstraint = tp.spec.SpecialConstraint;
441 spec.InterfacesDefined = tp.spec.InterfacesDefined;
442 spec.TypeArguments = tp.spec.TypeArguments;
443 spec.BaseType = tp.spec.BaseType;
448 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
450 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
453 public void CheckGenericConstraints ()
455 if (constraints != null)
456 constraints.CheckGenericConstraints (this);
459 public TypeParameter CreateHoistedCopy (TypeContainer declaringType, TypeSpec declaringSpec)
461 return new TypeParameter (spec, declaringType, declaringSpec, MemberName, null);
464 public override bool Define ()
470 // This is the first method which is called during the resolving
471 // process; we're called immediately after creating the type parameters
472 // with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
475 public void Define (GenericTypeParameterBuilder type, TypeSpec declaringType)
478 throw new InternalErrorException ();
481 spec.DeclaringType = declaringType;
482 spec.SetMetaInfo (type);
485 public void EmitConstraints (GenericTypeParameterBuilder builder)
487 var attr = GenericParameterAttributes.None;
488 if (spec.Variance == Variance.Contravariant)
489 attr |= GenericParameterAttributes.Contravariant;
490 else if (spec.Variance == Variance.Covariant)
491 attr |= GenericParameterAttributes.Covariant;
493 if (spec.HasSpecialClass)
494 attr |= GenericParameterAttributes.ReferenceTypeConstraint;
495 else if (spec.HasSpecialStruct)
496 attr |= GenericParameterAttributes.NotNullableValueTypeConstraint | GenericParameterAttributes.DefaultConstructorConstraint;
498 if (spec.HasSpecialConstructor)
499 attr |= GenericParameterAttributes.DefaultConstructorConstraint;
501 if (spec.BaseType != TypeManager.object_type)
502 builder.SetBaseTypeConstraint (spec.BaseType.GetMetaInfo ());
504 if (spec.InterfacesDefined != null)
505 builder.SetInterfaceConstraints (spec.InterfacesDefined.Select (l => l.GetMetaInfo ()).ToArray ());
507 if (spec.TypeArguments != null)
508 builder.SetInterfaceConstraints (spec.TypeArguments.Select (l => l.GetMetaInfo ()).ToArray ());
510 builder.SetGenericParameterAttributes (attr);
513 public override void Emit ()
515 EmitConstraints (builder);
517 if (OptAttributes != null)
518 OptAttributes.Emit ();
523 public void ErrorInvalidVariance (IMemberContext mc, Variance expected)
525 Report.SymbolRelatedToPreviousError (mc.CurrentMemberDefinition);
526 string input_variance = Variance == Variance.Contravariant ? "contravariant" : "covariant";
527 string gtype_variance;
529 case Variance.Contravariant: gtype_variance = "contravariantly"; break;
530 case Variance.Covariant: gtype_variance = "covariantly"; break;
531 default: gtype_variance = "invariantly"; break;
534 Delegate d = mc as Delegate;
535 string parameters = d != null ? d.Parameters.GetSignatureForError () : "";
537 Report.Error (1961, Location,
538 "The {2} type parameter `{0}' must be {3} valid on `{1}{4}'",
539 GetSignatureForError (), mc.GetSignatureForError (), input_variance, gtype_variance, parameters);
542 public TypeSpec GetAttributeCoClass ()
547 public string GetAttributeDefaultMember ()
549 throw new NotSupportedException ();
552 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
554 throw new NotSupportedException ();
557 public override string GetSignatureForError ()
559 return MemberName.Name;
562 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
564 throw new NotImplementedException ();
567 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
569 throw new NotSupportedException ("Not supported for compiled definition");
573 // Resolves all type parameter constraints
575 public bool ResolveConstraints (IMemberContext context)
577 if (constraints != null)
578 return constraints.Resolve (context, this);
580 if (spec.BaseType == null)
581 spec.BaseType = TypeManager.object_type;
586 public static TypeParameter FindTypeParameter (TypeParameter[] tparams, string name)
588 foreach (var tp in tparams) {
596 public override bool IsClsComplianceRequired ()
601 public new void VerifyClsCompliance ()
603 if (constraints != null)
604 constraints.VerifyClsCompliance (Report);
608 [System.Diagnostics.DebuggerDisplay ("{DisplayDebugInfo()}")]
609 public class TypeParameterSpec : TypeSpec
611 public static readonly new TypeParameterSpec[] EmptyTypes = new TypeParameterSpec[0];
614 SpecialConstraint spec;
617 TypeSpec[] ifaces_defined;
620 // Creates type owned type parameter
622 public TypeParameterSpec (TypeSpec declaringType, int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
623 : base (MemberKind.TypeParameter, declaringType, definition, info, Modifiers.PUBLIC)
625 this.variance = variance;
627 state &= ~StateFlags.Obsolete_Undetected;
632 // Creates method owned type parameter
634 public TypeParameterSpec (int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
635 : this (null, index, definition, spec, variance, info)
641 public int DeclaredPosition {
647 public bool HasSpecialConstructor {
649 return (spec & SpecialConstraint.Constructor) != 0;
653 public bool HasSpecialClass {
655 return (spec & SpecialConstraint.Class) != 0;
659 public bool HasSpecialStruct {
661 return (spec & SpecialConstraint.Struct) != 0;
665 public bool HasTypeConstraint {
667 return BaseType != TypeManager.object_type && BaseType != TypeManager.value_type;
671 public override IList<TypeSpec> Interfaces {
673 if ((state & StateFlags.InterfacesExpanded) == 0) {
674 if (ifaces != null) {
675 for (int i = 0; i < ifaces.Count; ++i ) {
676 var iface_type = ifaces[i];
677 if (iface_type.Interfaces != null) {
678 if (ifaces_defined == null)
679 ifaces_defined = ifaces.ToArray ();
681 for (int ii = 0; ii < iface_type.Interfaces.Count; ++ii) {
682 var ii_iface_type = iface_type.Interfaces [ii];
684 AddInterface (ii_iface_type);
690 if (ifaces_defined == null && ifaces != null)
691 ifaces_defined = ifaces.ToArray ();
693 state |= StateFlags.InterfacesExpanded;
701 // Unexpanded interfaces list
703 public TypeSpec[] InterfacesDefined {
705 if (ifaces_defined == null && ifaces != null)
706 ifaces_defined = ifaces.ToArray ();
708 return ifaces_defined;
711 ifaces_defined = value;
715 public bool IsConstrained {
717 return spec != SpecialConstraint.None || ifaces != null || targs != null || HasTypeConstraint;
722 // Returns whether the type parameter is "known to be a reference type"
724 public bool IsReferenceType {
726 if ((spec & SpecialConstraint.Class) != 0 || HasTypeConstraint)
730 foreach (var ta in targs) {
731 if (TypeManager.IsReferenceType (ta))
740 public bool IsValueType { // TODO: Do I need this ?
742 // TODO MemberCache: probably wrong
743 return HasSpecialStruct;
747 public override string Name {
749 return definition.Name;
753 public bool IsMethodOwned {
755 return DeclaringType == null;
759 public SpecialConstraint SpecialConstraint {
769 // Types used to inflate the generic type
771 public new TypeSpec[] TypeArguments {
780 public Variance Variance {
788 public void ChangeTypeArgumentToBaseType (int index)
790 BaseType = targs [index];
791 if (targs.Length == 1) {
794 var copy = new TypeSpec[targs.Length - 1];
796 Array.Copy (targs, copy, index);
798 Array.Copy (targs, index + 1, copy, index, targs.Length - index - 1);
803 public string DisplayDebugInfo ()
805 var s = GetSignatureForError ();
806 return IsMethodOwned ? s + "!!" : s + "!";
810 // Finds effective base class
812 public TypeSpec GetEffectiveBase ()
814 if (HasSpecialStruct) {
815 return TypeManager.value_type;
818 if (BaseType != null && targs == null)
822 if (HasTypeConstraint) {
823 Array.Resize (ref types, types.Length + 1);
824 types[types.Length - 1] = BaseType;
828 return Convert.FindMostEncompassedType (types.Select (l => l.BaseType));
830 return TypeManager.object_type;
833 public override string GetSignatureForError ()
839 // Constraints have to match by definition but not position, used by
840 // partial classes or methods
842 public bool HasSameConstraintsDefinition (TypeParameterSpec other)
844 if (spec != other.spec)
847 if (BaseType != other.BaseType)
850 if (!TypeSpecComparer.Override.IsSame (InterfacesDefined, other.InterfacesDefined))
853 if (!TypeSpecComparer.Override.IsSame (targs, other.targs))
860 // Constraints have to match by using same set of types, used by
861 // implicit interface implementation
863 public bool HasSameConstraintsImplementation (TypeParameterSpec other)
865 if (spec != other.spec)
869 // It can be same base type or inflated type parameter
871 // interface I<T> { void Foo<U> where U : T; }
872 // class A : I<int> { void Foo<X> where X : int {} }
875 if (!TypeSpecComparer.Override.IsEqual (BaseType, other.BaseType)) {
876 if (other.targs == null)
880 foreach (var otarg in other.targs) {
881 if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
891 // Check interfaces implementation -> definition
892 if (InterfacesDefined != null) {
893 foreach (var iface in InterfacesDefined) {
895 if (other.InterfacesDefined != null) {
896 foreach (var oiface in other.InterfacesDefined) {
897 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
907 if (other.targs != null) {
908 foreach (var otarg in other.targs) {
909 if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
921 // Check interfaces implementation <- definition
922 if (other.InterfacesDefined != null) {
923 if (InterfacesDefined == null)
926 foreach (var oiface in other.InterfacesDefined) {
928 foreach (var iface in InterfacesDefined) {
929 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
940 // Check type parameters implementation -> definition
942 if (other.targs == null)
945 foreach (var targ in targs) {
947 foreach (var otarg in other.targs) {
948 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
959 // Check type parameters implementation <- definition
960 if (other.targs != null) {
961 foreach (var otarg in other.targs) {
962 // Ignore inflated type arguments, were checked above
963 if (!otarg.IsGenericParameter)
970 foreach (var targ in targs) {
971 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
985 public static TypeParameterSpec[] InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec[] tparams)
987 return InflateConstraints (tparams, l => l, inflator);
990 public static TypeParameterSpec[] InflateConstraints<T> (TypeParameterSpec[] tparams, Func<T, TypeParameterInflator> inflatorFactory, T arg)
992 TypeParameterSpec[] constraints = null;
993 TypeParameterInflator? inflator = null;
995 for (int i = 0; i < tparams.Length; ++i) {
997 if (tp.HasTypeConstraint || tp.Interfaces != null || tp.TypeArguments != null) {
998 if (constraints == null) {
999 constraints = new TypeParameterSpec[tparams.Length];
1000 Array.Copy (tparams, constraints, constraints.Length);
1004 // Using a factory to avoid possibly expensive inflator build up
1006 if (inflator == null)
1007 inflator = inflatorFactory (arg);
1009 constraints[i] = (TypeParameterSpec) constraints[i].InflateMember (inflator.Value);
1013 if (constraints == null)
1014 constraints = tparams;
1019 public void InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec tps)
1021 tps.BaseType = inflator.Inflate (BaseType);
1022 if (ifaces != null) {
1023 tps.ifaces = new List<TypeSpec> (ifaces.Count);
1024 for (int i = 0; i < ifaces.Count; ++i)
1025 tps.ifaces.Add (inflator.Inflate (ifaces[i]));
1028 if (targs != null) {
1029 tps.targs = new TypeSpec[targs.Length];
1030 for (int i = 0; i < targs.Length; ++i)
1031 tps.targs[i] = inflator.Inflate (targs[i]);
1035 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1037 var tps = (TypeParameterSpec) MemberwiseClone ();
1038 InflateConstraints (inflator, tps);
1043 // Populates type parameter members using type parameter constraints
1044 // The trick here is to be called late enough but not too late to
1045 // populate member cache with all members from other types
1047 protected override void InitializeMemberCache (bool onlyTypes)
1049 cache = new MemberCache ();
1052 // For a type parameter the membercache is the union of the sets of members of the types
1053 // specified as a primary constraint or secondary constraint
1055 if (BaseType != TypeManager.object_type && BaseType != TypeManager.value_type)
1056 cache.AddBaseType (BaseType);
1058 if (ifaces != null) {
1059 foreach (var iface_type in Interfaces) {
1060 cache.AddInterface (iface_type);
1064 if (targs != null) {
1065 foreach (var ta in targs) {
1066 if (ta.BaseType != TypeManager.object_type && ta.BaseType != TypeManager.value_type)
1067 cache.AddBaseType (ta.BaseType);
1069 if (ta.Interfaces != null) {
1070 foreach (var iface_type in ta.Interfaces) {
1071 cache.AddInterface (iface_type);
1078 public bool IsConvertibleToInterface (TypeSpec iface)
1080 if (Interfaces != null) {
1081 foreach (var t in Interfaces) {
1087 if (TypeArguments != null) {
1088 foreach (var t in TypeArguments) {
1089 if (((TypeParameterSpec) t).IsConvertibleToInterface (iface))
1097 public override TypeSpec Mutate (TypeParameterMutator mutator)
1099 return mutator.Mutate (this);
1103 public struct TypeParameterInflator
1105 readonly TypeSpec type;
1106 readonly TypeParameterSpec[] tparams;
1107 readonly TypeSpec[] targs;
1109 public TypeParameterInflator (TypeParameterInflator nested, TypeSpec type)
1110 : this (type, nested.tparams, nested.targs)
1114 public TypeParameterInflator (TypeSpec type, TypeParameterSpec[] tparams, TypeSpec[] targs)
1116 if (tparams.Length != targs.Length)
1117 throw new ArgumentException ("Invalid arguments");
1119 this.tparams = tparams;
1126 public TypeSpec TypeInstance {
1127 get { return type; }
1131 // Type parameters to inflate
1133 public TypeParameterSpec[] TypeParameters {
1141 public TypeSpec Inflate (TypeSpec type)
1143 var tp = type as TypeParameterSpec;
1145 return Inflate (tp);
1147 var ac = type as ArrayContainer;
1149 var et = Inflate (ac.Element);
1150 if (et != ac.Element)
1151 return ArrayContainer.MakeType (et, ac.Rank);
1157 // When inflating a nested type, inflate its parent first
1158 // in case it's using same type parameters (was inflated within the type)
1162 if (type.IsNested) {
1163 var parent = Inflate (type.DeclaringType);
1166 // Keep the inflated type arguments
1168 targs = type.TypeArguments;
1171 // Parent was inflated, find the same type on inflated type
1172 // to use same cache for nested types on same generic parent
1174 type = MemberCache.FindNestedType (parent, type.Name, type.Arity);
1177 // Handle the tricky case where parent shares local type arguments
1178 // which means inflating inflated type
1181 // public static Nested<T> Foo () { return null; }
1183 // public class Nested<U> {}
1186 // return type of Test<string>.Foo() has to be Test<string>.Nested<string>
1188 if (targs.Length > 0) {
1189 var inflated_targs = new TypeSpec[targs.Length];
1190 for (; i < targs.Length; ++i)
1191 inflated_targs[i] = Inflate (targs[i]);
1193 type = type.MakeGenericType (inflated_targs);
1199 // Nothing to do for non-generic type
1200 if (type.Arity == 0)
1203 targs = new TypeSpec[type.Arity];
1206 // Inflating using outside type arguments, var v = new Foo<int> (), class Foo<T> {}
1208 if (type is InflatedTypeSpec) {
1209 for (; i < targs.Length; ++i)
1210 targs[i] = Inflate (type.TypeArguments[i]);
1212 type = type.GetDefinition ();
1215 // Inflating parent using inside type arguments, class Foo<T> { ITest<T> foo; }
1217 var args = type.MemberDefinition.TypeParameters;
1218 foreach (var ds_tp in args)
1219 targs[i++] = Inflate (ds_tp);
1222 return type.MakeGenericType (targs);
1225 public TypeSpec Inflate (TypeParameterSpec tp)
1227 for (int i = 0; i < tparams.Length; ++i)
1228 if (tparams [i] == tp)
1231 // This can happen when inflating nested types
1232 // without type arguments specified
1238 // Before emitting any code we have to change all MVAR references to VAR
1239 // when the method is of generic type and has hoisted variables
1241 public class TypeParameterMutator
1243 TypeParameter[] mvar;
1244 TypeParameter[] var;
1245 Dictionary<TypeSpec, TypeSpec> mutated_typespec = new Dictionary<TypeSpec, TypeSpec> ();
1247 public TypeParameterMutator (TypeParameter[] mvar, TypeParameter[] var)
1249 if (mvar.Length != var.Length)
1250 throw new ArgumentException ();
1258 public TypeParameter[] MethodTypeParameters {
1266 public static TypeSpec GetMemberDeclaringType (TypeSpec type)
1268 if (type is InflatedTypeSpec) {
1269 if (type.DeclaringType == null)
1270 return type.GetDefinition ();
1272 var parent = GetMemberDeclaringType (type.DeclaringType);
1273 type = MemberCache.GetMember<TypeSpec> (parent, type);
1279 public TypeSpec Mutate (TypeSpec ts)
1282 if (mutated_typespec.TryGetValue (ts, out value))
1285 value = ts.Mutate (this);
1286 mutated_typespec.Add (ts, value);
1290 public TypeParameterSpec Mutate (TypeParameterSpec tp)
1292 for (int i = 0; i < mvar.Length; ++i) {
1293 if (mvar[i].Type == tp)
1300 public TypeSpec[] Mutate (TypeSpec[] targs)
1302 TypeSpec[] mutated = new TypeSpec[targs.Length];
1303 bool changed = false;
1304 for (int i = 0; i < targs.Length; ++i) {
1305 mutated[i] = Mutate (targs[i]);
1306 changed |= targs[i] != mutated[i];
1309 return changed ? mutated : targs;
1314 /// A TypeExpr which already resolved to a type parameter.
1316 public class TypeParameterExpr : TypeExpr {
1318 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1320 this.type = type_parameter.Type;
1321 this.eclass = ExprClass.TypeParameter;
1325 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
1327 throw new NotSupportedException ();
1330 public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
1336 public class InflatedTypeSpec : TypeSpec
1339 TypeParameterSpec[] constraints;
1340 readonly TypeSpec open_type;
1342 public InflatedTypeSpec (TypeSpec openType, TypeSpec declaringType, TypeSpec[] targs)
1343 : base (openType.Kind, declaringType, openType.MemberDefinition, null, openType.Modifiers)
1346 throw new ArgumentNullException ("targs");
1348 // this.state = openType.state;
1349 this.open_type = openType;
1352 foreach (var arg in targs) {
1353 if (arg.HasDynamicElement || arg == InternalType.Dynamic) {
1354 state |= StateFlags.HasDynamicElement;
1362 public override TypeSpec BaseType {
1364 if (cache == null || (state & StateFlags.PendingBaseTypeInflate) != 0)
1365 InitializeMemberCache (true);
1367 return base.BaseType;
1372 // Inflated type parameters with constraints array, mapping with type arguments is based on index
1374 public TypeParameterSpec[] Constraints {
1376 if (constraints == null) {
1377 constraints = TypeParameterSpec.InflateConstraints (MemberDefinition.TypeParameters, l => l.CreateLocalInflator (), this);
1384 public override IList<TypeSpec> Interfaces {
1387 InitializeMemberCache (true);
1389 return base.Interfaces;
1394 // Types used to inflate the generic type
1396 public override TypeSpec[] TypeArguments {
1404 public static bool ContainsTypeParameter (TypeSpec type)
1406 if (type.Kind == MemberKind.TypeParameter)
1409 var element_container = type as ElementTypeSpec;
1410 if (element_container != null)
1411 return ContainsTypeParameter (element_container.Element);
1413 foreach (var t in type.TypeArguments) {
1414 if (ContainsTypeParameter (t)) {
1422 TypeParameterInflator CreateLocalInflator ()
1424 TypeParameterSpec[] tparams_full;
1425 TypeSpec[] targs_full = targs;
1428 // Special case is needed when we are inflating an open type (nested type definition)
1429 // on inflated parent. Consider following case
1431 // Foo<T>.Bar<U> => Foo<string>.Bar<U>
1433 // Any later inflation of Foo<string>.Bar<U> has to also inflate T if used inside Bar<U>
1435 List<TypeSpec> merged_targs = null;
1436 List<TypeParameterSpec> merged_tparams = null;
1438 var type = DeclaringType;
1441 if (type.TypeArguments.Length > 0) {
1442 if (merged_targs == null) {
1443 merged_targs = new List<TypeSpec> ();
1444 merged_tparams = new List<TypeParameterSpec> ();
1445 if (targs.Length > 0) {
1446 merged_targs.AddRange (targs);
1447 merged_tparams.AddRange (open_type.MemberDefinition.TypeParameters);
1450 merged_tparams.AddRange (type.MemberDefinition.TypeParameters);
1451 merged_targs.AddRange (type.TypeArguments);
1453 type = type.DeclaringType;
1454 } while (type != null);
1456 if (merged_targs != null) {
1457 // Type arguments are not in the right order but it should not matter in this case
1458 targs_full = merged_targs.ToArray ();
1459 tparams_full = merged_tparams.ToArray ();
1460 } else if (targs.Length == 0) {
1461 tparams_full = TypeParameterSpec.EmptyTypes;
1463 tparams_full = open_type.MemberDefinition.TypeParameters;
1465 } else if (targs.Length == 0) {
1466 tparams_full = TypeParameterSpec.EmptyTypes;
1468 tparams_full = open_type.MemberDefinition.TypeParameters;
1471 return new TypeParameterInflator (this, tparams_full, targs_full);
1474 MetaType CreateMetaInfo (TypeParameterMutator mutator)
1477 // Converts nested type arguments into right order
1478 // Foo<string, bool>.Bar<int> => string, bool, int
1480 var all = new List<MetaType> ();
1481 TypeSpec type = this;
1482 TypeSpec definition = type;
1484 if (type.GetDefinition().IsGeneric) {
1486 type.TypeArguments != TypeSpec.EmptyTypes ?
1487 type.TypeArguments.Select (l => l.GetMetaInfo ()) :
1488 type.MemberDefinition.TypeParameters.Select (l => l.GetMetaInfo ()));
1491 definition = definition.GetDefinition ();
1492 type = type.DeclaringType;
1493 } while (type != null);
1495 return definition.GetMetaInfo ().MakeGenericType (all.ToArray ());
1498 public override ObsoleteAttribute GetAttributeObsolete ()
1500 return open_type.GetAttributeObsolete ();
1503 protected override bool IsNotCLSCompliant ()
1505 if (base.IsNotCLSCompliant ())
1508 foreach (var ta in TypeArguments) {
1509 if (ta.MemberDefinition.IsNotCLSCompliant ())
1516 public override TypeSpec GetDefinition ()
1521 public override MetaType GetMetaInfo ()
1524 info = CreateMetaInfo (null);
1529 public override string GetSignatureForError ()
1531 if (TypeManager.IsNullableType (open_type))
1532 return targs[0].GetSignatureForError () + "?";
1534 return base.GetSignatureForError ();
1537 protected override string GetTypeNameSignature ()
1539 if (targs.Length == 0 || MemberDefinition is AnonymousTypeClass)
1542 return "<" + TypeManager.CSharpName (targs) + ">";
1545 protected override void InitializeMemberCache (bool onlyTypes)
1548 cache = new MemberCache (onlyTypes ? open_type.MemberCacheTypes : open_type.MemberCache);
1550 var inflator = CreateLocalInflator ();
1553 // Two stage inflate due to possible nested types recursive
1563 // When resolving type of `b' members of `B' cannot be
1564 // inflated because are not yet available in membercache
1566 if ((state & StateFlags.PendingMemberCacheMembers) == 0) {
1567 open_type.MemberCacheTypes.InflateTypes (cache, inflator);
1570 // Inflate any implemented interfaces
1572 if (open_type.Interfaces != null) {
1573 ifaces = new List<TypeSpec> (open_type.Interfaces.Count);
1574 foreach (var iface in open_type.Interfaces) {
1575 var iface_inflated = inflator.Inflate (iface);
1576 AddInterface (iface_inflated);
1581 // Handles the tricky case of recursive nested base generic type
1583 // class A<T> : Base<A<T>.Nested> {
1587 // When inflating A<T>. base type is not yet known, secondary
1588 // inflation is required (not common case) once base scope
1591 if (open_type.BaseType == null) {
1593 state |= StateFlags.PendingBaseTypeInflate;
1595 BaseType = inflator.Inflate (open_type.BaseType);
1597 } else if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1598 BaseType = inflator.Inflate (open_type.BaseType);
1599 state &= ~StateFlags.PendingBaseTypeInflate;
1603 state |= StateFlags.PendingMemberCacheMembers;
1607 var tc = open_type.MemberDefinition as TypeContainer;
1608 if (tc != null && !tc.HasMembersDefined)
1609 throw new InternalErrorException ("Inflating MemberCache with undefined members");
1611 if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1612 BaseType = inflator.Inflate (open_type.BaseType);
1613 state &= ~StateFlags.PendingBaseTypeInflate;
1616 state &= ~StateFlags.PendingMemberCacheMembers;
1617 open_type.MemberCache.InflateMembers (cache, open_type, inflator);
1620 public override TypeSpec Mutate (TypeParameterMutator mutator)
1622 var targs = TypeArguments;
1624 targs = mutator.Mutate (targs);
1626 var decl = DeclaringType;
1627 if (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
1628 decl = mutator.Mutate (decl);
1630 if (targs == TypeArguments && decl == DeclaringType)
1633 var mutated = (InflatedTypeSpec) MemberwiseClone ();
1634 if (decl != DeclaringType) {
1635 // Gets back MethodInfo in case of metaInfo was inflated
1636 //mutated.info = MemberCache.GetMember<TypeSpec> (DeclaringType.GetDefinition (), this).info;
1638 mutated.declaringType = decl;
1639 mutated.state |= StateFlags.PendingMetaInflate;
1642 if (targs != null) {
1643 mutated.targs = targs;
1644 mutated.info = null;
1653 // Tracks the type arguments when instantiating a generic type. It's used
1654 // by both type arguments and type parameters
1656 public class TypeArguments
1658 List<FullNamedExpression> args;
1661 public TypeArguments (params FullNamedExpression[] types)
1663 this.args = new List<FullNamedExpression> (types);
1666 public void Add (FullNamedExpression type)
1671 // TODO: Kill this monster
1672 public TypeParameterName[] GetDeclarations ()
1674 return args.ConvertAll (i => (TypeParameterName) i).ToArray ();
1678 /// We may only be used after Resolve() is called and return the fully
1681 // TODO: Not needed, just return type from resolve
1682 public TypeSpec[] Arguments {
1694 public virtual bool IsEmpty {
1700 public string GetSignatureForError()
1702 StringBuilder sb = new StringBuilder ();
1703 for (int i = 0; i < Count; ++i) {
1706 sb.Append (expr.GetSignatureForError ());
1712 return sb.ToString ();
1716 /// Resolve the type arguments.
1718 public virtual bool Resolve (IMemberContext ec)
1721 return atypes.Length != 0;
1723 int count = args.Count;
1726 atypes = new TypeSpec [count];
1728 for (int i = 0; i < count; i++){
1729 TypeExpr te = args[i].ResolveAsTypeTerminal (ec, false);
1735 atypes[i] = te.Type;
1737 if (te.Type.IsStatic) {
1738 ec.Compiler.Report.Error (718, te.Location, "`{0}': static classes cannot be used as generic arguments",
1739 te.GetSignatureForError ());
1743 if (te.Type.IsPointer || TypeManager.IsSpecialType (te.Type)) {
1744 ec.Compiler.Report.Error (306, te.Location,
1745 "The type `{0}' may not be used as a type argument",
1746 te.GetSignatureForError ());
1752 atypes = TypeSpec.EmptyTypes;
1757 public TypeArguments Clone ()
1759 TypeArguments copy = new TypeArguments ();
1760 foreach (var ta in args)
1767 public class UnboundTypeArguments : TypeArguments
1769 public UnboundTypeArguments (int arity)
1770 : base (new FullNamedExpression[arity])
1774 public override bool IsEmpty {
1780 public override bool Resolve (IMemberContext ec)
1782 // Nothing to be resolved
1787 public class TypeParameterName : SimpleName
1789 Attributes attributes;
1792 public TypeParameterName (string name, Attributes attrs, Location loc)
1793 : this (name, attrs, Variance.None, loc)
1797 public TypeParameterName (string name, Attributes attrs, Variance variance, Location loc)
1801 this.variance = variance;
1804 public Attributes OptAttributes {
1810 public Variance Variance {
1818 // A type expression of generic type with type arguments
1820 class GenericTypeExpr : TypeExpr
1824 bool constraints_checked;
1827 /// Instantiate the generic type `t' with the type arguments `args'.
1828 /// Use this constructor if you already know the fully resolved
1831 public GenericTypeExpr (TypeSpec open_type, TypeArguments args, Location l)
1833 this.open_type = open_type;
1838 public TypeArguments TypeArguments {
1839 get { return args; }
1842 public override string GetSignatureForError ()
1844 return TypeManager.CSharpName (type);
1847 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
1849 if (!args.Resolve (ec))
1852 TypeSpec[] atypes = args.Arguments;
1855 // Now bind the parameters
1857 type = open_type.MakeGenericType (atypes);
1860 // Check constraints when context is not method/base type
1862 if (!ec.HasUnresolvedConstraints)
1863 CheckConstraints (ec);
1869 // Checks the constraints of open generic type against type
1870 // arguments. Has to be called after all members have been defined
1872 public bool CheckConstraints (IMemberContext ec)
1874 if (constraints_checked)
1877 constraints_checked = true;
1879 var gtype = (InflatedTypeSpec) type;
1880 var constraints = gtype.Constraints;
1881 if (constraints == null)
1884 return new ConstraintChecker(ec).CheckAll (open_type, args.Arguments, constraints, loc);
1887 public bool HasDynamicArguments ()
1889 return HasDynamicArguments (args.Arguments);
1892 static bool HasDynamicArguments (TypeSpec[] args)
1894 for (int i = 0; i < args.Length; ++i) {
1897 if (item == InternalType.Dynamic)
1900 if (TypeManager.IsGenericType (item))
1901 return HasDynamicArguments (TypeManager.GetTypeArguments (item));
1904 while (item.IsArray) {
1905 item = ((ArrayContainer) item).Element;
1908 if (item == InternalType.Dynamic)
1916 public override bool Equals (object obj)
1918 GenericTypeExpr cobj = obj as GenericTypeExpr;
1922 if ((type == null) || (cobj.type == null))
1925 return type == cobj.type;
1928 public override int GetHashCode ()
1930 return base.GetHashCode ();
1935 // Generic type with unbound type arguments, used for typeof (G<,,>)
1937 class GenericOpenTypeExpr : TypeExpr
1939 public GenericOpenTypeExpr (TypeSpec type, /*UnboundTypeArguments args,*/ Location loc)
1941 this.type = type.GetDefinition ();
1945 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
1951 struct ConstraintChecker
1954 bool ignore_inferred_dynamic;
1956 public ConstraintChecker (IMemberContext ctx)
1959 ignore_inferred_dynamic = false;
1964 public bool IgnoreInferredDynamic {
1966 return ignore_inferred_dynamic;
1969 ignore_inferred_dynamic = value;
1976 // Checks all type arguments againts type parameters constraints
1977 // NOTE: It can run in probing mode when `mc' is null
1979 public bool CheckAll (MemberSpec context, TypeSpec[] targs, TypeParameterSpec[] tparams, Location loc)
1981 for (int i = 0; i < tparams.Length; i++) {
1982 if (ignore_inferred_dynamic && targs[i] == InternalType.Dynamic)
1985 if (!CheckConstraint (context, targs [i], tparams [i], loc))
1992 bool CheckConstraint (MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, Location loc)
1995 // First, check the `class' and `struct' constraints.
1997 if (tparam.HasSpecialClass && !TypeManager.IsReferenceType (atype)) {
1999 mc.Compiler.Report.Error (452, loc,
2000 "The type `{0}' must be a reference type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
2001 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2007 if (tparam.HasSpecialStruct && (!TypeManager.IsValueType (atype) || TypeManager.IsNullableType (atype))) {
2009 mc.Compiler.Report.Error (453, loc,
2010 "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}'",
2011 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2020 // Check the class constraint
2022 if (tparam.HasTypeConstraint) {
2023 var dep = tparam.BaseType.GetMissingDependencies ();
2028 ImportedTypeDefinition.Error_MissingDependency (mc, dep, loc);
2032 if (!CheckConversion (mc, context, atype, tparam, tparam.BaseType, loc)) {
2041 // Check the interfaces constraints
2043 if (tparam.Interfaces != null) {
2044 if (TypeManager.IsNullableType (atype)) {
2048 mc.Compiler.Report.Error (313, loc,
2049 "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",
2050 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
2053 foreach (TypeSpec iface in tparam.Interfaces) {
2054 var dep = iface.GetMissingDependencies ();
2059 ImportedTypeDefinition.Error_MissingDependency (mc, dep, loc);
2062 // return immediately to avoid duplicate errors because we are scanning
2063 // expanded interface list
2067 if (!CheckConversion (mc, context, atype, tparam, iface, loc)) {
2078 // Check the type parameter constraint
2080 if (tparam.TypeArguments != null) {
2081 foreach (var ta in tparam.TypeArguments) {
2082 if (!CheckConversion (mc, context, atype, tparam, ta, loc)) {
2092 // Finally, check the constructor constraint.
2094 if (!tparam.HasSpecialConstructor)
2097 if (!HasDefaultConstructor (atype)) {
2099 mc.Compiler.Report.SymbolRelatedToPreviousError (atype);
2100 mc.Compiler.Report.Error (310, loc,
2101 "The type `{0}' must have a public parameterless constructor in order to use it as parameter `{1}' in the generic type or method `{2}'",
2102 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2110 static bool HasDynamicTypeArgument (TypeSpec[] targs)
2112 for (int i = 0; i < targs.Length; ++i) {
2113 var targ = targs [i];
2114 if (targ == InternalType.Dynamic)
2117 if (HasDynamicTypeArgument (targ.TypeArguments))
2124 bool CheckConversion (IMemberContext mc, MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, TypeSpec ttype, Location loc)
2126 if (TypeManager.IsValueType (atype)) {
2127 if (atype == ttype || Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
2130 var expr = new EmptyExpression (atype);
2132 if (atype.IsGenericParameter) {
2133 if (Convert.ImplicitTypeParameterConversion (expr, ttype) != null)
2137 if (Convert.ImplicitStandardConversionExists (expr, ttype))
2142 // When partial/full type inference finds a dynamic type argument delay
2143 // the constraint check to runtime, it can succeed for real underlying
2146 if (ignore_inferred_dynamic && HasDynamicTypeArgument (ttype.TypeArguments))
2150 mc.Compiler.Report.SymbolRelatedToPreviousError (tparam);
2151 if (TypeManager.IsValueType (atype)) {
2152 mc.Compiler.Report.Error (315, loc,
2153 "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}'",
2154 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2155 } else if (atype.IsGenericParameter) {
2156 mc.Compiler.Report.Error (314, loc,
2157 "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}'",
2158 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2160 mc.Compiler.Report.Error (311, loc,
2161 "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}'",
2162 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2169 bool HasDefaultConstructor (TypeSpec atype)
2171 var tp = atype as TypeParameterSpec;
2173 return tp.HasSpecialConstructor || tp.HasSpecialStruct;
2176 if (atype.IsStruct || atype.IsEnum)
2179 if (atype.IsAbstract)
2182 var tdef = atype.GetDefinition ();
2185 // In some circumstances MemberCache is not yet populated and members
2186 // cannot be defined yet (recursive type new constraints)
2188 // class A<T> where T : B<T>, new () {}
2189 // class B<T> where T : A<T>, new () {}
2191 var tc = tdef.MemberDefinition as Class;
2193 if (tc.InstanceConstructors == null) {
2194 // Default ctor will be generated later
2198 foreach (var c in tc.InstanceConstructors) {
2199 if (c.ParameterInfo.IsEmpty) {
2200 if ((c.ModFlags & Modifiers.PUBLIC) != 0)
2208 var found = MemberCache.FindMember (tdef,
2209 MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters),
2210 BindingRestriction.DeclaredOnly | BindingRestriction.InstanceOnly);
2212 return found != null && (found.Modifiers & Modifiers.PUBLIC) != 0;
2217 /// A generic method definition.
2219 public class GenericMethod : DeclSpace
2221 ParametersCompiled parameters;
2223 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
2224 FullNamedExpression return_type, ParametersCompiled parameters)
2225 : base (ns, parent, name, null)
2227 this.parameters = parameters;
2230 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name, TypeParameter[] tparams,
2231 FullNamedExpression return_type, ParametersCompiled parameters)
2232 : this (ns, parent, name, return_type, parameters)
2234 this.type_params = tparams;
2237 public override TypeParameter[] CurrentTypeParameters {
2239 return base.type_params;
2243 public override void DefineType ()
2245 throw new Exception ();
2248 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2250 throw new NotSupportedException ();
2253 public override bool Define ()
2255 throw new NotSupportedException ();
2259 /// Define and resolve the type parameters.
2260 /// We're called from Method.Define().
2262 public bool Define (MethodOrOperator m)
2264 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
2265 string[] snames = new string [names.Length];
2266 var block = m.Block;
2267 for (int i = 0; i < names.Length; i++) {
2268 string type_argument_name = names[i].Name;
2270 if (block == null) {
2271 int idx = parameters.GetParameterIndexByName (type_argument_name);
2275 b = new ToplevelBlock (Compiler, Location);
2277 b.Error_AlreadyDeclaredTypeParameter (type_argument_name, parameters[i].Location);
2280 INamedBlockVariable variable = null;
2281 block.GetLocalName (type_argument_name, m.Block, ref variable);
2282 if (variable != null)
2283 variable.Block.Error_AlreadyDeclaredTypeParameter (type_argument_name, variable.Location);
2286 snames[i] = type_argument_name;
2289 GenericTypeParameterBuilder[] gen_params = m.MethodBuilder.DefineGenericParameters (snames);
2290 for (int i = 0; i < TypeParameters.Length; i++)
2291 TypeParameters [i].Define (gen_params [i], null);
2296 public void EmitAttributes ()
2298 if (OptAttributes != null)
2299 OptAttributes.Emit ();
2302 public override string GetSignatureForError ()
2304 return base.GetSignatureForError () + parameters.GetSignatureForError ();
2307 public override AttributeTargets AttributeTargets {
2309 return AttributeTargets.Method | AttributeTargets.ReturnValue;
2313 public override string DocCommentHeader {
2314 get { return "M:"; }
2317 public new void VerifyClsCompliance ()
2319 foreach (TypeParameter tp in TypeParameters) {
2320 tp.VerifyClsCompliance ();
2325 public partial class TypeManager
2327 public static Variance CheckTypeVariance (TypeSpec t, Variance expected, IMemberContext member)
2329 var tp = t as TypeParameterSpec;
2331 Variance v = tp.Variance;
2332 if (expected == Variance.None && v != expected ||
2333 expected == Variance.Covariant && v == Variance.Contravariant ||
2334 expected == Variance.Contravariant && v == Variance.Covariant) {
2335 ((TypeParameter)tp.MemberDefinition).ErrorInvalidVariance (member, expected);
2341 if (t.TypeArguments.Length > 0) {
2342 var targs_definition = t.MemberDefinition.TypeParameters;
2343 TypeSpec[] targs = GetTypeArguments (t);
2344 for (int i = 0; i < targs.Length; ++i) {
2345 Variance v = targs_definition[i].Variance;
2346 CheckTypeVariance (targs[i], (Variance) ((int)v * (int)expected), member);
2353 return CheckTypeVariance (GetElementType (t), expected, member);
2355 return Variance.None;
2360 // Implements C# type inference
2365 // Tracks successful rate of type inference
2367 int score = int.MaxValue;
2368 readonly Arguments arguments;
2369 readonly int arg_count;
2371 public TypeInference (Arguments arguments)
2373 this.arguments = arguments;
2374 if (arguments != null)
2375 arg_count = arguments.Count;
2378 public int InferenceScore {
2384 public TypeSpec[] InferMethodArguments (ResolveContext ec, MethodSpec method)
2386 var method_generic_args = method.GenericDefinition.TypeParameters;
2387 TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2388 if (!context.UnfixedVariableExists)
2389 return TypeSpec.EmptyTypes;
2391 AParametersCollection pd = method.Parameters;
2392 if (!InferInPhases (ec, context, pd))
2395 return context.InferredTypeArguments;
2399 // Implements method type arguments inference
2401 bool InferInPhases (ResolveContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
2403 int params_arguments_start;
2404 if (methodParameters.HasParams) {
2405 params_arguments_start = methodParameters.Count - 1;
2407 params_arguments_start = arg_count;
2410 TypeSpec [] ptypes = methodParameters.Types;
2413 // The first inference phase
2415 TypeSpec method_parameter = null;
2416 for (int i = 0; i < arg_count; i++) {
2417 Argument a = arguments [i];
2421 if (i < params_arguments_start) {
2422 method_parameter = methodParameters.Types [i];
2423 } else if (i == params_arguments_start) {
2424 if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2425 method_parameter = methodParameters.Types [params_arguments_start];
2427 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2429 ptypes = (TypeSpec[]) ptypes.Clone ();
2430 ptypes [i] = method_parameter;
2434 // When a lambda expression, an anonymous method
2435 // is used an explicit argument type inference takes a place
2437 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2439 if (am.ExplicitTypeInference (ec, tic, method_parameter))
2445 score -= tic.ExactInference (a.Type, method_parameter);
2449 if (a.Expr.Type == InternalType.Null)
2452 if (TypeManager.IsValueType (method_parameter)) {
2453 score -= tic.LowerBoundInference (a.Type, method_parameter);
2458 // Otherwise an output type inference is made
2460 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2464 // Part of the second phase but because it happens only once
2465 // we don't need to call it in cycle
2467 bool fixed_any = false;
2468 if (!tic.FixIndependentTypeArguments (ec, ptypes, ref fixed_any))
2471 return DoSecondPhase (ec, tic, ptypes, !fixed_any);
2474 bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, TypeSpec[] methodParameters, bool fixDependent)
2476 bool fixed_any = false;
2477 if (fixDependent && !tic.FixDependentTypes (ec, ref fixed_any))
2480 // If no further unfixed type variables exist, type inference succeeds
2481 if (!tic.UnfixedVariableExists)
2484 if (!fixed_any && fixDependent)
2487 // For all arguments where the corresponding argument output types
2488 // contain unfixed type variables but the input types do not,
2489 // an output type inference is made
2490 for (int i = 0; i < arg_count; i++) {
2492 // Align params arguments
2493 TypeSpec t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
2495 if (!TypeManager.IsDelegateType (t_i)) {
2496 if (t_i.GetDefinition () != TypeManager.expression_type)
2499 t_i = TypeManager.GetTypeArguments (t_i) [0];
2502 var mi = Delegate.GetInvokeMethod (ec.Compiler, t_i);
2503 TypeSpec rtype = mi.ReturnType;
2505 if (tic.IsReturnTypeNonDependent (ec, mi, rtype))
2506 score -= tic.OutputTypeInference (ec, arguments [i].Expr, t_i);
2510 return DoSecondPhase (ec, tic, methodParameters, true);
2514 public class TypeInferenceContext
2516 protected enum BoundKind
2523 protected class BoundInfo : IEquatable<BoundInfo>
2525 public readonly TypeSpec Type;
2526 public readonly BoundKind Kind;
2528 public BoundInfo (TypeSpec type, BoundKind kind)
2534 public override int GetHashCode ()
2536 return Type.GetHashCode ();
2539 public virtual Expression GetTypeExpression ()
2541 return new TypeExpression (Type, Location.Null);
2544 #region IEquatable<BoundInfo> Members
2546 public virtual bool Equals (BoundInfo other)
2548 return Type == other.Type && Kind == other.Kind;
2554 readonly TypeSpec[] tp_args;
2555 readonly TypeSpec[] fixed_types;
2556 readonly List<BoundInfo>[] bounds;
2559 // TODO MemberCache: Could it be TypeParameterSpec[] ??
2560 public TypeInferenceContext (TypeSpec[] typeArguments)
2562 if (typeArguments.Length == 0)
2563 throw new ArgumentException ("Empty generic arguments");
2565 fixed_types = new TypeSpec [typeArguments.Length];
2566 for (int i = 0; i < typeArguments.Length; ++i) {
2567 if (typeArguments [i].IsGenericParameter) {
2568 if (bounds == null) {
2569 bounds = new List<BoundInfo> [typeArguments.Length];
2570 tp_args = new TypeSpec [typeArguments.Length];
2572 tp_args [i] = typeArguments [i];
2574 fixed_types [i] = typeArguments [i];
2580 // Used together with AddCommonTypeBound fo implement
2581 // 7.4.2.13 Finding the best common type of a set of expressions
2583 public TypeInferenceContext ()
2585 fixed_types = new TypeSpec [1];
2586 tp_args = new TypeSpec [1];
2587 tp_args[0] = InternalType.Arglist; // it can be any internal type
2588 bounds = new List<BoundInfo> [1];
2591 public TypeSpec[] InferredTypeArguments {
2597 public void AddCommonTypeBound (TypeSpec type)
2599 AddToBounds (new BoundInfo (type, BoundKind.Lower), 0);
2602 protected void AddToBounds (BoundInfo bound, int index)
2605 // Some types cannot be used as type arguments
2607 if (bound.Type == TypeManager.void_type || bound.Type.IsPointer)
2610 var a = bounds [index];
2612 a = new List<BoundInfo> (2);
2618 if (a.Contains (bound))
2624 bool AllTypesAreFixed (TypeSpec[] types)
2626 foreach (TypeSpec t in types) {
2627 if (t.IsGenericParameter) {
2633 if (TypeManager.IsGenericType (t))
2634 return AllTypesAreFixed (TypeManager.GetTypeArguments (t));
2641 // 26.3.3.8 Exact Inference
2643 public int ExactInference (TypeSpec u, TypeSpec v)
2645 // If V is an array type
2650 // TODO MemberCache: GetMetaInfo ()
2651 if (u.GetMetaInfo ().GetArrayRank () != v.GetMetaInfo ().GetArrayRank ())
2654 return ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
2657 // If V is constructed type and U is constructed type
2658 if (TypeManager.IsGenericType (v)) {
2659 if (!TypeManager.IsGenericType (u))
2662 TypeSpec [] ga_u = TypeManager.GetTypeArguments (u);
2663 TypeSpec [] ga_v = TypeManager.GetTypeArguments (v);
2664 if (ga_u.Length != ga_v.Length)
2668 for (int i = 0; i < ga_u.Length; ++i)
2669 score += ExactInference (ga_u [i], ga_v [i]);
2671 return score > 0 ? 1 : 0;
2674 // If V is one of the unfixed type arguments
2675 int pos = IsUnfixed (v);
2679 AddToBounds (new BoundInfo (u, BoundKind.Exact), pos);
2683 public bool FixAllTypes (ResolveContext ec)
2685 for (int i = 0; i < tp_args.Length; ++i) {
2686 if (!FixType (ec, i))
2693 // All unfixed type variables Xi are fixed for which all of the following hold:
2694 // a, There is at least one type variable Xj that depends on Xi
2695 // b, Xi has a non-empty set of bounds
2697 public bool FixDependentTypes (ResolveContext ec, ref bool fixed_any)
2699 for (int i = 0; i < tp_args.Length; ++i) {
2700 if (fixed_types[i] != null)
2703 if (bounds[i] == null)
2706 if (!FixType (ec, i))
2716 // All unfixed type variables Xi which depend on no Xj are fixed
2718 public bool FixIndependentTypeArguments (ResolveContext ec, TypeSpec[] methodParameters, ref bool fixed_any)
2720 var types_to_fix = new List<TypeSpec> (tp_args);
2721 for (int i = 0; i < methodParameters.Length; ++i) {
2722 TypeSpec t = methodParameters[i];
2724 if (!TypeManager.IsDelegateType (t)) {
2725 if (TypeManager.expression_type == null || t.MemberDefinition != TypeManager.expression_type.MemberDefinition)
2728 t = TypeManager.GetTypeArguments (t) [0];
2731 if (t.IsGenericParameter)
2734 var invoke = Delegate.GetInvokeMethod (ec.Compiler, t);
2735 TypeSpec rtype = invoke.ReturnType;
2736 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
2739 // Remove dependent types, they cannot be fixed yet
2740 RemoveDependentTypes (types_to_fix, rtype);
2743 foreach (TypeSpec t in types_to_fix) {
2747 int idx = IsUnfixed (t);
2748 if (idx >= 0 && !FixType (ec, idx)) {
2753 fixed_any = types_to_fix.Count > 0;
2760 public bool FixType (ResolveContext ec, int i)
2762 // It's already fixed
2763 if (fixed_types[i] != null)
2764 throw new InternalErrorException ("Type argument has been already fixed");
2769 var candidates = bounds [i];
2770 if (candidates == null)
2773 if (candidates.Count == 1) {
2774 TypeSpec t = candidates[0].Type;
2775 if (t == InternalType.Null)
2778 fixed_types [i] = t;
2783 // Determines a unique type from which there is
2784 // a standard implicit conversion to all the other
2787 TypeSpec best_candidate = null;
2789 int candidates_count = candidates.Count;
2790 for (int ci = 0; ci < candidates_count; ++ci) {
2791 BoundInfo bound = candidates [ci];
2792 for (cii = 0; cii < candidates_count; ++cii) {
2796 BoundInfo cbound = candidates[cii];
2798 // Same type parameters with different bounds
2799 if (cbound.Type == bound.Type) {
2800 if (bound.Kind != BoundKind.Exact)
2806 if (bound.Kind == BoundKind.Exact || cbound.Kind == BoundKind.Exact) {
2807 if (cbound.Kind == BoundKind.Lower) {
2808 if (!Convert.ImplicitConversionExists (ec, cbound.GetTypeExpression (), bound.Type)) {
2814 if (cbound.Kind == BoundKind.Upper) {
2815 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
2822 if (bound.Kind != BoundKind.Exact) {
2823 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
2834 if (bound.Kind == BoundKind.Lower) {
2835 if (cbound.Kind == BoundKind.Lower) {
2836 if (!Convert.ImplicitConversionExists (ec, cbound.GetTypeExpression (), bound.Type)) {
2840 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
2850 if (bound.Kind == BoundKind.Upper) {
2851 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
2855 throw new NotImplementedException ("variance conversion");
2859 if (cii != candidates_count)
2863 // We already have the best candidate, break if thet are different
2865 // Dynamic is never ambiguous as we prefer dynamic over other best candidate types
2867 if (best_candidate != null) {
2869 if (best_candidate == InternalType.Dynamic)
2872 if (bound.Type != InternalType.Dynamic && best_candidate != bound.Type)
2876 best_candidate = bound.Type;
2879 if (best_candidate == null)
2882 fixed_types[i] = best_candidate;
2887 // Uses inferred or partially infered types to inflate delegate type argument. Returns
2888 // null when type parameter has not been fixed
2890 public TypeSpec InflateGenericArgument (TypeSpec parameter)
2892 var tp = parameter as TypeParameterSpec;
2895 // Type inference works on generic arguments (MVAR) only
2897 if (!tp.IsMethodOwned)
2901 // Ensure the type parameter belongs to same container
2903 if (tp.DeclaredPosition < tp_args.Length && tp_args[tp.DeclaredPosition] == parameter)
2904 return fixed_types[tp.DeclaredPosition] ?? parameter;
2909 var gt = parameter as InflatedTypeSpec;
2911 var inflated_targs = new TypeSpec [gt.TypeArguments.Length];
2912 for (int ii = 0; ii < inflated_targs.Length; ++ii) {
2913 var inflated = InflateGenericArgument (gt.TypeArguments [ii]);
2914 if (inflated == null)
2917 inflated_targs[ii] = inflated;
2920 return gt.GetDefinition ().MakeGenericType (inflated_targs);
2927 // Tests whether all delegate input arguments are fixed and generic output type
2928 // requires output type inference
2930 public bool IsReturnTypeNonDependent (ResolveContext ec, MethodSpec invoke, TypeSpec returnType)
2932 if (returnType.IsGenericParameter) {
2933 if (IsFixed (returnType))
2935 } else if (TypeManager.IsGenericType (returnType)) {
2936 if (TypeManager.IsDelegateType (returnType)) {
2937 invoke = Delegate.GetInvokeMethod (ec.Compiler, returnType);
2938 return IsReturnTypeNonDependent (ec, invoke, invoke.ReturnType);
2941 TypeSpec[] g_args = TypeManager.GetTypeArguments (returnType);
2943 // At least one unfixed return type has to exist
2944 if (AllTypesAreFixed (g_args))
2950 // All generic input arguments have to be fixed
2951 AParametersCollection d_parameters = invoke.Parameters;
2952 return AllTypesAreFixed (d_parameters.Types);
2955 bool IsFixed (TypeSpec type)
2957 return IsUnfixed (type) == -1;
2960 int IsUnfixed (TypeSpec type)
2962 if (!type.IsGenericParameter)
2965 for (int i = 0; i < tp_args.Length; ++i) {
2966 if (tp_args[i] == type) {
2967 if (fixed_types[i] != null)
2978 // 26.3.3.9 Lower-bound Inference
2980 public int LowerBoundInference (TypeSpec u, TypeSpec v)
2982 return LowerBoundInference (u, v, false);
2986 // Lower-bound (false) or Upper-bound (true) inference based on inversed argument
2988 int LowerBoundInference (TypeSpec u, TypeSpec v, bool inversed)
2990 // If V is one of the unfixed type arguments
2991 int pos = IsUnfixed (v);
2993 AddToBounds (new BoundInfo (u, inversed ? BoundKind.Upper : BoundKind.Lower), pos);
2997 // If U is an array type
2998 var u_ac = u as ArrayContainer;
3000 var v_ac = v as ArrayContainer;
3002 if (u_ac.Rank != v_ac.Rank)
3005 if (TypeManager.IsValueType (u_ac.Element))
3006 return ExactInference (u_ac.Element, v_ac.Element);
3008 return LowerBoundInference (u_ac.Element, v_ac.Element, inversed);
3014 if (TypeManager.IsGenericType (v)) {
3015 TypeSpec g_v = v.GetDefinition ();
3016 if (g_v != TypeManager.generic_ilist_type &&
3017 g_v != TypeManager.generic_icollection_type &&
3018 g_v != TypeManager.generic_ienumerable_type)
3021 var v_i = TypeManager.GetTypeArguments (v) [0];
3022 if (TypeManager.IsValueType (u_ac.Element))
3023 return ExactInference (u_ac.Element, v_i);
3025 return LowerBoundInference (u_ac.Element, v_i);
3027 } else if (TypeManager.IsGenericType (v)) {
3029 // if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
3030 // such that U is identical to, inherits from (directly or indirectly),
3031 // or implements (directly or indirectly) C<U1..Uk>
3033 var u_candidates = new List<TypeSpec> ();
3034 var open_v = v.MemberDefinition;
3036 for (TypeSpec t = u; t != null; t = t.BaseType) {
3037 if (open_v == t.MemberDefinition)
3038 u_candidates.Add (t);
3041 // Using this trick for dynamic type inference, the spec says the type arguments are "unknown" but
3042 // that would complicate the process a lot, instead I treat them as dynamic
3044 if (t == InternalType.Dynamic)
3045 u_candidates.Add (t);
3047 if (t.Interfaces != null) {
3048 foreach (var iface in t.Interfaces) {
3049 if (open_v == iface.MemberDefinition)
3050 u_candidates.Add (iface);
3055 TypeSpec [] unique_candidate_targs = null;
3056 TypeSpec[] ga_v = TypeManager.GetTypeArguments (v);
3057 foreach (TypeSpec u_candidate in u_candidates) {
3059 // The unique set of types U1..Uk means that if we have an interface I<T>,
3060 // class U : I<int>, I<long> then no type inference is made when inferring
3061 // type I<T> by applying type U because T could be int or long
3063 if (unique_candidate_targs != null) {
3064 TypeSpec[] second_unique_candidate_targs = TypeManager.GetTypeArguments (u_candidate);
3065 if (TypeSpecComparer.Equals (unique_candidate_targs, second_unique_candidate_targs)) {
3066 unique_candidate_targs = second_unique_candidate_targs;
3071 // This should always cause type inference failure
3078 // A candidate is dynamic type expression, to simplify things use dynamic
3079 // for all type parameter of this type. For methods like this one
3081 // void M<T, U> (IList<T>, IList<U[]>)
3083 // dynamic becomes both T and U when the arguments are of dynamic type
3085 if (u_candidate == InternalType.Dynamic) {
3086 unique_candidate_targs = new TypeSpec[ga_v.Length];
3087 for (int i = 0; i < unique_candidate_targs.Length; ++i)
3088 unique_candidate_targs[i] = u_candidate;
3090 unique_candidate_targs = TypeManager.GetTypeArguments (u_candidate);
3094 if (unique_candidate_targs != null) {
3095 var ga_open_v = open_v.TypeParameters;
3097 for (int i = 0; i < unique_candidate_targs.Length; ++i) {
3098 Variance variance = ga_open_v [i].Variance;
3100 TypeSpec u_i = unique_candidate_targs [i];
3101 if (variance == Variance.None || TypeManager.IsValueType (u_i)) {
3102 if (ExactInference (u_i, ga_v [i]) == 0)
3105 bool upper_bound = (variance == Variance.Contravariant && !inversed) ||
3106 (variance == Variance.Covariant && inversed);
3108 if (LowerBoundInference (u_i, ga_v [i], upper_bound) == 0)
3120 // 26.3.3.6 Output Type Inference
3122 public int OutputTypeInference (ResolveContext ec, Expression e, TypeSpec t)
3124 // If e is a lambda or anonymous method with inferred return type
3125 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
3127 TypeSpec rt = ame.InferReturnType (ec, this, t);
3128 var invoke = Delegate.GetInvokeMethod (ec.Compiler, t);
3131 AParametersCollection pd = invoke.Parameters;
3132 return ame.Parameters.Count == pd.Count ? 1 : 0;
3135 TypeSpec rtype = invoke.ReturnType;
3136 return LowerBoundInference (rt, rtype) + 1;
3140 // if E is a method group and T is a delegate type or expression tree type
3141 // return type Tb with parameter types T1..Tk and return type Tb, and overload
3142 // resolution of E with the types T1..Tk yields a single method with return type U,
3143 // then a lower-bound inference is made from U for Tb.
3145 if (e is MethodGroupExpr) {
3146 if (!TypeManager.IsDelegateType (t)) {
3147 if (TypeManager.expression_type == null || t.MemberDefinition != TypeManager.expression_type.MemberDefinition)
3150 t = TypeManager.GetTypeArguments (t)[0];
3153 var invoke = Delegate.GetInvokeMethod (ec.Compiler, t);
3154 TypeSpec rtype = invoke.ReturnType;
3156 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
3159 // LAMESPEC: Standard does not specify that all methodgroup arguments
3160 // has to be fixed but it does not specify how to do recursive type inference
3161 // either. We choose the simple option and infer return type only
3162 // if all delegate generic arguments are fixed.
3163 TypeSpec[] param_types = new TypeSpec [invoke.Parameters.Count];
3164 for (int i = 0; i < param_types.Length; ++i) {
3165 var inflated = InflateGenericArgument (invoke.Parameters.Types[i]);
3166 if (inflated == null)
3169 if (IsUnfixed (inflated) >= 0)
3172 param_types[i] = inflated;
3175 MethodGroupExpr mg = (MethodGroupExpr) e;
3176 Arguments args = DelegateCreation.CreateDelegateMethodArguments (invoke.Parameters, param_types, e.Location);
3177 mg = mg.OverloadResolve (ec, ref args, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
3181 return LowerBoundInference (mg.BestCandidateReturnType, rtype) + 1;
3185 // if e is an expression with type U, then
3186 // a lower-bound inference is made from U for T
3188 return LowerBoundInference (e.Type, t) * 2;
3191 void RemoveDependentTypes (List<TypeSpec> types, TypeSpec returnType)
3193 int idx = IsUnfixed (returnType);
3199 if (TypeManager.IsGenericType (returnType)) {
3200 foreach (TypeSpec t in TypeManager.GetTypeArguments (returnType)) {
3201 RemoveDependentTypes (types, t);
3206 public bool UnfixedVariableExists {
3208 foreach (TypeSpec ut in fixed_types) {