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;
19 using System.Text.RegularExpressions;
21 namespace Mono.CSharp {
24 /// Abstract base class for type parameter constraints.
25 /// The type parameter can come from a generic type definition or from reflection.
27 public abstract class GenericConstraints {
28 public abstract string TypeParameter {
32 public abstract GenericParameterAttributes Attributes {
36 public bool HasConstructorConstraint {
37 get { return (Attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0; }
40 public bool HasReferenceTypeConstraint {
41 get { return (Attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0; }
44 public bool HasValueTypeConstraint {
45 get { return (Attributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0; }
48 public virtual bool HasClassConstraint {
49 get { return ClassConstraint != null; }
52 public abstract Type ClassConstraint {
56 public abstract Type[] InterfaceConstraints {
60 public abstract Type EffectiveBaseClass {
65 // Returns whether the type parameter is "known to be a reference type".
67 public virtual bool IsReferenceType {
69 if (HasReferenceTypeConstraint)
71 if (HasValueTypeConstraint)
74 if (ClassConstraint != null) {
75 if (ClassConstraint.IsValueType)
78 if (ClassConstraint != TypeManager.object_type)
82 foreach (Type t in InterfaceConstraints) {
83 if (!t.IsGenericParameter)
86 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
87 if ((gc != null) && gc.IsReferenceType)
96 // Returns whether the type parameter is "known to be a value type".
98 public virtual bool IsValueType {
100 if (HasValueTypeConstraint)
102 if (HasReferenceTypeConstraint)
105 if (ClassConstraint != null) {
106 if (!ClassConstraint.IsValueType)
109 if (ClassConstraint != TypeManager.value_type)
113 foreach (Type t in InterfaceConstraints) {
114 if (!t.IsGenericParameter)
117 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
118 if ((gc != null) && gc.IsValueType)
127 public enum SpecialConstraint
135 /// Tracks the constraints for a type parameter from a generic type definition.
137 public class Constraints : GenericConstraints {
139 ArrayList constraints;
143 // name is the identifier, constraints is an arraylist of
144 // Expressions (with types) or `true' for the constructor constraint.
146 public Constraints (string name, ArrayList constraints,
150 this.constraints = constraints;
154 public override string TypeParameter {
160 public Constraints Clone ()
162 return new Constraints (name, constraints, loc);
165 GenericParameterAttributes attrs;
166 TypeExpr class_constraint;
167 ArrayList iface_constraints;
168 ArrayList type_param_constraints;
170 Type class_constraint_type;
171 Type[] iface_constraint_types;
172 Type effective_base_type;
177 /// Resolve the constraints - but only resolve things into Expression's, not
178 /// into actual types.
180 public bool Resolve (IResolveContext ec)
185 iface_constraints = new ArrayList (2); // TODO: Too expensive allocation
186 type_param_constraints = new ArrayList ();
188 foreach (object obj in constraints) {
189 if (HasConstructorConstraint) {
190 Report.Error (401, loc,
191 "The new() constraint must be the last constraint specified");
195 if (obj is SpecialConstraint) {
196 SpecialConstraint sc = (SpecialConstraint) obj;
198 if (sc == SpecialConstraint.Constructor) {
199 if (!HasValueTypeConstraint) {
200 attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
204 Report.Error (451, loc, "The `new()' constraint " +
205 "cannot be used with the `struct' constraint");
209 if ((num_constraints > 0) || HasReferenceTypeConstraint || HasValueTypeConstraint) {
210 Report.Error (449, loc, "The `class' or `struct' " +
211 "constraint must be the first constraint specified");
215 if (sc == SpecialConstraint.ReferenceType)
216 attrs |= GenericParameterAttributes.ReferenceTypeConstraint;
218 attrs |= GenericParameterAttributes.NotNullableValueTypeConstraint;
222 int errors = Report.Errors;
223 FullNamedExpression fn = ((Expression) obj).ResolveAsTypeStep (ec, false);
226 if (errors != Report.Errors)
229 NamespaceEntry.Error_NamespaceNotFound (loc, ((Expression)obj).GetSignatureForError ());
234 ConstructedType cexpr = fn as ConstructedType;
236 if (!cexpr.ResolveConstructedType (ec))
241 expr = ((Expression) obj).ResolveAsTypeTerminal (ec, false);
243 if ((expr == null) || (expr.Type == null))
246 if (!ec.GenericDeclContainer.IsAccessibleAs (fn.Type)) {
247 Report.SymbolRelatedToPreviousError (fn.Type);
248 Report.Error (703, loc,
249 "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
250 fn.GetSignatureForError (), ec.GenericDeclContainer.GetSignatureForError ());
254 TypeParameterExpr texpr = expr as TypeParameterExpr;
256 type_param_constraints.Add (expr);
257 else if (expr.IsInterface)
258 iface_constraints.Add (expr);
259 else if (class_constraint != null || iface_constraints.Count != 0) {
260 Report.Error (406, loc,
261 "The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
262 expr.GetSignatureForError ());
264 } else if (HasReferenceTypeConstraint || HasValueTypeConstraint) {
265 Report.Error (450, loc, "`{0}': cannot specify both " +
266 "a constraint class and the `class' " +
267 "or `struct' constraint", expr.GetSignatureForError ());
270 class_constraint = expr;
275 ArrayList list = new ArrayList ();
276 foreach (TypeExpr iface_constraint in iface_constraints) {
277 foreach (Type type in list) {
278 if (!type.Equals (iface_constraint.Type))
281 Report.Error (405, loc,
282 "Duplicate constraint `{0}' for type " +
283 "parameter `{1}'.", iface_constraint.GetSignatureForError (),
288 list.Add (iface_constraint.Type);
291 foreach (TypeParameterExpr expr in type_param_constraints) {
292 foreach (Type type in list) {
293 if (!type.Equals (expr.Type))
296 Report.Error (405, loc,
297 "Duplicate constraint `{0}' for type " +
298 "parameter `{1}'.", expr.GetSignatureForError (), name);
302 list.Add (expr.Type);
305 iface_constraint_types = new Type [list.Count];
306 list.CopyTo (iface_constraint_types, 0);
308 if (class_constraint != null) {
309 class_constraint_type = class_constraint.Type;
310 if (class_constraint_type == null)
313 if (class_constraint_type.IsSealed) {
314 if (class_constraint_type.IsAbstract)
316 Report.Error (717, loc, "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
317 TypeManager.CSharpName (class_constraint_type));
321 Report.Error (701, loc, "`{0}' is not a valid constraint. A constraint must be an interface, " +
322 "a non-sealed class or a type parameter", TypeManager.CSharpName(class_constraint_type));
327 if ((class_constraint_type == TypeManager.array_type) ||
328 (class_constraint_type == TypeManager.delegate_type) ||
329 (class_constraint_type == TypeManager.enum_type) ||
330 (class_constraint_type == TypeManager.value_type) ||
331 (class_constraint_type == TypeManager.object_type) ||
332 class_constraint_type == TypeManager.multicast_delegate_type) {
333 Report.Error (702, loc,
334 "A constraint cannot be special class `{0}'",
335 TypeManager.CSharpName (class_constraint_type));
340 if (class_constraint_type != null)
341 effective_base_type = class_constraint_type;
342 else if (HasValueTypeConstraint)
343 effective_base_type = TypeManager.value_type;
345 effective_base_type = TypeManager.object_type;
347 if ((attrs & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0)
348 attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
354 bool CheckTypeParameterConstraints (TypeParameter tparam, ref TypeExpr prevConstraint, ArrayList seen)
358 Constraints constraints = tparam.Constraints;
359 if (constraints == null)
362 if (constraints.HasValueTypeConstraint) {
363 Report.Error (456, loc,
364 "Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
370 // Checks whether there are no conflicts between type parameter constraints
374 // where U : A, B // A and B are not convertible
376 if (constraints.HasClassConstraint) {
377 if (prevConstraint != null) {
378 Type t2 = constraints.ClassConstraint;
379 TypeExpr e2 = constraints.class_constraint;
381 if (!Convert.ImplicitReferenceConversionExists (prevConstraint, t2) &&
382 !Convert.ImplicitReferenceConversionExists (e2, prevConstraint.Type)) {
383 Report.Error (455, loc,
384 "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
385 name, TypeManager.CSharpName (prevConstraint.Type), TypeManager.CSharpName (t2));
390 prevConstraint = constraints.class_constraint;
393 if (constraints.type_param_constraints == null)
396 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
397 if (seen.Contains (expr.TypeParameter)) {
398 Report.Error (454, loc, "Circular constraint " +
399 "dependency involving `{0}' and `{1}'",
400 tparam.Name, expr.GetSignatureForError ());
404 if (!CheckTypeParameterConstraints (expr.TypeParameter, ref prevConstraint, seen))
412 /// Resolve the constraints into actual types.
414 public bool ResolveTypes (IResolveContext ec)
419 resolved_types = true;
421 foreach (object obj in constraints) {
422 ConstructedType cexpr = obj as ConstructedType;
426 if (!cexpr.CheckConstraints (ec))
430 if (type_param_constraints.Count != 0) {
431 ArrayList seen = new ArrayList ();
432 TypeExpr prev_constraint = class_constraint;
433 foreach (TypeParameterExpr expr in type_param_constraints) {
434 if (!CheckTypeParameterConstraints (expr.TypeParameter, ref prev_constraint, seen))
440 for (int i = 0; i < iface_constraints.Count; ++i) {
441 TypeExpr iface_constraint = (TypeExpr) iface_constraints [i];
442 iface_constraint = iface_constraint.ResolveAsTypeTerminal (ec, false);
443 if (iface_constraint == null)
445 iface_constraints [i] = iface_constraint;
448 if (class_constraint != null) {
449 class_constraint = class_constraint.ResolveAsTypeTerminal (ec, false);
450 if (class_constraint == null)
457 public override GenericParameterAttributes Attributes {
458 get { return attrs; }
461 public override bool HasClassConstraint {
462 get { return class_constraint != null; }
465 public override Type ClassConstraint {
466 get { return class_constraint_type; }
469 public override Type[] InterfaceConstraints {
470 get { return iface_constraint_types; }
473 public override Type EffectiveBaseClass {
474 get { return effective_base_type; }
477 public bool IsSubclassOf (Type t)
479 if ((class_constraint_type != null) &&
480 class_constraint_type.IsSubclassOf (t))
483 if (iface_constraint_types == null)
486 foreach (Type iface in iface_constraint_types) {
487 if (TypeManager.IsSubclassOf (iface, t))
494 public Location Location {
501 /// This is used when we're implementing a generic interface method.
502 /// Each method type parameter in implementing method must have the same
503 /// constraints than the corresponding type parameter in the interface
504 /// method. To do that, we're called on each of the implementing method's
507 public bool AreEqual (GenericConstraints gc)
509 if (gc.Attributes != attrs)
512 if (HasClassConstraint != gc.HasClassConstraint)
514 if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
517 int gc_icount = gc.InterfaceConstraints != null ?
518 gc.InterfaceConstraints.Length : 0;
519 int icount = InterfaceConstraints != null ?
520 InterfaceConstraints.Length : 0;
522 if (gc_icount != icount)
525 for (int i = 0; i < gc.InterfaceConstraints.Length; ++i) {
526 Type iface = gc.InterfaceConstraints [i];
527 if (iface.IsGenericType)
528 iface = iface.GetGenericTypeDefinition ();
531 for (int ii = 0; i < InterfaceConstraints.Length; ++ii) {
532 Type check = InterfaceConstraints [ii];
533 if (check.IsGenericType)
534 check = check.GetGenericTypeDefinition ();
536 if (TypeManager.IsEqual (iface, check)) {
549 public void VerifyClsCompliance ()
551 if (class_constraint_type != null && !AttributeTester.IsClsCompliant (class_constraint_type))
552 Warning_ConstrainIsNotClsCompliant (class_constraint_type, class_constraint.Location);
554 if (iface_constraint_types != null) {
555 for (int i = 0; i < iface_constraint_types.Length; ++i) {
556 if (!AttributeTester.IsClsCompliant (iface_constraint_types [i]))
557 Warning_ConstrainIsNotClsCompliant (iface_constraint_types [i],
558 ((TypeExpr)iface_constraints [i]).Location);
563 void Warning_ConstrainIsNotClsCompliant (Type t, Location loc)
565 Report.SymbolRelatedToPreviousError (t);
566 Report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
567 TypeManager.CSharpName (t));
572 /// A type parameter from a generic type definition.
574 public class TypeParameter : MemberCore, IMemberContainer
576 static readonly string[] attribute_target = new string [] { "type parameter" };
579 GenericConstraints gc;
580 Constraints constraints;
581 GenericTypeParameterBuilder type;
582 MemberCache member_cache;
584 public TypeParameter (DeclSpace parent, DeclSpace decl, string name,
585 Constraints constraints, Attributes attrs, Location loc)
586 : base (parent, new MemberName (name, loc), attrs)
589 this.constraints = constraints;
592 public GenericConstraints GenericConstraints {
593 get { return gc != null ? gc : constraints; }
596 public Constraints Constraints {
597 get { return constraints; }
600 public DeclSpace DeclSpace {
609 /// This is the first method which is called during the resolving
610 /// process; we're called immediately after creating the type parameters
611 /// with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
614 /// We're either called from TypeContainer.DefineType() or from
615 /// GenericMethod.Define() (called from Method.Define()).
617 public void Define (GenericTypeParameterBuilder type)
619 if (this.type != null)
620 throw new InvalidOperationException ();
623 TypeManager.AddTypeParameter (type, this);
627 /// This is the second method which is called during the resolving
628 /// process - in case of class type parameters, we're called from
629 /// TypeContainer.ResolveType() - after it resolved the class'es
630 /// base class and interfaces. For method type parameters, we're
631 /// called immediately after Define().
633 /// We're just resolving the constraints into expressions here, we
634 /// don't resolve them into actual types.
636 /// Note that in the special case of partial generic classes, we may be
637 /// called _before_ Define() and we may also be called multiple types.
639 public bool Resolve (DeclSpace ds)
641 if (constraints != null) {
642 if (!constraints.Resolve (ds)) {
652 /// This is the third method which is called during the resolving
653 /// process. We're called immediately after calling DefineConstraints()
654 /// on all of the current class'es type parameters.
656 /// Our job is to resolve the constraints to actual types.
658 /// Note that we may have circular dependencies on type parameters - this
659 /// is why Resolve() and ResolveType() are separate.
661 public bool ResolveType (IResolveContext ec)
663 if (constraints != null) {
664 if (!constraints.ResolveTypes (ec)) {
674 /// This is the fourth and last method which is called during the resolving
675 /// process. We're called after everything is fully resolved and actually
676 /// register the constraints with SRE and the TypeManager.
678 public bool DefineType (IResolveContext ec)
680 return DefineType (ec, null, null, false);
684 /// This is the fith and last method which is called during the resolving
685 /// process. We're called after everything is fully resolved and actually
686 /// register the constraints with SRE and the TypeManager.
688 /// The `builder', `implementing' and `is_override' arguments are only
689 /// applicable to method type parameters.
691 public bool DefineType (IResolveContext ec, MethodBuilder builder,
692 MethodInfo implementing, bool is_override)
694 if (!ResolveType (ec))
697 if (implementing != null) {
698 if (is_override && (constraints != null)) {
699 Report.Error (460, Location,
700 "`{0}': Cannot specify constraints for overrides or explicit interface implementation methods",
701 TypeManager.CSharpSignature (builder));
705 MethodBase mb = TypeManager.DropGenericMethodArguments (implementing);
707 int pos = type.GenericParameterPosition;
708 Type mparam = mb.GetGenericArguments () [pos];
709 GenericConstraints temp_gc = ReflectionConstraints.GetConstraints (mparam);
712 gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
713 else if (constraints != null)
714 gc = new InflatedConstraints (constraints, implementing.DeclaringType);
717 if (constraints != null) {
720 else if (!constraints.AreEqual (gc))
723 if (!is_override && (temp_gc != null))
728 Report.SymbolRelatedToPreviousError (implementing);
731 425, Location, "The constraints for type " +
732 "parameter `{0}' of method `{1}' must match " +
733 "the constraints for type parameter `{2}' " +
734 "of interface method `{3}'. Consider using " +
735 "an explicit interface implementation instead",
736 Name, TypeManager.CSharpSignature (builder),
737 TypeManager.CSharpName (mparam), TypeManager.CSharpSignature (mb));
740 } else if (DeclSpace is CompilerGeneratedClass) {
741 TypeParameter[] tparams = DeclSpace.TypeParameters;
742 Type[] types = new Type [tparams.Length];
743 for (int i = 0; i < tparams.Length; i++)
744 types [i] = tparams [i].Type;
746 if (constraints != null)
747 gc = new InflatedConstraints (constraints, types);
749 gc = (GenericConstraints) constraints;
755 if (gc.HasClassConstraint || gc.HasValueTypeConstraint)
756 type.SetBaseTypeConstraint (gc.EffectiveBaseClass);
758 type.SetInterfaceConstraints (gc.InterfaceConstraints);
759 type.SetGenericParameterAttributes (gc.Attributes);
760 TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
766 /// This is called for each part of a partial generic type definition.
768 /// If `new_constraints' is not null and we don't already have constraints,
769 /// they become our constraints. If we already have constraints, we must
770 /// check that they're the same.
773 public bool UpdateConstraints (IResolveContext ec, Constraints new_constraints)
776 throw new InvalidOperationException ();
778 if (new_constraints == null)
781 if (!new_constraints.Resolve (ec))
783 if (!new_constraints.ResolveTypes (ec))
786 if (constraints != null)
787 return constraints.AreEqual (new_constraints);
789 constraints = new_constraints;
793 public override void Emit ()
795 if (OptAttributes != null)
796 OptAttributes.Emit ();
801 public override string DocCommentHeader {
803 throw new InvalidOperationException (
804 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
812 public override bool Define ()
817 public override void ApplyAttributeBuilder (Attribute a,
818 CustomAttributeBuilder cb)
820 type.SetCustomAttribute (cb);
823 public override AttributeTargets AttributeTargets {
825 return AttributeTargets.GenericParameter;
829 public override string[] ValidAttributeTargets {
831 return attribute_target;
839 string IMemberContainer.Name {
843 MemberCache IMemberContainer.BaseCache {
848 if (gc.EffectiveBaseClass.BaseType == null)
851 return TypeManager.LookupMemberCache (gc.EffectiveBaseClass.BaseType);
855 bool IMemberContainer.IsInterface {
856 get { return false; }
859 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
861 throw new NotSupportedException ();
864 public MemberCache MemberCache {
866 if (member_cache != null)
872 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
873 member_cache = new MemberCache (this, gc.EffectiveBaseClass, ifaces);
879 public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
880 MemberFilter filter, object criteria)
883 return MemberList.Empty;
885 ArrayList members = new ArrayList ();
887 if (gc.HasClassConstraint) {
888 MemberList list = TypeManager.FindMembers (
889 gc.ClassConstraint, mt, bf, filter, criteria);
891 members.AddRange (list);
894 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
895 foreach (Type t in ifaces) {
896 MemberList list = TypeManager.FindMembers (
897 t, mt, bf, filter, criteria);
899 members.AddRange (list);
902 return new MemberList (members);
905 public bool IsSubclassOf (Type t)
910 if (constraints != null)
911 return constraints.IsSubclassOf (t);
916 public static string GetSignatureForError (TypeParameter[] tp)
918 if (tp == null || tp.Length == 0)
921 StringBuilder sb = new StringBuilder ("<");
922 for (int i = 0; i < tp.Length; ++i) {
925 sb.Append (tp[i].GetSignatureForError ());
928 return sb.ToString ();
931 public void InflateConstraints (Type declaring)
933 if (constraints != null)
934 gc = new InflatedConstraints (constraints, declaring);
937 public override bool IsClsComplianceRequired ()
942 protected class InflatedConstraints : GenericConstraints
944 GenericConstraints gc;
946 Type class_constraint;
947 Type[] iface_constraints;
950 public InflatedConstraints (GenericConstraints gc, Type declaring)
951 : this (gc, TypeManager.GetTypeArguments (declaring))
954 public InflatedConstraints (GenericConstraints gc, Type[] dargs)
959 ArrayList list = new ArrayList ();
960 if (gc.HasClassConstraint)
961 list.Add (inflate (gc.ClassConstraint));
962 foreach (Type iface in gc.InterfaceConstraints)
963 list.Add (inflate (iface));
965 bool has_class_constr = false;
966 if (list.Count > 0) {
967 Type first = (Type) list [0];
968 has_class_constr = !first.IsGenericParameter && !first.IsInterface;
971 if ((list.Count > 0) && has_class_constr) {
972 class_constraint = (Type) list [0];
973 iface_constraints = new Type [list.Count - 1];
974 list.CopyTo (1, iface_constraints, 0, list.Count - 1);
976 iface_constraints = new Type [list.Count];
977 list.CopyTo (iface_constraints, 0);
980 if (HasValueTypeConstraint)
981 base_type = TypeManager.value_type;
982 else if (class_constraint != null)
983 base_type = class_constraint;
985 base_type = TypeManager.object_type;
988 Type inflate (Type t)
992 if (t.IsGenericParameter)
993 return t.GenericParameterPosition < dargs.Length ? dargs [t.GenericParameterPosition] : t;
994 if (t.IsGenericType) {
995 Type[] args = t.GetGenericArguments ();
996 Type[] inflated = new Type [args.Length];
998 for (int i = 0; i < args.Length; i++)
999 inflated [i] = inflate (args [i]);
1001 t = t.GetGenericTypeDefinition ();
1002 t = t.MakeGenericType (inflated);
1008 public override string TypeParameter {
1009 get { return gc.TypeParameter; }
1012 public override GenericParameterAttributes Attributes {
1013 get { return gc.Attributes; }
1016 public override Type ClassConstraint {
1017 get { return class_constraint; }
1020 public override Type EffectiveBaseClass {
1021 get { return base_type; }
1024 public override Type[] InterfaceConstraints {
1025 get { return iface_constraints; }
1031 /// A TypeExpr which already resolved to a type parameter.
1033 public class TypeParameterExpr : TypeExpr {
1034 TypeParameter type_parameter;
1036 public TypeParameter TypeParameter {
1038 return type_parameter;
1042 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1044 this.type_parameter = type_parameter;
1048 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1050 throw new NotSupportedException ();
1053 public override FullNamedExpression ResolveAsTypeStep (IResolveContext ec, bool silent)
1055 type = type_parameter.Type;
1056 eclass = ExprClass.TypeParameter;
1060 public override bool IsInterface {
1061 get { return false; }
1064 public override bool CheckAccessLevel (DeclSpace ds)
1071 /// Tracks the type arguments when instantiating a generic type. We're used in
1072 /// ConstructedType.
1074 public class TypeArguments {
1075 public readonly Location Location;
1081 public TypeArguments (Location loc)
1083 args = new ArrayList ();
1084 this.Location = loc;
1087 public TypeArguments (Location loc, params Expression[] types)
1089 this.Location = loc;
1090 this.args = new ArrayList (types);
1093 public TypeArguments (int dimension, Location loc)
1095 this.dimension = dimension;
1096 this.Location = loc;
1099 public void Add (Expression type)
1104 public void Add (TypeArguments new_args)
1106 args.AddRange (new_args.args);
1110 /// We're used during the parsing process: the parser can't distinguish
1111 /// between type parameters and type arguments. Because of that, the
1112 /// parser creates a `MemberName' with `TypeArguments' for both cases and
1113 /// in case of a generic type definition, we call GetDeclarations().
1115 public TypeParameterName[] GetDeclarations ()
1117 TypeParameterName[] ret = new TypeParameterName [args.Count];
1118 for (int i = 0; i < args.Count; i++) {
1119 TypeParameterName name = args [i] as TypeParameterName;
1124 SimpleName sn = args [i] as SimpleName;
1125 if (sn != null && !sn.HasTypeArguments) {
1126 ret [i] = new TypeParameterName (sn.Name, null, sn.Location);
1130 Expression expr = (Expression) args [i];
1131 // TODO: Wrong location
1132 Report.Error (81, Location, "Type parameter declaration must be an identifier not a type");
1133 ret [i] = new TypeParameterName (expr.GetSignatureForError (), null, expr.Location);
1139 /// We may only be used after Resolve() is called and return the fully
1142 public Type[] Arguments {
1148 public bool HasTypeArguments {
1150 return has_type_args;
1163 public bool IsUnbound {
1165 return dimension > 0;
1169 public override string ToString ()
1171 StringBuilder s = new StringBuilder ();
1174 for (int i = 0; i < count; i++){
1176 // FIXME: Use TypeManager.CSharpname once we have the type
1179 s.Append (args [i].ToString ());
1183 return s.ToString ();
1186 public string GetSignatureForError()
1188 StringBuilder sb = new StringBuilder();
1189 for (int i = 0; i < Count; ++i)
1191 Expression expr = (Expression)args [i];
1192 sb.Append(expr.GetSignatureForError());
1196 return sb.ToString();
1200 /// Resolve the type arguments.
1202 public bool Resolve (IResolveContext ec)
1204 int count = args.Count;
1207 atypes = new Type [count];
1209 for (int i = 0; i < count; i++){
1210 TypeExpr te = ((Expression) args [i]).ResolveAsTypeTerminal (ec, false);
1216 atypes[i] = te.Type;
1217 if (te.Type.IsGenericParameter) {
1218 if (te is TypeParameterExpr)
1219 has_type_args = true;
1223 if (te.Type.IsSealed && te.Type.IsAbstract) {
1224 Report.Error (718, Location, "`{0}': static classes cannot be used as generic arguments",
1225 te.GetSignatureForError ());
1229 if (te.Type.IsPointer || TypeManager.IsSpecialType (te.Type)) {
1230 Report.Error (306, Location,
1231 "The type `{0}' may not be used as a type argument",
1232 TypeManager.CSharpName (te.Type));
1236 if (te.Type == TypeManager.void_type) {
1237 Expression.Error_VoidInvalidInTheContext (Location);
1244 public TypeArguments Clone ()
1246 TypeArguments copy = new TypeArguments (Location);
1247 foreach (Expression ta in args)
1254 public class TypeParameterName : SimpleName
1256 Attributes attributes;
1258 public TypeParameterName (string name, Attributes attrs, Location loc)
1264 public Attributes OptAttributes {
1272 /// An instantiation of a generic type.
1274 public class ConstructedType : TypeExpr {
1275 FullNamedExpression name;
1277 Type[] gen_params, atypes;
1281 /// Instantiate the generic type `fname' with the type arguments `args'.
1283 public ConstructedType (FullNamedExpression fname, TypeArguments args, Location l)
1289 eclass = ExprClass.Type;
1293 /// This is used to construct the `this' type inside a generic type definition.
1295 public ConstructedType (Type t, TypeParameter[] type_params, Location l)
1297 gt = t.GetGenericTypeDefinition ();
1299 args = new TypeArguments (l);
1300 foreach (TypeParameter type_param in type_params)
1301 args.Add (new TypeParameterExpr (type_param, l));
1304 this.name = new TypeExpression (gt, l);
1305 eclass = ExprClass.Type;
1309 /// Instantiate the generic type `t' with the type arguments `args'.
1310 /// Use this constructor if you already know the fully resolved
1313 public ConstructedType (Type t, TypeArguments args, Location l)
1314 : this ((FullNamedExpression)null, args, l)
1316 gt = t.GetGenericTypeDefinition ();
1317 this.name = new TypeExpression (gt, l);
1320 public TypeArguments TypeArguments {
1321 get { return args; }
1324 public override string GetSignatureForError ()
1326 return TypeManager.CSharpName (type);
1329 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1331 if (!ResolveConstructedType (ec))
1338 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1339 /// after fully resolving the constructed type.
1341 public bool CheckConstraints (IResolveContext ec)
1343 return ConstraintChecker.CheckConstraints (ec, gt, gen_params, atypes, loc);
1347 /// Resolve the constructed type, but don't check the constraints.
1349 public bool ResolveConstructedType (IResolveContext ec)
1353 // If we already know the fully resolved generic type.
1355 return DoResolveType (ec);
1361 Report.Error (246, loc, "Cannot find type `{0}'<...>", GetSignatureForError ());
1365 num_args = TypeManager.GetNumberOfTypeArguments (t);
1366 if (num_args == 0) {
1367 Report.Error (308, loc,
1368 "The non-generic type `{0}' cannot " +
1369 "be used with type arguments.",
1370 TypeManager.CSharpName (t));
1374 gt = t.GetGenericTypeDefinition ();
1375 return DoResolveType (ec);
1378 bool DoResolveType (IResolveContext ec)
1381 // Resolve the arguments.
1383 if (args.Resolve (ec) == false)
1386 gen_params = gt.GetGenericArguments ();
1387 atypes = args.Arguments;
1389 if (atypes.Length != gen_params.Length) {
1390 Report.Error (305, loc,
1391 "Using the generic type `{0}' " +
1392 "requires {1} type arguments",
1393 TypeManager.CSharpName (gt),
1394 gen_params.Length.ToString ());
1399 // Now bind the parameters.
1401 type = gt.MakeGenericType (atypes);
1405 public Expression GetSimpleName (EmitContext ec)
1410 public override bool CheckAccessLevel (DeclSpace ds)
1412 return ds.CheckAccessLevel (gt);
1415 public override bool AsAccessible (DeclSpace ds)
1417 foreach (Type t in atypes) {
1418 if (!ds.IsAccessibleAs (t))
1422 return ds.IsAccessibleAs (gt);
1425 public override bool IsClass {
1426 get { return gt.IsClass; }
1429 public override bool IsValueType {
1430 get { return gt.IsValueType; }
1433 public override bool IsInterface {
1434 get { return gt.IsInterface; }
1437 public override bool IsSealed {
1438 get { return gt.IsSealed; }
1441 public override bool Equals (object obj)
1443 ConstructedType cobj = obj as ConstructedType;
1447 if ((type == null) || (cobj.type == null))
1450 return type == cobj.type;
1453 public override int GetHashCode ()
1455 return base.GetHashCode ();
1459 public abstract class ConstraintChecker
1461 protected readonly Type[] gen_params;
1462 protected readonly Type[] atypes;
1463 protected readonly Location loc;
1465 protected ConstraintChecker (Type[] gen_params, Type[] atypes, Location loc)
1467 this.gen_params = gen_params;
1468 this.atypes = atypes;
1473 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1474 /// after fully resolving the constructed type.
1476 public bool CheckConstraints (IResolveContext ec)
1478 for (int i = 0; i < gen_params.Length; i++) {
1479 if (!CheckConstraints (ec, i))
1486 protected bool CheckConstraints (IResolveContext ec, int index)
1488 Type atype = atypes [index];
1489 Type ptype = gen_params [index];
1494 Expression aexpr = new EmptyExpression (atype);
1496 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1500 bool is_class, is_struct;
1501 if (atype.IsGenericParameter) {
1502 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1504 if (agc is Constraints)
1505 ((Constraints) agc).Resolve (ec);
1506 is_class = agc.IsReferenceType;
1507 is_struct = agc.IsValueType;
1509 is_class = is_struct = false;
1514 if (!atype.IsGenericType)
1516 is_class = atype.IsClass || atype.IsInterface;
1517 is_struct = atype.IsValueType && !TypeManager.IsNullableType (atype);
1521 // First, check the `class' and `struct' constraints.
1523 if (gc.HasReferenceTypeConstraint && !is_class) {
1524 Report.Error (452, loc, "The type `{0}' must be " +
1525 "a reference type in order to use it " +
1526 "as type parameter `{1}' in the " +
1527 "generic type or method `{2}'.",
1528 TypeManager.CSharpName (atype),
1529 TypeManager.CSharpName (ptype),
1530 GetSignatureForError ());
1532 } else if (gc.HasValueTypeConstraint && !is_struct) {
1533 Report.Error (453, loc, "The type `{0}' must be a " +
1534 "non-nullable value type in order to use it " +
1535 "as type parameter `{1}' in the " +
1536 "generic type or method `{2}'.",
1537 TypeManager.CSharpName (atype),
1538 TypeManager.CSharpName (ptype),
1539 GetSignatureForError ());
1544 // The class constraint comes next.
1546 if (gc.HasClassConstraint) {
1547 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint))
1552 // Now, check the interface constraints.
1554 if (gc.InterfaceConstraints != null) {
1555 foreach (Type it in gc.InterfaceConstraints) {
1556 if (!CheckConstraint (ec, ptype, aexpr, it))
1562 // Finally, check the constructor constraint.
1565 if (!gc.HasConstructorConstraint)
1568 if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
1571 if (HasDefaultConstructor (atype))
1574 Report_SymbolRelatedToPreviousError ();
1575 Report.SymbolRelatedToPreviousError (atype);
1576 Report.Error (310, loc, "The type `{0}' must have a public " +
1577 "parameterless constructor in order to use it " +
1578 "as parameter `{1}' in the generic type or " +
1580 TypeManager.CSharpName (atype),
1581 TypeManager.CSharpName (ptype),
1582 GetSignatureForError ());
1586 protected bool CheckConstraint (IResolveContext ec, Type ptype, Expression expr,
1589 if (TypeManager.HasGenericArguments (ctype)) {
1590 Type[] types = TypeManager.GetTypeArguments (ctype);
1592 TypeArguments new_args = new TypeArguments (loc);
1594 for (int i = 0; i < types.Length; i++) {
1597 if (t.IsGenericParameter) {
1598 int pos = t.GenericParameterPosition;
1601 new_args.Add (new TypeExpression (t, loc));
1604 TypeExpr ct = new ConstructedType (ctype, new_args, loc);
1605 if (ct.ResolveAsTypeStep (ec, false) == null)
1608 } else if (ctype.IsGenericParameter) {
1609 int pos = ctype.GenericParameterPosition;
1610 ctype = atypes [pos];
1613 if (Convert.ImplicitStandardConversionExists (expr, ctype))
1616 Report_SymbolRelatedToPreviousError ();
1617 Report.SymbolRelatedToPreviousError (expr.Type);
1619 if (TypeManager.IsNullableType (expr.Type) && ctype.IsInterface) {
1620 Report.Error (313, loc,
1621 "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. " +
1622 "The nullable type `{0}' never satisfies interface constraint of type `{3}'",
1623 TypeManager.CSharpName (expr.Type), TypeManager.CSharpName (ptype),
1624 GetSignatureForError (), TypeManager.CSharpName (ctype));
1626 Report.Error (309, loc,
1627 "The type `{0}' must be convertible to `{1}' in order to " +
1628 "use it as parameter `{2}' in the generic type or method `{3}'",
1629 TypeManager.CSharpName (expr.Type), TypeManager.CSharpName (ctype),
1630 TypeManager.CSharpName (ptype), GetSignatureForError ());
1635 static bool HasDefaultConstructor (Type atype)
1637 TypeParameter tparam = TypeManager.LookupTypeParameter (atype);
1638 if (tparam != null) {
1639 if (tparam.GenericConstraints == null)
1642 return tparam.GenericConstraints.HasConstructorConstraint ||
1643 tparam.GenericConstraints.HasValueTypeConstraint;
1646 if (atype.IsAbstract)
1650 atype = TypeManager.DropGenericTypeArguments (atype);
1651 if (atype is TypeBuilder) {
1652 TypeContainer tc = TypeManager.LookupTypeContainer (atype);
1653 if (tc.InstanceConstructors == null) {
1654 atype = atype.BaseType;
1658 foreach (Constructor c in tc.InstanceConstructors) {
1659 if ((c.ModFlags & Modifiers.PUBLIC) == 0)
1661 if ((c.Parameters.FixedParameters != null) &&
1662 (c.Parameters.FixedParameters.Length != 0))
1664 if (c.Parameters.HasArglist || c.Parameters.HasParams)
1671 MemberInfo [] list = TypeManager.MemberLookup (null, null, atype, MemberTypes.Constructor,
1672 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
1673 ConstructorInfo.ConstructorName, null);
1678 foreach (MethodBase mb in list) {
1679 AParametersCollection pd = TypeManager.GetParameterData (mb);
1687 protected abstract string GetSignatureForError ();
1688 protected abstract void Report_SymbolRelatedToPreviousError ();
1690 public static bool CheckConstraints (EmitContext ec, MethodBase definition,
1691 MethodBase instantiated, Location loc)
1693 MethodConstraintChecker checker = new MethodConstraintChecker (
1694 definition, definition.GetGenericArguments (),
1695 instantiated.GetGenericArguments (), loc);
1697 return checker.CheckConstraints (ec);
1700 public static bool CheckConstraints (IResolveContext ec, Type gt, Type[] gen_params,
1701 Type[] atypes, Location loc)
1703 TypeConstraintChecker checker = new TypeConstraintChecker (
1704 gt, gen_params, atypes, loc);
1706 return checker.CheckConstraints (ec);
1709 protected class MethodConstraintChecker : ConstraintChecker
1711 MethodBase definition;
1713 public MethodConstraintChecker (MethodBase definition, Type[] gen_params,
1714 Type[] atypes, Location loc)
1715 : base (gen_params, atypes, loc)
1717 this.definition = definition;
1720 protected override string GetSignatureForError ()
1722 return TypeManager.CSharpSignature (definition);
1725 protected override void Report_SymbolRelatedToPreviousError ()
1727 Report.SymbolRelatedToPreviousError (definition);
1731 protected class TypeConstraintChecker : ConstraintChecker
1735 public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
1737 : base (gen_params, atypes, loc)
1742 protected override string GetSignatureForError ()
1744 return TypeManager.CSharpName (gt);
1747 protected override void Report_SymbolRelatedToPreviousError ()
1749 Report.SymbolRelatedToPreviousError (gt);
1755 /// A generic method definition.
1757 public class GenericMethod : DeclSpace
1759 FullNamedExpression return_type;
1760 Parameters parameters;
1762 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
1763 FullNamedExpression return_type, Parameters parameters)
1764 : base (ns, parent, name, null)
1766 this.return_type = return_type;
1767 this.parameters = parameters;
1770 public override TypeBuilder DefineType ()
1772 throw new Exception ();
1775 public override bool Define ()
1777 for (int i = 0; i < TypeParameters.Length; i++)
1778 if (!TypeParameters [i].Resolve (this))
1785 /// Define and resolve the type parameters.
1786 /// We're called from Method.Define().
1788 public bool Define (MethodBuilder mb)
1790 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1791 string[] snames = new string [names.Length];
1792 for (int i = 0; i < names.Length; i++) {
1793 string type_argument_name = names[i].Name;
1794 Parameter p = parameters.GetParameterByName (type_argument_name);
1796 Error_ParameterNameCollision (p.Location, type_argument_name, "method parameter");
1800 snames[i] = type_argument_name;
1803 GenericTypeParameterBuilder[] gen_params = mb.DefineGenericParameters (snames);
1804 for (int i = 0; i < TypeParameters.Length; i++)
1805 TypeParameters [i].Define (gen_params [i]);
1810 for (int i = 0; i < TypeParameters.Length; i++) {
1811 if (!TypeParameters [i].ResolveType (this))
1818 internal static void Error_ParameterNameCollision (Location loc, string name, string collisionWith)
1820 Report.Error (412, loc, "The type parameter name `{0}' is the same as `{1}'",
1821 name, collisionWith);
1825 /// We're called from MethodData.Define() after creating the MethodBuilder.
1827 public bool DefineType (EmitContext ec, MethodBuilder mb,
1828 MethodInfo implementing, bool is_override)
1830 for (int i = 0; i < TypeParameters.Length; i++)
1831 if (!TypeParameters [i].DefineType (
1832 ec, mb, implementing, is_override))
1835 bool ok = parameters.Resolve (ec);
1837 if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec, false) == null))
1843 public void EmitAttributes ()
1845 for (int i = 0; i < TypeParameters.Length; i++)
1846 TypeParameters [i].Emit ();
1848 if (OptAttributes != null)
1849 OptAttributes.Emit ();
1852 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1853 MemberFilter filter, object criteria)
1855 throw new Exception ();
1858 public override MemberCache MemberCache {
1864 public override AttributeTargets AttributeTargets {
1866 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1870 public override string DocCommentHeader {
1871 get { return "M:"; }
1874 public new void VerifyClsCompliance ()
1876 foreach (TypeParameter tp in TypeParameters) {
1877 if (tp.Constraints == null)
1880 tp.Constraints.VerifyClsCompliance ();
1885 public partial class TypeManager
1887 static public Type activator_type;
1889 public static TypeContainer LookupGenericTypeContainer (Type t)
1891 t = DropGenericTypeArguments (t);
1892 return LookupTypeContainer (t);
1896 /// Check whether `a' and `b' may become equal generic types.
1897 /// The algorithm to do that is a little bit complicated.
1899 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_inferred,
1900 Type[] method_inferred)
1902 if (a.IsGenericParameter) {
1904 // If a is an array of a's type, they may never
1908 b = b.GetElementType ();
1914 // If b is a generic parameter or an actual type,
1915 // they may become equal:
1917 // class X<T,U> : I<T>, I<U>
1918 // class X<T> : I<T>, I<float>
1920 if (b.IsGenericParameter || !b.IsGenericType) {
1921 int pos = a.GenericParameterPosition;
1922 Type[] args = a.DeclaringMethod != null ? method_inferred : class_inferred;
1923 if (args [pos] == null) {
1928 return args [pos] == a;
1932 // We're now comparing a type parameter with a
1933 // generic instance. They may become equal unless
1934 // the type parameter appears anywhere in the
1935 // generic instance:
1937 // class X<T,U> : I<T>, I<X<U>>
1938 // -> error because you could instanciate it as
1941 // class X<T> : I<T>, I<X<T>> -> ok
1944 Type[] bargs = GetTypeArguments (b);
1945 for (int i = 0; i < bargs.Length; i++) {
1946 if (a.Equals (bargs [i]))
1953 if (b.IsGenericParameter)
1954 return MayBecomeEqualGenericTypes (b, a, class_inferred, method_inferred);
1957 // At this point, neither a nor b are a type parameter.
1959 // If one of them is a generic instance, let
1960 // MayBecomeEqualGenericInstances() compare them (if the
1961 // other one is not a generic instance, they can never
1965 if (a.IsGenericType || b.IsGenericType)
1966 return MayBecomeEqualGenericInstances (a, b, class_inferred, method_inferred);
1969 // If both of them are arrays.
1972 if (a.IsArray && b.IsArray) {
1973 if (a.GetArrayRank () != b.GetArrayRank ())
1976 a = a.GetElementType ();
1977 b = b.GetElementType ();
1979 return MayBecomeEqualGenericTypes (a, b, class_inferred, method_inferred);
1983 // Ok, two ordinary types.
1986 return a.Equals (b);
1990 // Checks whether two generic instances may become equal for some
1991 // particular instantiation (26.3.1).
1993 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
1994 Type[] class_inferred,
1995 Type[] method_inferred)
1997 if (!a.IsGenericType || !b.IsGenericType)
1999 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2002 return MayBecomeEqualGenericInstances (
2003 GetTypeArguments (a), GetTypeArguments (b), class_inferred, method_inferred);
2006 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
2007 Type[] class_inferred,
2008 Type[] method_inferred)
2010 if (aargs.Length != bargs.Length)
2013 for (int i = 0; i < aargs.Length; i++) {
2014 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_inferred, method_inferred))
2022 /// Type inference. Try to infer the type arguments from `method',
2023 /// which is invoked with the arguments `arguments'. This is used
2024 /// when resolving an Invocation or a DelegateInvocation and the user
2025 /// did not explicitly specify type arguments.
2027 public static int InferTypeArguments (EmitContext ec,
2028 ArrayList arguments,
2029 ref MethodBase method)
2031 ATypeInference ti = ATypeInference.CreateInstance (arguments);
2032 Type[] i_args = ti.InferMethodArguments (ec, method);
2034 return ti.InferenceScore;
2036 if (i_args.Length == 0)
2039 method = ((MethodInfo) method).MakeGenericMethod (i_args);
2046 public static bool InferTypeArguments (AParametersCollection apd,
2047 ref MethodBase method)
2049 if (!TypeManager.IsGenericMethod (method))
2052 ATypeInference ti = ATypeInference.CreateInstance (ArrayList.Adapter (apd.Types));
2053 Type[] i_args = ti.InferDelegateArguments (method);
2057 method = ((MethodInfo) method).MakeGenericMethod (i_args);
2062 abstract class ATypeInference
2064 protected readonly ArrayList arguments;
2065 protected readonly int arg_count;
2067 protected ATypeInference (ArrayList arguments)
2069 this.arguments = arguments;
2070 if (arguments != null)
2071 arg_count = arguments.Count;
2074 public static ATypeInference CreateInstance (ArrayList arguments)
2076 if (RootContext.Version == LanguageVersion.ISO_2)
2077 return new TypeInferenceV2 (arguments);
2079 return new TypeInferenceV3 (arguments);
2082 public virtual int InferenceScore {
2084 return int.MaxValue;
2088 public abstract Type[] InferMethodArguments (EmitContext ec, MethodBase method);
2089 public abstract Type[] InferDelegateArguments (MethodBase method);
2093 // Implements C# 2.0 type inference
2095 class TypeInferenceV2 : ATypeInference
2097 public TypeInferenceV2 (ArrayList arguments)
2102 public override Type[] InferDelegateArguments (MethodBase method)
2104 AParametersCollection pd = TypeManager.GetParameterData (method);
2105 if (arg_count != pd.Count)
2108 Type[] method_args = method.GetGenericArguments ();
2109 Type[] inferred_types = new Type[method_args.Length];
2111 Type[] param_types = new Type[pd.Count];
2112 Type[] arg_types = (Type[])arguments.ToArray (typeof (Type));
2114 for (int i = 0; i < arg_count; i++) {
2115 param_types[i] = pd.Types [i];
2118 if (!InferTypeArguments (param_types, arg_types, inferred_types))
2121 return inferred_types;
2124 public override Type[] InferMethodArguments (EmitContext ec, MethodBase method)
2126 AParametersCollection pd = TypeManager.GetParameterData (method);
2127 Type[] method_generic_args = method.GetGenericArguments ();
2128 Type [] inferred_types = new Type [method_generic_args.Length];
2129 Type[] arg_types = new Type [pd.Count];
2131 int a_count = arg_types.Length;
2135 for (int i = 0; i < a_count; i++) {
2136 Argument a = (Argument) arguments[i];
2137 if (a.Expr is NullLiteral || a.Expr is MethodGroupExpr || a.Expr is AnonymousMethodExpression)
2140 if (!TypeInferenceV2.UnifyType (pd.Types [i], a.Type, inferred_types))
2145 Type element_type = TypeManager.GetElementType (pd.Types [a_count]);
2146 for (int i = a_count; i < arg_count; i++) {
2147 Argument a = (Argument) arguments [i];
2148 if (a.Expr is NullLiteral || a.Expr is MethodGroupExpr || a.Expr is AnonymousMethodExpression)
2151 if (!TypeInferenceV2.UnifyType (element_type, a.Type, inferred_types))
2156 for (int i = 0; i < inferred_types.Length; i++)
2157 if (inferred_types [i] == null)
2160 return inferred_types;
2163 static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
2164 Type[] inferred_types)
2166 for (int i = 0; i < arg_types.Length; i++) {
2167 if (arg_types[i] == null)
2170 if (!UnifyType (param_types[i], arg_types[i], inferred_types))
2174 for (int i = 0; i < inferred_types.Length; ++i)
2175 if (inferred_types[i] == null)
2181 public static bool UnifyType (Type pt, Type at, Type[] inferred)
2183 if (pt.IsGenericParameter) {
2184 if (pt.DeclaringMethod == null)
2187 int pos = pt.GenericParameterPosition;
2189 if (inferred [pos] == null)
2190 inferred [pos] = at;
2192 return inferred [pos] == at;
2195 if (!pt.ContainsGenericParameters) {
2196 if (at.ContainsGenericParameters)
2197 return UnifyType (at, pt, inferred);
2204 if (at.GetArrayRank () != pt.GetArrayRank ())
2207 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2210 if (!pt.IsGenericType)
2213 Type gt = pt.GetGenericTypeDefinition ();
2214 if ((gt != TypeManager.generic_ilist_type) && (gt != TypeManager.generic_icollection_type) &&
2215 (gt != TypeManager.generic_ienumerable_type))
2218 Type[] args = TypeManager.GetTypeArguments (pt);
2219 return UnifyType (args[0], at.GetElementType (), inferred);
2224 (pt.GetArrayRank () != at.GetArrayRank ()))
2227 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2230 if (pt.IsByRef && at.IsByRef)
2231 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2232 ArrayList list = new ArrayList ();
2233 if (at.IsGenericType)
2235 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
2238 list.AddRange (TypeManager.GetInterfaces (at));
2240 foreach (Type type in list) {
2241 if (!type.IsGenericType)
2244 if (TypeManager.DropGenericTypeArguments (pt) != TypeManager.DropGenericTypeArguments (type))
2247 if (!UnifyTypes (pt.GetGenericArguments (), type.GetGenericArguments (), inferred))
2254 static bool UnifyTypes (Type[] pts, Type[] ats, Type[] inferred)
2256 for (int i = 0; i < ats.Length; i++) {
2257 if (!UnifyType (pts [i], ats [i], inferred))
2265 // Implements C# 3.0 type inference
2267 class TypeInferenceV3 : ATypeInference
2270 // Tracks successful rate of type inference
2272 int score = int.MaxValue;
2274 public TypeInferenceV3 (ArrayList arguments)
2279 public override int InferenceScore {
2285 public override Type[] InferDelegateArguments (MethodBase method)
2287 AParametersCollection pd = TypeManager.GetParameterData (method);
2288 if (arg_count != pd.Count)
2291 Type[] d_gargs = method.GetGenericArguments ();
2292 TypeInferenceContext context = new TypeInferenceContext (d_gargs);
2294 // A lower-bound inference is made from each argument type Uj of D
2295 // to the corresponding parameter type Tj of M
2296 for (int i = 0; i < arg_count; ++i) {
2297 Type t = pd.Types [i];
2298 if (!t.IsGenericParameter)
2301 context.LowerBoundInference ((Type)arguments[i], t);
2304 if (!context.FixAllTypes ())
2307 return context.InferredTypeArguments;
2310 public override Type[] InferMethodArguments (EmitContext ec, MethodBase method)
2312 Type[] method_generic_args = method.GetGenericArguments ();
2313 TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2314 if (!context.UnfixedVariableExists)
2315 return Type.EmptyTypes;
2317 AParametersCollection pd = TypeManager.GetParameterData (method);
2318 if (!InferInPhases (ec, context, pd))
2321 return context.InferredTypeArguments;
2325 // Implements method type arguments inference
2327 bool InferInPhases (EmitContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
2329 int params_arguments_start;
2330 if (methodParameters.HasParams) {
2331 params_arguments_start = methodParameters.Count - 1;
2333 params_arguments_start = arg_count;
2336 Type [] ptypes = methodParameters.Types;
2339 // The first inference phase
2341 Type method_parameter = null;
2342 for (int i = 0; i < arg_count; i++) {
2343 Argument a = (Argument) arguments [i];
2345 if (i < params_arguments_start) {
2346 method_parameter = methodParameters.Types [i];
2347 } else if (i == params_arguments_start) {
2348 if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2349 method_parameter = methodParameters.Types [params_arguments_start];
2351 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2353 ptypes = (Type[]) ptypes.Clone ();
2354 ptypes [i] = method_parameter;
2358 // When a lambda expression, an anonymous method
2359 // is used an explicit argument type inference takes a place
2361 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2363 if (am.ExplicitTypeInference (tic, method_parameter))
2368 if (a.Expr is NullLiteral)
2372 // Otherwise an output type inference is made
2374 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2378 // Part of the second phase but because it happens only once
2379 // we don't need to call it in cycle
2381 bool fixed_any = false;
2382 if (!tic.FixIndependentTypeArguments (ptypes, ref fixed_any))
2385 return DoSecondPhase (ec, tic, ptypes, !fixed_any);
2388 bool DoSecondPhase (EmitContext ec, TypeInferenceContext tic, Type[] methodParameters, bool fixDependent)
2390 bool fixed_any = false;
2391 if (fixDependent && !tic.FixDependentTypes (ref fixed_any))
2394 // If no further unfixed type variables exist, type inference succeeds
2395 if (!tic.UnfixedVariableExists)
2398 if (!fixed_any && fixDependent)
2401 // For all arguments where the corresponding argument output types
2402 // contain unfixed type variables but the input types do not,
2403 // an output type inference is made
2404 for (int i = 0; i < arg_count; i++) {
2406 // Align params arguments
2407 Type t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
2409 if (!TypeManager.IsDelegateType (t_i)) {
2410 if (TypeManager.DropGenericTypeArguments (t_i) != TypeManager.expression_type)
2413 t_i = t_i.GetGenericArguments () [0];
2416 MethodInfo mi = Delegate.GetInvokeMethod (t_i, t_i);
2417 Type rtype = mi.ReturnType;
2420 // Blablabla, because reflection does not work with dynamic types
2421 Type[] g_args = t_i.GetGenericArguments ();
2422 rtype = g_args[rtype.GenericParameterPosition];
2425 if (tic.IsReturnTypeNonDependent (mi, rtype))
2426 score -= tic.OutputTypeInference (ec, ((Argument) arguments [i]).Expr, t_i);
2430 return DoSecondPhase (ec, tic, methodParameters, true);
2434 public class TypeInferenceContext
2436 readonly Type[] unfixed_types;
2437 readonly Type[] fixed_types;
2438 readonly ArrayList[] bounds;
2441 public TypeInferenceContext (Type[] typeArguments)
2443 if (typeArguments.Length == 0)
2444 throw new ArgumentException ("Empty generic arguments");
2446 fixed_types = new Type [typeArguments.Length];
2447 for (int i = 0; i < typeArguments.Length; ++i) {
2448 if (typeArguments [i].IsGenericParameter) {
2449 if (bounds == null) {
2450 bounds = new ArrayList [typeArguments.Length];
2451 unfixed_types = new Type [typeArguments.Length];
2453 unfixed_types [i] = typeArguments [i];
2455 fixed_types [i] = typeArguments [i];
2460 public Type[] InferredTypeArguments {
2466 void AddToBounds (Type t, int index)
2469 // Some types cannot be used as type arguments
2471 if (t == TypeManager.void_type || t.IsPointer)
2474 ArrayList a = bounds [index];
2476 a = new ArrayList ();
2484 // SPEC: does not cover type inference using constraints
2486 //if (TypeManager.IsGenericParameter (t)) {
2487 // GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
2488 // if (constraints != null) {
2489 // //if (constraints.EffectiveBaseClass != null)
2490 // // t = constraints.EffectiveBaseClass;
2496 bool AllTypesAreFixed (Type[] types)
2498 foreach (Type t in types) {
2499 if (t.IsGenericParameter) {
2505 if (t.IsGenericType)
2506 return AllTypesAreFixed (t.GetGenericArguments ());
2513 // 26.3.3.8 Exact Inference
2515 public int ExactInference (Type u, Type v)
2517 // If V is an array type
2522 if (u.GetArrayRank () != v.GetArrayRank ())
2525 return ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
2528 // If V is constructed type and U is constructed type
2529 if (v.IsGenericType && !v.IsGenericTypeDefinition) {
2530 if (!u.IsGenericType)
2533 Type [] ga_u = u.GetGenericArguments ();
2534 Type [] ga_v = v.GetGenericArguments ();
2535 if (ga_u.Length != ga_v.Length)
2539 for (int i = 0; i < ga_u.Length; ++i)
2540 score += ExactInference (ga_u [i], ga_v [i]);
2542 return score > 0 ? 1 : 0;
2545 // If V is one of the unfixed type arguments
2546 int pos = IsUnfixed (v);
2550 AddToBounds (u, pos);
2554 public bool FixAllTypes ()
2556 for (int i = 0; i < unfixed_types.Length; ++i) {
2564 // All unfixed type variables Xi are fixed for which all of the following hold:
2565 // a, There is at least one type variable Xj that depends on Xi
2566 // b, Xi has a non-empty set of bounds
2568 public bool FixDependentTypes (ref bool fixed_any)
2570 for (int i = 0; i < unfixed_types.Length; ++i) {
2571 if (unfixed_types[i] == null)
2574 if (bounds[i] == null)
2587 // All unfixed type variables Xi which depend on no Xj are fixed
2589 public bool FixIndependentTypeArguments (Type[] methodParameters, ref bool fixed_any)
2591 ArrayList types_to_fix = new ArrayList (unfixed_types);
2592 for (int i = 0; i < methodParameters.Length; ++i) {
2593 Type t = methodParameters[i];
2594 if (t.IsGenericParameter)
2597 if (!TypeManager.IsDelegateType (t)) {
2598 if (TypeManager.DropGenericTypeArguments (t) != TypeManager.expression_type)
2601 t = t.GetGenericArguments () [0];
2604 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
2605 Type rtype = invoke.ReturnType;
2606 if (!rtype.IsGenericParameter && !rtype.IsGenericType)
2610 // Blablabla, because reflection does not work with dynamic types
2611 if (rtype.IsGenericParameter) {
2612 Type [] g_args = t.GetGenericArguments ();
2613 rtype = g_args [rtype.GenericParameterPosition];
2616 // Remove dependent types, they cannot be fixed yet
2617 RemoveDependentTypes (types_to_fix, rtype);
2620 foreach (Type t in types_to_fix) {
2624 int idx = IsUnfixed (t);
2625 if (idx >= 0 && !FixType (idx)) {
2630 fixed_any = types_to_fix.Count > 0;
2637 public bool FixType (int i)
2639 // It's already fixed
2640 if (unfixed_types[i] == null)
2641 throw new InternalErrorException ("Type argument has been already fixed");
2646 ArrayList candidates = (ArrayList)bounds [i];
2647 if (candidates == null)
2650 if (candidates.Count == 1) {
2651 unfixed_types[i] = null;
2652 fixed_types[i] = (Type)candidates[0];
2657 // Determines a unique type from which there is
2658 // a standard implicit conversion to all the other
2661 Type best_candidate = null;
2663 int candidates_count = candidates.Count;
2664 for (int ci = 0; ci < candidates_count; ++ci) {
2665 Type candidate = (Type)candidates [ci];
2666 for (cii = 0; cii < candidates_count; ++cii) {
2670 if (!Convert.ImplicitConversionExists (null,
2671 new TypeExpression ((Type)candidates [cii], Location.Null), candidate)) {
2676 if (cii != candidates_count)
2679 if (best_candidate != null)
2682 best_candidate = candidate;
2685 if (best_candidate == null)
2688 unfixed_types[i] = null;
2689 fixed_types[i] = best_candidate;
2694 // Uses inferred types to inflate delegate type argument
2696 public Type InflateGenericArgument (Type parameter)
2698 if (parameter.IsGenericParameter) {
2700 // Inflate method generic argument (MVAR) only
2702 if (parameter.DeclaringMethod == null)
2705 return fixed_types [parameter.GenericParameterPosition];
2708 if (parameter.IsGenericType) {
2709 Type [] parameter_targs = parameter.GetGenericArguments ();
2710 for (int ii = 0; ii < parameter_targs.Length; ++ii) {
2711 parameter_targs [ii] = InflateGenericArgument (parameter_targs [ii]);
2713 return parameter.GetGenericTypeDefinition ().MakeGenericType (parameter_targs);
2720 // Tests whether all delegate input arguments are fixed and generic output type
2721 // requires output type inference
2723 public bool IsReturnTypeNonDependent (MethodInfo invoke, Type returnType)
2725 if (returnType.IsGenericParameter) {
2726 if (IsFixed (returnType))
2728 } else if (returnType.IsGenericType) {
2729 if (TypeManager.IsDelegateType (returnType)) {
2730 invoke = Delegate.GetInvokeMethod (returnType, returnType);
2731 return IsReturnTypeNonDependent (invoke, invoke.ReturnType);
2734 Type[] g_args = returnType.GetGenericArguments ();
2736 // At least one unfixed return type has to exist
2737 if (AllTypesAreFixed (g_args))
2743 // All generic input arguments have to be fixed
2744 AParametersCollection d_parameters = TypeManager.GetParameterData (invoke);
2745 return AllTypesAreFixed (d_parameters.Types);
2748 bool IsFixed (Type type)
2750 return IsUnfixed (type) == -1;
2753 int IsUnfixed (Type type)
2755 if (!type.IsGenericParameter)
2758 //return unfixed_types[type.GenericParameterPosition] != null;
2759 for (int i = 0; i < unfixed_types.Length; ++i) {
2760 if (unfixed_types [i] == type)
2768 // 26.3.3.9 Lower-bound Inference
2770 public int LowerBoundInference (Type u, Type v)
2772 // If V is one of the unfixed type arguments
2773 int pos = IsUnfixed (v);
2775 AddToBounds (u, pos);
2779 // If U is an array type
2781 int u_dim = u.GetArrayRank ();
2783 Type u_e = TypeManager.GetElementType (u);
2786 if (u_dim != v.GetArrayRank ())
2789 v_e = TypeManager.GetElementType (v);
2792 return LowerBoundInference (u_e, v_e);
2795 return ExactInference (u_e, v_e);
2801 if (v.IsGenericType) {
2802 Type g_v = v.GetGenericTypeDefinition ();
2803 if ((g_v != TypeManager.generic_ilist_type) && (g_v != TypeManager.generic_icollection_type) &&
2804 (g_v != TypeManager.generic_ienumerable_type))
2807 v_e = TypeManager.GetTypeArguments (v)[0];
2810 return LowerBoundInference (u_e, v_e);
2813 return ExactInference (u_e, v_e);
2815 } else if (v.IsGenericType && !v.IsGenericTypeDefinition) {
2817 // if V is a constructed type C<V1..Vk> and there is a unique set of types U1..Uk
2818 // such that a standard implicit conversion exists from U to C<U1..Uk> then an exact
2819 // inference is made from each Ui for the corresponding Vi
2821 ArrayList u_candidates = new ArrayList ();
2822 if (u.IsGenericType)
2823 u_candidates.Add (u);
2825 for (Type t = u.BaseType; t != null; t = t.BaseType) {
2826 if (t.IsGenericType && !t.IsGenericTypeDefinition)
2827 u_candidates.Add (t);
2830 // TODO: Implement GetGenericInterfaces only and remove
2831 // the if from foreach
2832 u_candidates.AddRange (TypeManager.GetInterfaces (u));
2834 Type open_v = v.GetGenericTypeDefinition ();
2835 Type [] unique_candidate_targs = null;
2836 Type [] ga_v = v.GetGenericArguments ();
2837 foreach (Type u_candidate in u_candidates) {
2838 if (!u_candidate.IsGenericType || u_candidate.IsGenericTypeDefinition)
2841 if (TypeManager.DropGenericTypeArguments (u_candidate) != open_v)
2845 // The unique set of types U1..Uk means that if we have an interface C<T>,
2846 // class U: C<int>, C<long> then no type inference is made when inferring
2847 // from U to C<T> because T could be int or long
2849 if (unique_candidate_targs != null) {
2850 Type[] second_unique_candidate_targs = u_candidate.GetGenericArguments ();
2851 if (TypeManager.IsEqual (unique_candidate_targs, second_unique_candidate_targs)) {
2852 unique_candidate_targs = second_unique_candidate_targs;
2857 // This should always cause type inference failure
2863 unique_candidate_targs = u_candidate.GetGenericArguments ();
2866 if (unique_candidate_targs != null) {
2868 for (int i = 0; i < unique_candidate_targs.Length; ++i)
2869 if (ExactInference (unique_candidate_targs [i], ga_v [i]) == 0)
2879 // 26.3.3.6 Output Type Inference
2881 public int OutputTypeInference (EmitContext ec, Expression e, Type t)
2883 // If e is a lambda or anonymous method with inferred return type
2884 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
2886 Type rt = ame.InferReturnType (ec, this, t);
2887 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
2890 AParametersCollection pd = TypeManager.GetParameterData (invoke);
2891 return ame.Parameters.Count == pd.Count ? 1 : 0;
2894 Type rtype = invoke.ReturnType;
2896 // Blablabla, because reflection does not work with dynamic types
2897 Type [] g_args = t.GetGenericArguments ();
2898 rtype = g_args [rtype.GenericParameterPosition];
2900 return LowerBoundInference (rt, rtype) + 1;
2904 // if E is a method group and T is a delegate type or expression tree type
2905 // return type Tb with parameter types T1..Tk and return type Tb, and overload
2906 // resolution of E with the types T1..Tk yields a single method with return type U,
2907 // then a lower-bound inference is made from U for Tb.
2909 if (e is MethodGroupExpr) {
2910 // TODO: Or expression tree
2911 if (!TypeManager.IsDelegateType (t))
2914 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
2915 Type rtype = invoke.ReturnType;
2917 // Blablabla, because reflection does not work with dynamic types
2918 Type [] g_args = t.GetGenericArguments ();
2919 rtype = g_args [rtype.GenericParameterPosition];
2922 if (!TypeManager.IsGenericType (rtype))
2925 MethodGroupExpr mg = (MethodGroupExpr) e;
2926 ArrayList args = DelegateCreation.CreateDelegateMethodArguments (invoke, e.Location);
2927 mg = mg.OverloadResolve (ec, ref args, true, e.Location);
2931 // TODO: What should happen when return type is of generic type ?
2932 throw new NotImplementedException ();
2933 // return LowerBoundInference (null, rtype) + 1;
2937 // if e is an expression with type U, then
2938 // a lower-bound inference is made from U for T
2940 return LowerBoundInference (e.Type, t) * 2;
2943 static void RemoveDependentTypes (ArrayList types, Type returnType)
2945 if (returnType.IsGenericParameter) {
2946 types [returnType.GenericParameterPosition] = null;
2950 if (returnType.IsGenericType) {
2951 foreach (Type t in returnType.GetGenericArguments ()) {
2952 RemoveDependentTypes (types, t);
2957 public bool UnfixedVariableExists {
2959 if (unfixed_types == null)
2962 foreach (Type ut in unfixed_types)