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 ();
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) {
260 Report.Error (406, loc,
261 "`{0}': the class constraint for `{1}' " +
262 "must come before any other constraints.",
263 expr.GetSignatureForError (), name);
265 } else if (HasReferenceTypeConstraint || HasValueTypeConstraint) {
266 Report.Error (450, loc, "`{0}': cannot specify both " +
267 "a constraint class and the `class' " +
268 "or `struct' constraint", expr.GetSignatureForError ());
271 class_constraint = expr;
276 ArrayList list = new ArrayList ();
277 foreach (TypeExpr iface_constraint in iface_constraints) {
278 foreach (Type type in list) {
279 if (!type.Equals (iface_constraint.Type))
282 Report.Error (405, loc,
283 "Duplicate constraint `{0}' for type " +
284 "parameter `{1}'.", iface_constraint.GetSignatureForError (),
289 list.Add (iface_constraint.Type);
292 foreach (TypeParameterExpr expr in type_param_constraints) {
293 foreach (Type type in list) {
294 if (!type.Equals (expr.Type))
297 Report.Error (405, loc,
298 "Duplicate constraint `{0}' for type " +
299 "parameter `{1}'.", expr.GetSignatureForError (), name);
303 list.Add (expr.Type);
306 iface_constraint_types = new Type [list.Count];
307 list.CopyTo (iface_constraint_types, 0);
309 if (class_constraint != null) {
310 class_constraint_type = class_constraint.Type;
311 if (class_constraint_type == null)
314 if (class_constraint_type.IsSealed) {
315 if (class_constraint_type.IsAbstract)
317 Report.Error (717, loc, "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
318 TypeManager.CSharpName (class_constraint_type));
322 Report.Error (701, loc, "`{0}' is not a valid constraint. A constraint must be an interface, " +
323 "a non-sealed class or a type parameter", TypeManager.CSharpName(class_constraint_type));
328 if ((class_constraint_type == TypeManager.array_type) ||
329 (class_constraint_type == TypeManager.delegate_type) ||
330 (class_constraint_type == TypeManager.enum_type) ||
331 (class_constraint_type == TypeManager.value_type) ||
332 (class_constraint_type == TypeManager.object_type) ||
333 class_constraint_type == TypeManager.multicast_delegate_type) {
334 Report.Error (702, loc,
335 "A constraint cannot be special class `{0}'",
336 TypeManager.CSharpName (class_constraint_type));
341 if (class_constraint_type != null)
342 effective_base_type = class_constraint_type;
343 else if (HasValueTypeConstraint)
344 effective_base_type = TypeManager.value_type;
346 effective_base_type = TypeManager.object_type;
352 bool CheckTypeParameterConstraints (TypeParameter tparam, Hashtable seen)
354 seen.Add (tparam, true);
356 Constraints constraints = tparam.Constraints;
357 if (constraints == null)
360 if (constraints.HasValueTypeConstraint) {
361 Report.Error (456, loc, "Type parameter `{0}' has " +
362 "the `struct' constraint, so it cannot " +
363 "be used as a constraint for `{1}'",
368 if (constraints.type_param_constraints == null)
371 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
372 if (seen.Contains (expr.TypeParameter)) {
373 Report.Error (454, loc, "Circular constraint " +
374 "dependency involving `{0}' and `{1}'",
375 tparam.Name, expr.GetSignatureForError ());
379 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
387 /// Resolve the constraints into actual types.
389 public bool ResolveTypes (IResolveContext ec)
394 resolved_types = true;
396 foreach (object obj in constraints) {
397 ConstructedType cexpr = obj as ConstructedType;
401 if (!cexpr.CheckConstraints (ec))
405 foreach (TypeParameterExpr expr in type_param_constraints) {
406 Hashtable seen = new Hashtable ();
407 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
411 for (int i = 0; i < iface_constraints.Count; ++i) {
412 TypeExpr iface_constraint = (TypeExpr) iface_constraints [i];
413 iface_constraint = iface_constraint.ResolveAsTypeTerminal (ec, false);
414 if (iface_constraint == null)
416 iface_constraints [i] = iface_constraint;
419 if (class_constraint != null) {
420 class_constraint = class_constraint.ResolveAsTypeTerminal (ec, false);
421 if (class_constraint == null)
429 /// Check whether there are no conflicts in our type parameter constraints.
431 /// This is an example:
435 /// where U : T, struct
437 public bool CheckDependencies ()
439 foreach (TypeParameterExpr expr in type_param_constraints) {
440 if (!CheckDependencies (expr.TypeParameter))
447 bool CheckDependencies (TypeParameter tparam)
449 Constraints constraints = tparam.Constraints;
450 if (constraints == null)
453 if (HasValueTypeConstraint && constraints.HasClassConstraint) {
454 Report.Error (455, loc, "Type parameter `{0}' inherits " +
455 "conflicting constraints `{1}' and `{2}'",
456 name, TypeManager.CSharpName (constraints.ClassConstraint),
461 if (HasClassConstraint && constraints.HasClassConstraint) {
462 Type t1 = ClassConstraint;
463 TypeExpr e1 = class_constraint;
464 Type t2 = constraints.ClassConstraint;
465 TypeExpr e2 = constraints.class_constraint;
467 if (!Convert.ImplicitReferenceConversionExists (e1, t2) &&
468 !Convert.ImplicitReferenceConversionExists (e2, t1)) {
469 Report.Error (455, loc,
470 "Type parameter `{0}' inherits " +
471 "conflicting constraints `{1}' and `{2}'",
472 name, TypeManager.CSharpName (t1), TypeManager.CSharpName (t2));
477 if (constraints.type_param_constraints == null)
480 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
481 if (!CheckDependencies (expr.TypeParameter))
488 public override GenericParameterAttributes Attributes {
489 get { return attrs; }
492 public override bool HasClassConstraint {
493 get { return class_constraint != null; }
496 public override Type ClassConstraint {
497 get { return class_constraint_type; }
500 public override Type[] InterfaceConstraints {
501 get { return iface_constraint_types; }
504 public override Type EffectiveBaseClass {
505 get { return effective_base_type; }
508 public bool IsSubclassOf (Type t)
510 if ((class_constraint_type != null) &&
511 class_constraint_type.IsSubclassOf (t))
514 if (iface_constraint_types == null)
517 foreach (Type iface in iface_constraint_types) {
518 if (TypeManager.IsSubclassOf (iface, t))
525 public Location Location {
532 /// This is used when we're implementing a generic interface method.
533 /// Each method type parameter in implementing method must have the same
534 /// constraints than the corresponding type parameter in the interface
535 /// method. To do that, we're called on each of the implementing method's
538 public bool AreEqual (GenericConstraints gc)
540 if (gc.Attributes != attrs)
543 if (HasClassConstraint != gc.HasClassConstraint)
545 if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
548 int gc_icount = gc.InterfaceConstraints != null ?
549 gc.InterfaceConstraints.Length : 0;
550 int icount = InterfaceConstraints != null ?
551 InterfaceConstraints.Length : 0;
553 if (gc_icount != icount)
556 for (int i = 0; i < gc.InterfaceConstraints.Length; ++i) {
557 Type iface = gc.InterfaceConstraints [i];
558 if (iface.IsGenericType)
559 iface = iface.GetGenericTypeDefinition ();
562 for (int ii = 0; i < InterfaceConstraints.Length; ++ii) {
563 Type check = InterfaceConstraints [ii];
564 if (check.IsGenericType)
565 check = check.GetGenericTypeDefinition ();
567 if (TypeManager.IsEqual (iface, check)) {
580 public void VerifyClsCompliance ()
582 if (class_constraint_type != null && !AttributeTester.IsClsCompliant (class_constraint_type))
583 Warning_ConstrainIsNotClsCompliant (class_constraint_type, class_constraint.Location);
585 if (iface_constraint_types != null) {
586 for (int i = 0; i < iface_constraint_types.Length; ++i) {
587 if (!AttributeTester.IsClsCompliant (iface_constraint_types [i]))
588 Warning_ConstrainIsNotClsCompliant (iface_constraint_types [i],
589 ((TypeExpr)iface_constraints [i]).Location);
594 void Warning_ConstrainIsNotClsCompliant (Type t, Location loc)
596 Report.SymbolRelatedToPreviousError (t);
597 Report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
598 TypeManager.CSharpName (t));
603 /// A type parameter from a generic type definition.
605 public class TypeParameter : MemberCore, IMemberContainer
607 static readonly string[] attribute_target = new string [] { "type parameter" };
611 GenericConstraints gc;
612 Constraints constraints;
613 GenericTypeParameterBuilder type;
614 MemberCache member_cache;
616 public TypeParameter (DeclSpace parent, DeclSpace decl, string name,
617 Constraints constraints, Attributes attrs, Location loc)
618 : base (parent, new MemberName (name, loc), attrs)
622 this.constraints = constraints;
625 public GenericConstraints GenericConstraints {
626 get { return gc != null ? gc : constraints; }
629 public Constraints Constraints {
630 get { return constraints; }
633 public DeclSpace DeclSpace {
642 /// This is the first method which is called during the resolving
643 /// process; we're called immediately after creating the type parameters
644 /// with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
647 /// We're either called from TypeContainer.DefineType() or from
648 /// GenericMethod.Define() (called from Method.Define()).
650 public void Define (GenericTypeParameterBuilder type)
652 if (this.type != null)
653 throw new InvalidOperationException ();
656 TypeManager.AddTypeParameter (type, this);
660 /// This is the second method which is called during the resolving
661 /// process - in case of class type parameters, we're called from
662 /// TypeContainer.ResolveType() - after it resolved the class'es
663 /// base class and interfaces. For method type parameters, we're
664 /// called immediately after Define().
666 /// We're just resolving the constraints into expressions here, we
667 /// don't resolve them into actual types.
669 /// Note that in the special case of partial generic classes, we may be
670 /// called _before_ Define() and we may also be called multiple types.
672 public bool Resolve (DeclSpace ds)
674 if (constraints != null) {
675 if (!constraints.Resolve (ds)) {
685 /// This is the third method which is called during the resolving
686 /// process. We're called immediately after calling DefineConstraints()
687 /// on all of the current class'es type parameters.
689 /// Our job is to resolve the constraints to actual types.
691 /// Note that we may have circular dependencies on type parameters - this
692 /// is why Resolve() and ResolveType() are separate.
694 public bool ResolveType (IResolveContext ec)
696 if (constraints != null) {
697 if (!constraints.ResolveTypes (ec)) {
707 /// This is the fourth and last method which is called during the resolving
708 /// process. We're called after everything is fully resolved and actually
709 /// register the constraints with SRE and the TypeManager.
711 public bool DefineType (IResolveContext ec)
713 return DefineType (ec, null, null, false);
717 /// This is the fith and last method which is called during the resolving
718 /// process. We're called after everything is fully resolved and actually
719 /// register the constraints with SRE and the TypeManager.
721 /// The `builder', `implementing' and `is_override' arguments are only
722 /// applicable to method type parameters.
724 public bool DefineType (IResolveContext ec, MethodBuilder builder,
725 MethodInfo implementing, bool is_override)
727 if (!ResolveType (ec))
730 if (implementing != null) {
731 if (is_override && (constraints != null)) {
732 Report.Error (460, Location,
733 "`{0}': Cannot specify constraints for overrides or explicit interface implementation methods",
734 TypeManager.CSharpSignature (builder));
738 MethodBase mb = TypeManager.DropGenericMethodArguments (implementing);
740 int pos = type.GenericParameterPosition;
741 Type mparam = mb.GetGenericArguments () [pos];
742 GenericConstraints temp_gc = ReflectionConstraints.GetConstraints (mparam);
745 gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
746 else if (constraints != null)
747 gc = new InflatedConstraints (constraints, implementing.DeclaringType);
750 if (constraints != null) {
753 else if (!constraints.AreEqual (gc))
756 if (!is_override && (temp_gc != null))
761 Report.SymbolRelatedToPreviousError (implementing);
764 425, Location, "The constraints for type " +
765 "parameter `{0}' of method `{1}' must match " +
766 "the constraints for type parameter `{2}' " +
767 "of interface method `{3}'. Consider using " +
768 "an explicit interface implementation instead",
769 Name, TypeManager.CSharpSignature (builder),
770 TypeManager.CSharpName (mparam), TypeManager.CSharpSignature (mb));
773 } else if (DeclSpace is CompilerGeneratedClass) {
774 TypeParameter[] tparams = DeclSpace.TypeParameters;
775 Type[] types = new Type [tparams.Length];
776 for (int i = 0; i < tparams.Length; i++)
777 types [i] = tparams [i].Type;
779 if (constraints != null)
780 gc = new InflatedConstraints (constraints, types);
782 gc = (GenericConstraints) constraints;
788 if (gc.HasClassConstraint)
789 type.SetBaseTypeConstraint (gc.ClassConstraint);
791 type.SetInterfaceConstraints (gc.InterfaceConstraints);
792 type.SetGenericParameterAttributes (gc.Attributes);
793 TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
799 /// Check whether there are no conflicts in our type parameter constraints.
801 /// This is an example:
805 /// where U : T, struct
807 public bool CheckDependencies ()
809 if (constraints != null)
810 return constraints.CheckDependencies ();
816 /// This is called for each part of a partial generic type definition.
818 /// If `new_constraints' is not null and we don't already have constraints,
819 /// they become our constraints. If we already have constraints, we must
820 /// check that they're the same.
823 public bool UpdateConstraints (IResolveContext ec, Constraints new_constraints)
826 throw new InvalidOperationException ();
828 if (new_constraints == null)
831 if (!new_constraints.Resolve (ec))
833 if (!new_constraints.ResolveTypes (ec))
836 if (constraints != null)
837 return constraints.AreEqual (new_constraints);
839 constraints = new_constraints;
843 public override void Emit ()
845 if (OptAttributes != null)
846 OptAttributes.Emit ();
851 public override string DocCommentHeader {
853 throw new InvalidOperationException (
854 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
862 public override bool Define ()
867 public override void ApplyAttributeBuilder (Attribute a,
868 CustomAttributeBuilder cb)
870 type.SetCustomAttribute (cb);
873 public override AttributeTargets AttributeTargets {
875 return AttributeTargets.GenericParameter;
879 public override string[] ValidAttributeTargets {
881 return attribute_target;
889 string IMemberContainer.Name {
893 MemberCache IMemberContainer.BaseCache {
898 if (gc.EffectiveBaseClass.BaseType == null)
901 return TypeManager.LookupMemberCache (gc.EffectiveBaseClass.BaseType);
905 bool IMemberContainer.IsInterface {
906 get { return false; }
909 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
911 throw new NotSupportedException ();
914 public MemberCache MemberCache {
916 if (member_cache != null)
922 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
923 member_cache = new MemberCache (this, gc.EffectiveBaseClass, ifaces);
929 public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
930 MemberFilter filter, object criteria)
933 return MemberList.Empty;
935 ArrayList members = new ArrayList ();
937 if (gc.HasClassConstraint) {
938 MemberList list = TypeManager.FindMembers (
939 gc.ClassConstraint, mt, bf, filter, criteria);
941 members.AddRange (list);
944 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
945 foreach (Type t in ifaces) {
946 MemberList list = TypeManager.FindMembers (
947 t, mt, bf, filter, criteria);
949 members.AddRange (list);
952 return new MemberList (members);
955 public bool IsSubclassOf (Type t)
960 if (constraints != null)
961 return constraints.IsSubclassOf (t);
966 public override string ToString ()
968 return "TypeParameter[" + name + "]";
971 public static string GetSignatureForError (TypeParameter[] tp)
973 if (tp == null || tp.Length == 0)
976 StringBuilder sb = new StringBuilder ("<");
977 for (int i = 0; i < tp.Length; ++i) {
980 sb.Append (tp[i].GetSignatureForError ());
983 return sb.ToString ();
986 public void InflateConstraints (Type declaring)
988 if (constraints != null)
989 gc = new InflatedConstraints (constraints, declaring);
992 public override bool IsClsComplianceRequired ()
997 protected class InflatedConstraints : GenericConstraints
999 GenericConstraints gc;
1001 Type class_constraint;
1002 Type[] iface_constraints;
1005 public InflatedConstraints (GenericConstraints gc, Type declaring)
1006 : this (gc, TypeManager.GetTypeArguments (declaring))
1009 public InflatedConstraints (GenericConstraints gc, Type[] dargs)
1014 ArrayList list = new ArrayList ();
1015 if (gc.HasClassConstraint)
1016 list.Add (inflate (gc.ClassConstraint));
1017 foreach (Type iface in gc.InterfaceConstraints)
1018 list.Add (inflate (iface));
1020 bool has_class_constr = false;
1021 if (list.Count > 0) {
1022 Type first = (Type) list [0];
1023 has_class_constr = !first.IsGenericParameter && !first.IsInterface;
1026 if ((list.Count > 0) && has_class_constr) {
1027 class_constraint = (Type) list [0];
1028 iface_constraints = new Type [list.Count - 1];
1029 list.CopyTo (1, iface_constraints, 0, list.Count - 1);
1031 iface_constraints = new Type [list.Count];
1032 list.CopyTo (iface_constraints, 0);
1035 if (HasValueTypeConstraint)
1036 base_type = TypeManager.value_type;
1037 else if (class_constraint != null)
1038 base_type = class_constraint;
1040 base_type = TypeManager.object_type;
1043 Type inflate (Type t)
1047 if (t.IsGenericParameter)
1048 return dargs [t.GenericParameterPosition];
1049 if (t.IsGenericType) {
1050 Type[] args = t.GetGenericArguments ();
1051 Type[] inflated = new Type [args.Length];
1053 for (int i = 0; i < args.Length; i++)
1054 inflated [i] = inflate (args [i]);
1056 t = t.GetGenericTypeDefinition ();
1057 t = t.MakeGenericType (inflated);
1063 public override string TypeParameter {
1064 get { return gc.TypeParameter; }
1067 public override GenericParameterAttributes Attributes {
1068 get { return gc.Attributes; }
1071 public override Type ClassConstraint {
1072 get { return class_constraint; }
1075 public override Type EffectiveBaseClass {
1076 get { return base_type; }
1079 public override Type[] InterfaceConstraints {
1080 get { return iface_constraints; }
1086 /// A TypeExpr which already resolved to a type parameter.
1088 public class TypeParameterExpr : TypeExpr {
1089 TypeParameter type_parameter;
1091 public TypeParameter TypeParameter {
1093 return type_parameter;
1097 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1099 this.type_parameter = type_parameter;
1103 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1105 type = type_parameter.Type;
1110 public override bool IsInterface {
1111 get { return false; }
1114 public override bool CheckAccessLevel (DeclSpace ds)
1121 /// Tracks the type arguments when instantiating a generic type. We're used in
1122 /// ConstructedType.
1124 public class TypeArguments {
1125 public readonly Location Location;
1132 public TypeArguments (Location loc)
1134 args = new ArrayList ();
1135 this.Location = loc;
1138 public TypeArguments (Location loc, params Expression[] types)
1140 this.Location = loc;
1141 this.args = new ArrayList (types);
1144 public TypeArguments (int dimension, Location loc)
1146 this.dimension = dimension;
1147 this.Location = loc;
1150 public void Add (Expression type)
1153 throw new InvalidOperationException ();
1158 public void Add (TypeArguments new_args)
1161 throw new InvalidOperationException ();
1163 args.AddRange (new_args.args);
1167 /// We're used during the parsing process: the parser can't distinguish
1168 /// between type parameters and type arguments. Because of that, the
1169 /// parser creates a `MemberName' with `TypeArguments' for both cases and
1170 /// in case of a generic type definition, we call GetDeclarations().
1172 public TypeParameterName[] GetDeclarations ()
1174 TypeParameterName[] ret = new TypeParameterName [args.Count];
1175 for (int i = 0; i < args.Count; i++) {
1176 TypeParameterName name = args [i] as TypeParameterName;
1181 SimpleName sn = args [i] as SimpleName;
1182 if (sn != null && !sn.HasTypeArguments) {
1183 ret [i] = new TypeParameterName (sn.Name, null, sn.Location);
1187 Expression expr = (Expression) args [i];
1188 // TODO: Wrong location
1189 Report.Error (81, Location, "Type parameter declaration must be an identifier not a type");
1190 ret [i] = new TypeParameterName (expr.GetSignatureForError (), null, expr.Location);
1196 /// We may only be used after Resolve() is called and return the fully
1199 public Type[] Arguments {
1205 public bool HasTypeArguments {
1207 return has_type_args;
1220 public bool IsUnbound {
1222 return dimension > 0;
1226 public override string ToString ()
1228 StringBuilder s = new StringBuilder ();
1231 for (int i = 0; i < count; i++){
1233 // FIXME: Use TypeManager.CSharpname once we have the type
1236 s.Append (args [i].ToString ());
1240 return s.ToString ();
1243 public string GetSignatureForError()
1245 StringBuilder sb = new StringBuilder();
1246 for (int i = 0; i < Count; ++i)
1248 Expression expr = (Expression)args [i];
1249 sb.Append(expr.GetSignatureForError());
1253 return sb.ToString();
1257 /// Resolve the type arguments.
1259 public bool Resolve (IResolveContext ec)
1261 int count = args.Count;
1264 atypes = new Type [count];
1266 for (int i = 0; i < count; i++){
1267 TypeExpr te = ((Expression) args [i]).ResolveAsTypeTerminal (ec, false);
1273 atypes[i] = te.Type;
1274 if (te.Type.IsGenericParameter) {
1275 if (te is TypeParameterExpr)
1276 has_type_args = true;
1280 if (te.Type.IsSealed && te.Type.IsAbstract) {
1281 Report.Error (718, Location, "`{0}': static classes cannot be used as generic arguments",
1282 te.GetSignatureForError ());
1286 if (te.Type.IsPointer) {
1287 Report.Error (306, Location, "The type `{0}' may not be used " +
1288 "as a type argument", TypeManager.CSharpName (te.Type));
1292 if (te.Type == TypeManager.void_type) {
1293 Expression.Error_VoidInvalidInTheContext (Location);
1300 public TypeArguments Clone ()
1302 TypeArguments copy = new TypeArguments (Location);
1303 foreach (Expression ta in args)
1310 public class TypeParameterName : SimpleName
1312 Attributes attributes;
1314 public TypeParameterName (string name, Attributes attrs, Location loc)
1320 public Attributes OptAttributes {
1328 /// An instantiation of a generic type.
1330 public class ConstructedType : TypeExpr {
1331 FullNamedExpression name;
1333 Type[] gen_params, atypes;
1337 /// Instantiate the generic type `fname' with the type arguments `args'.
1339 public ConstructedType (FullNamedExpression fname, TypeArguments args, Location l)
1345 eclass = ExprClass.Type;
1349 /// This is used to construct the `this' type inside a generic type definition.
1351 public ConstructedType (Type t, TypeParameter[] type_params, Location l)
1353 gt = t.GetGenericTypeDefinition ();
1355 args = new TypeArguments (l);
1356 foreach (TypeParameter type_param in type_params)
1357 args.Add (new TypeParameterExpr (type_param, l));
1360 this.name = new TypeExpression (gt, l);
1361 eclass = ExprClass.Type;
1365 /// Instantiate the generic type `t' with the type arguments `args'.
1366 /// Use this constructor if you already know the fully resolved
1369 public ConstructedType (Type t, TypeArguments args, Location l)
1370 : this ((FullNamedExpression)null, args, l)
1372 gt = t.GetGenericTypeDefinition ();
1373 this.name = new TypeExpression (gt, l);
1376 public TypeArguments TypeArguments {
1377 get { return args; }
1380 public override string GetSignatureForError ()
1382 return TypeManager.RemoveGenericArity (gt.FullName) + "<" + args.GetSignatureForError () + ">";
1385 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1387 if (!ResolveConstructedType (ec))
1394 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1395 /// after fully resolving the constructed type.
1397 public bool CheckConstraints (IResolveContext ec)
1399 return ConstraintChecker.CheckConstraints (ec, gt, gen_params, atypes, loc);
1403 /// Resolve the constructed type, but don't check the constraints.
1405 public bool ResolveConstructedType (IResolveContext ec)
1409 // If we already know the fully resolved generic type.
1411 return DoResolveType (ec);
1417 Report.Error (246, loc, "Cannot find type `{0}'<...>", GetSignatureForError ());
1421 num_args = TypeManager.GetNumberOfTypeArguments (t);
1422 if (num_args == 0) {
1423 Report.Error (308, loc,
1424 "The non-generic type `{0}' cannot " +
1425 "be used with type arguments.",
1426 TypeManager.CSharpName (t));
1430 gt = t.GetGenericTypeDefinition ();
1431 return DoResolveType (ec);
1434 bool DoResolveType (IResolveContext ec)
1437 // Resolve the arguments.
1439 if (args.Resolve (ec) == false)
1442 gen_params = gt.GetGenericArguments ();
1443 atypes = args.Arguments;
1445 if (atypes.Length != gen_params.Length) {
1446 Report.Error (305, loc,
1447 "Using the generic type `{0}' " +
1448 "requires {1} type arguments",
1449 TypeManager.CSharpName (gt),
1450 gen_params.Length.ToString ());
1455 // Now bind the parameters.
1457 type = gt.MakeGenericType (atypes);
1461 public Expression GetSimpleName (EmitContext ec)
1466 public override bool CheckAccessLevel (DeclSpace ds)
1468 return ds.CheckAccessLevel (gt);
1471 public override bool AsAccessible (DeclSpace ds)
1473 foreach (Type t in atypes) {
1474 if (!ds.IsAccessibleAs (t))
1478 return ds.IsAccessibleAs (gt);
1481 public override bool IsClass {
1482 get { return gt.IsClass; }
1485 public override bool IsValueType {
1486 get { return gt.IsValueType; }
1489 public override bool IsInterface {
1490 get { return gt.IsInterface; }
1493 public override bool IsSealed {
1494 get { return gt.IsSealed; }
1497 public override bool Equals (object obj)
1499 ConstructedType cobj = obj as ConstructedType;
1503 if ((type == null) || (cobj.type == null))
1506 return type == cobj.type;
1509 public override int GetHashCode ()
1511 return base.GetHashCode ();
1515 public abstract class ConstraintChecker
1517 protected readonly Type[] gen_params;
1518 protected readonly Type[] atypes;
1519 protected readonly Location loc;
1521 protected ConstraintChecker (Type[] gen_params, Type[] atypes, Location loc)
1523 this.gen_params = gen_params;
1524 this.atypes = atypes;
1529 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1530 /// after fully resolving the constructed type.
1532 public bool CheckConstraints (IResolveContext ec)
1534 for (int i = 0; i < gen_params.Length; i++) {
1535 if (!CheckConstraints (ec, i))
1542 protected bool CheckConstraints (IResolveContext ec, int index)
1544 Type atype = atypes [index];
1545 Type ptype = gen_params [index];
1550 Expression aexpr = new EmptyExpression (atype);
1552 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1556 bool is_class, is_struct;
1557 if (atype.IsGenericParameter) {
1558 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1560 if (agc is Constraints)
1561 ((Constraints) agc).Resolve (ec);
1562 is_class = agc.IsReferenceType;
1563 is_struct = agc.IsValueType;
1565 is_class = is_struct = false;
1570 if (!atype.IsGenericType)
1572 is_class = atype.IsClass || atype.IsInterface;
1573 is_struct = atype.IsValueType && !TypeManager.IsNullableType (atype);
1577 // First, check the `class' and `struct' constraints.
1579 if (gc.HasReferenceTypeConstraint && !is_class) {
1580 Report.Error (452, loc, "The type `{0}' must be " +
1581 "a reference type in order to use it " +
1582 "as type parameter `{1}' in the " +
1583 "generic type or method `{2}'.",
1584 TypeManager.CSharpName (atype),
1585 TypeManager.CSharpName (ptype),
1586 GetSignatureForError ());
1588 } else if (gc.HasValueTypeConstraint && !is_struct) {
1589 Report.Error (453, loc, "The type `{0}' must be a " +
1590 "non-nullable value type in order to use it " +
1591 "as type parameter `{1}' in the " +
1592 "generic type or method `{2}'.",
1593 TypeManager.CSharpName (atype),
1594 TypeManager.CSharpName (ptype),
1595 GetSignatureForError ());
1600 // The class constraint comes next.
1602 if (gc.HasClassConstraint) {
1603 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint))
1608 // Now, check the interface constraints.
1610 if (gc.InterfaceConstraints != null) {
1611 foreach (Type it in gc.InterfaceConstraints) {
1612 if (!CheckConstraint (ec, ptype, aexpr, it))
1618 // Finally, check the constructor constraint.
1621 if (!gc.HasConstructorConstraint)
1624 if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
1627 if (HasDefaultConstructor (atype))
1630 Report_SymbolRelatedToPreviousError ();
1631 Report.SymbolRelatedToPreviousError (atype);
1632 Report.Error (310, loc, "The type `{0}' must have a public " +
1633 "parameterless constructor in order to use it " +
1634 "as parameter `{1}' in the generic type or " +
1636 TypeManager.CSharpName (atype),
1637 TypeManager.CSharpName (ptype),
1638 GetSignatureForError ());
1642 protected bool CheckConstraint (IResolveContext ec, Type ptype, Expression expr,
1645 if (TypeManager.HasGenericArguments (ctype)) {
1646 Type[] types = TypeManager.GetTypeArguments (ctype);
1648 TypeArguments new_args = new TypeArguments (loc);
1650 for (int i = 0; i < types.Length; i++) {
1653 if (t.IsGenericParameter) {
1654 int pos = t.GenericParameterPosition;
1657 new_args.Add (new TypeExpression (t, loc));
1660 TypeExpr ct = new ConstructedType (ctype, new_args, loc);
1661 if (ct.ResolveAsTypeStep (ec, false) == null)
1664 } else if (ctype.IsGenericParameter) {
1665 int pos = ctype.GenericParameterPosition;
1666 ctype = atypes [pos];
1669 if (Convert.ImplicitStandardConversionExists (expr, ctype))
1672 Error_TypeMustBeConvertible (expr.Type, ctype, ptype);
1676 static bool HasDefaultConstructor (Type atype)
1678 TypeParameter tparam = TypeManager.LookupTypeParameter (atype);
1679 if (tparam != null) {
1680 if (tparam.GenericConstraints == null)
1683 return tparam.GenericConstraints.HasConstructorConstraint ||
1684 tparam.GenericConstraints.HasValueTypeConstraint;
1687 if (atype.IsAbstract)
1691 atype = TypeManager.DropGenericTypeArguments (atype);
1692 if (atype is TypeBuilder) {
1693 TypeContainer tc = TypeManager.LookupTypeContainer (atype);
1694 if (tc.InstanceConstructors == null) {
1695 atype = atype.BaseType;
1699 foreach (Constructor c in tc.InstanceConstructors) {
1700 if ((c.ModFlags & Modifiers.PUBLIC) == 0)
1702 if ((c.Parameters.FixedParameters != null) &&
1703 (c.Parameters.FixedParameters.Length != 0))
1705 if (c.Parameters.HasArglist || c.Parameters.HasParams)
1712 MemberInfo [] list = TypeManager.MemberLookup (null, null, atype, MemberTypes.Constructor,
1713 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
1714 ConstructorInfo.ConstructorName, null);
1719 foreach (MethodBase mb in list) {
1720 AParametersCollection pd = TypeManager.GetParameterData (mb);
1728 protected abstract string GetSignatureForError ();
1729 protected abstract void Report_SymbolRelatedToPreviousError ();
1731 void Error_TypeMustBeConvertible (Type atype, Type gc, Type ptype)
1733 Report_SymbolRelatedToPreviousError ();
1734 Report.SymbolRelatedToPreviousError (atype);
1735 Report.Error (309, loc,
1736 "The type `{0}' must be convertible to `{1}' in order to " +
1737 "use it as parameter `{2}' in the generic type or method `{3}'",
1738 TypeManager.CSharpName (atype), TypeManager.CSharpName (gc),
1739 TypeManager.CSharpName (ptype), GetSignatureForError ());
1742 public static bool CheckConstraints (EmitContext ec, MethodBase definition,
1743 MethodBase instantiated, Location loc)
1745 MethodConstraintChecker checker = new MethodConstraintChecker (
1746 definition, definition.GetGenericArguments (),
1747 instantiated.GetGenericArguments (), loc);
1749 return checker.CheckConstraints (ec);
1752 public static bool CheckConstraints (IResolveContext ec, Type gt, Type[] gen_params,
1753 Type[] atypes, Location loc)
1755 TypeConstraintChecker checker = new TypeConstraintChecker (
1756 gt, gen_params, atypes, loc);
1758 return checker.CheckConstraints (ec);
1761 protected class MethodConstraintChecker : ConstraintChecker
1763 MethodBase definition;
1765 public MethodConstraintChecker (MethodBase definition, Type[] gen_params,
1766 Type[] atypes, Location loc)
1767 : base (gen_params, atypes, loc)
1769 this.definition = definition;
1772 protected override string GetSignatureForError ()
1774 return TypeManager.CSharpSignature (definition);
1777 protected override void Report_SymbolRelatedToPreviousError ()
1779 Report.SymbolRelatedToPreviousError (definition);
1783 protected class TypeConstraintChecker : ConstraintChecker
1787 public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
1789 : base (gen_params, atypes, loc)
1794 protected override string GetSignatureForError ()
1796 return TypeManager.CSharpName (gt);
1799 protected override void Report_SymbolRelatedToPreviousError ()
1801 Report.SymbolRelatedToPreviousError (gt);
1807 /// A generic method definition.
1809 public class GenericMethod : DeclSpace
1811 FullNamedExpression return_type;
1812 Parameters parameters;
1814 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
1815 FullNamedExpression return_type, Parameters parameters)
1816 : base (ns, parent, name, null)
1818 this.return_type = return_type;
1819 this.parameters = parameters;
1822 public override TypeBuilder DefineType ()
1824 throw new Exception ();
1827 public override bool Define ()
1829 for (int i = 0; i < TypeParameters.Length; i++)
1830 if (!TypeParameters [i].Resolve (this))
1837 /// Define and resolve the type parameters.
1838 /// We're called from Method.Define().
1840 public bool Define (MethodBuilder mb)
1842 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1843 string[] snames = new string [names.Length];
1844 for (int i = 0; i < names.Length; i++) {
1845 string type_argument_name = names[i].Name;
1846 Parameter p = parameters.GetParameterByName (type_argument_name);
1848 Error_ParameterNameCollision (p.Location, type_argument_name, "method parameter");
1852 snames[i] = type_argument_name;
1855 GenericTypeParameterBuilder[] gen_params = mb.DefineGenericParameters (snames);
1856 for (int i = 0; i < TypeParameters.Length; i++)
1857 TypeParameters [i].Define (gen_params [i]);
1862 for (int i = 0; i < TypeParameters.Length; i++) {
1863 if (!TypeParameters [i].ResolveType (this))
1870 internal static void Error_ParameterNameCollision (Location loc, string name, string collisionWith)
1872 Report.Error (412, loc, "The type parameter name `{0}' is the same as `{1}'",
1873 name, collisionWith);
1877 /// We're called from MethodData.Define() after creating the MethodBuilder.
1879 public bool DefineType (EmitContext ec, MethodBuilder mb,
1880 MethodInfo implementing, bool is_override)
1882 for (int i = 0; i < TypeParameters.Length; i++)
1883 if (!TypeParameters [i].DefineType (
1884 ec, mb, implementing, is_override))
1888 foreach (Parameter p in parameters.FixedParameters){
1889 if (p.Resolve (ec) == null)
1892 if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec, false) == null))
1898 public void EmitAttributes ()
1900 for (int i = 0; i < TypeParameters.Length; i++)
1901 TypeParameters [i].Emit ();
1903 if (OptAttributes != null)
1904 OptAttributes.Emit ();
1907 public override bool DefineMembers ()
1912 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1913 MemberFilter filter, object criteria)
1915 throw new Exception ();
1918 public override MemberCache MemberCache {
1924 public override AttributeTargets AttributeTargets {
1926 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1930 public override string DocCommentHeader {
1931 get { return "M:"; }
1934 public new void VerifyClsCompliance ()
1936 foreach (TypeParameter tp in TypeParameters) {
1937 if (tp.Constraints == null)
1940 tp.Constraints.VerifyClsCompliance ();
1945 public partial class TypeManager
1947 public static TypeContainer LookupGenericTypeContainer (Type t)
1949 t = DropGenericTypeArguments (t);
1950 return LookupTypeContainer (t);
1954 /// Check whether `a' and `b' may become equal generic types.
1955 /// The algorithm to do that is a little bit complicated.
1957 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_inferred,
1958 Type[] method_inferred)
1960 if (a.IsGenericParameter) {
1962 // If a is an array of a's type, they may never
1966 b = b.GetElementType ();
1972 // If b is a generic parameter or an actual type,
1973 // they may become equal:
1975 // class X<T,U> : I<T>, I<U>
1976 // class X<T> : I<T>, I<float>
1978 if (b.IsGenericParameter || !b.IsGenericType) {
1979 int pos = a.GenericParameterPosition;
1980 Type[] args = a.DeclaringMethod != null ? method_inferred : class_inferred;
1981 if (args [pos] == null) {
1986 return args [pos] == a;
1990 // We're now comparing a type parameter with a
1991 // generic instance. They may become equal unless
1992 // the type parameter appears anywhere in the
1993 // generic instance:
1995 // class X<T,U> : I<T>, I<X<U>>
1996 // -> error because you could instanciate it as
1999 // class X<T> : I<T>, I<X<T>> -> ok
2002 Type[] bargs = GetTypeArguments (b);
2003 for (int i = 0; i < bargs.Length; i++) {
2004 if (a.Equals (bargs [i]))
2011 if (b.IsGenericParameter)
2012 return MayBecomeEqualGenericTypes (b, a, class_inferred, method_inferred);
2015 // At this point, neither a nor b are a type parameter.
2017 // If one of them is a generic instance, let
2018 // MayBecomeEqualGenericInstances() compare them (if the
2019 // other one is not a generic instance, they can never
2023 if (a.IsGenericType || b.IsGenericType)
2024 return MayBecomeEqualGenericInstances (a, b, class_inferred, method_inferred);
2027 // If both of them are arrays.
2030 if (a.IsArray && b.IsArray) {
2031 if (a.GetArrayRank () != b.GetArrayRank ())
2034 a = a.GetElementType ();
2035 b = b.GetElementType ();
2037 return MayBecomeEqualGenericTypes (a, b, class_inferred, method_inferred);
2041 // Ok, two ordinary types.
2044 return a.Equals (b);
2048 // Checks whether two generic instances may become equal for some
2049 // particular instantiation (26.3.1).
2051 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
2052 Type[] class_inferred,
2053 Type[] method_inferred)
2055 if (!a.IsGenericType || !b.IsGenericType)
2057 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2060 return MayBecomeEqualGenericInstances (
2061 GetTypeArguments (a), GetTypeArguments (b), class_inferred, method_inferred);
2064 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
2065 Type[] class_inferred,
2066 Type[] method_inferred)
2068 if (aargs.Length != bargs.Length)
2071 for (int i = 0; i < aargs.Length; i++) {
2072 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_inferred, method_inferred))
2080 /// Type inference. Try to infer the type arguments from `method',
2081 /// which is invoked with the arguments `arguments'. This is used
2082 /// when resolving an Invocation or a DelegateInvocation and the user
2083 /// did not explicitly specify type arguments.
2085 public static int InferTypeArguments (EmitContext ec,
2086 ArrayList arguments,
2087 ref MethodBase method)
2089 ATypeInference ti = ATypeInference.CreateInstance (arguments);
2090 Type[] i_args = ti.InferMethodArguments (ec, method);
2092 return ti.InferenceScore;
2094 if (i_args.Length == 0)
2097 method = ((MethodInfo) method).MakeGenericMethod (i_args);
2104 public static bool InferTypeArguments (AParametersCollection apd,
2105 ref MethodBase method)
2107 if (!TypeManager.IsGenericMethod (method))
2110 ATypeInference ti = ATypeInference.CreateInstance (ArrayList.Adapter (apd.Types));
2111 Type[] i_args = ti.InferDelegateArguments (method);
2115 method = ((MethodInfo) method).MakeGenericMethod (i_args);
2120 abstract class ATypeInference
2122 protected readonly ArrayList arguments;
2123 protected readonly int arg_count;
2125 protected ATypeInference (ArrayList arguments)
2127 this.arguments = arguments;
2128 if (arguments != null)
2129 arg_count = arguments.Count;
2132 public static ATypeInference CreateInstance (ArrayList arguments)
2134 if (RootContext.Version == LanguageVersion.ISO_2)
2135 return new TypeInferenceV2 (arguments);
2137 return new TypeInferenceV3 (arguments);
2140 public virtual int InferenceScore {
2142 return int.MaxValue;
2146 public abstract Type[] InferMethodArguments (EmitContext ec, MethodBase method);
2147 public abstract Type[] InferDelegateArguments (MethodBase method);
2151 // Implements C# 2.0 type inference
2153 class TypeInferenceV2 : ATypeInference
2155 public TypeInferenceV2 (ArrayList arguments)
2160 public override Type[] InferDelegateArguments (MethodBase method)
2162 AParametersCollection pd = TypeManager.GetParameterData (method);
2163 if (arg_count != pd.Count)
2166 Type[] method_args = method.GetGenericArguments ();
2167 Type[] inferred_types = new Type[method_args.Length];
2169 Type[] param_types = new Type[pd.Count];
2170 Type[] arg_types = (Type[])arguments.ToArray (typeof (Type));
2172 for (int i = 0; i < arg_count; i++) {
2173 param_types[i] = pd.Types [i];
2176 if (!InferTypeArguments (param_types, arg_types, inferred_types))
2179 return inferred_types;
2182 public override Type[] InferMethodArguments (EmitContext ec, MethodBase method)
2184 AParametersCollection pd = TypeManager.GetParameterData (method);
2185 Type[] method_generic_args = method.GetGenericArguments ();
2186 Type [] inferred_types = new Type [method_generic_args.Length];
2187 Type[] arg_types = new Type [pd.Count];
2189 int a_count = arg_types.Length;
2193 for (int i = 0; i < a_count; i++) {
2194 Argument a = (Argument) arguments[i];
2195 if (a.Expr is NullLiteral || a.Expr is MethodGroupExpr || a.Expr is AnonymousMethodExpression)
2198 if (!TypeInferenceV2.UnifyType (pd.Types [i], a.Type, inferred_types))
2203 Type element_type = TypeManager.GetElementType (pd.Types [a_count]);
2204 for (int i = a_count; i < arg_count; i++) {
2205 Argument a = (Argument) arguments [i];
2206 if (a.Expr is NullLiteral || a.Expr is MethodGroupExpr || a.Expr is AnonymousMethodExpression)
2209 if (!TypeInferenceV2.UnifyType (element_type, a.Type, inferred_types))
2214 for (int i = 0; i < inferred_types.Length; i++)
2215 if (inferred_types [i] == null)
2218 return inferred_types;
2221 static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
2222 Type[] inferred_types)
2224 for (int i = 0; i < arg_types.Length; i++) {
2225 if (arg_types[i] == null)
2228 if (!UnifyType (param_types[i], arg_types[i], inferred_types))
2232 for (int i = 0; i < inferred_types.Length; ++i)
2233 if (inferred_types[i] == null)
2239 public static bool UnifyType (Type pt, Type at, Type[] inferred)
2241 if (pt.IsGenericParameter) {
2242 if (pt.DeclaringMethod == null)
2245 int pos = pt.GenericParameterPosition;
2247 if (inferred [pos] == null)
2248 inferred [pos] = at;
2250 return inferred [pos] == at;
2253 if (!pt.ContainsGenericParameters) {
2254 if (at.ContainsGenericParameters)
2255 return UnifyType (at, pt, inferred);
2262 if (at.GetArrayRank () != pt.GetArrayRank ())
2265 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2268 if (!pt.IsGenericType)
2271 Type gt = pt.GetGenericTypeDefinition ();
2272 if ((gt != TypeManager.generic_ilist_type) && (gt != TypeManager.generic_icollection_type) &&
2273 (gt != TypeManager.generic_ienumerable_type))
2276 Type[] args = TypeManager.GetTypeArguments (pt);
2277 return UnifyType (args[0], at.GetElementType (), inferred);
2282 (pt.GetArrayRank () != at.GetArrayRank ()))
2285 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2288 if (pt.IsByRef && at.IsByRef)
2289 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2290 ArrayList list = new ArrayList ();
2291 if (at.IsGenericType)
2293 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
2296 list.AddRange (TypeManager.GetInterfaces (at));
2298 foreach (Type type in list) {
2299 if (!type.IsGenericType)
2302 if (TypeManager.DropGenericTypeArguments (pt) != TypeManager.DropGenericTypeArguments (type))
2305 if (!UnifyTypes (pt.GetGenericArguments (), type.GetGenericArguments (), inferred))
2312 static bool UnifyTypes (Type[] pts, Type[] ats, Type[] inferred)
2314 for (int i = 0; i < ats.Length; i++) {
2315 if (!UnifyType (pts [i], ats [i], inferred))
2323 // Implements C# 3.0 type inference
2325 class TypeInferenceV3 : ATypeInference
2328 // Tracks successful rate of type inference
2330 int score = int.MaxValue;
2332 public TypeInferenceV3 (ArrayList arguments)
2337 public override int InferenceScore {
2343 public override Type[] InferDelegateArguments (MethodBase method)
2345 AParametersCollection pd = TypeManager.GetParameterData (method);
2346 if (arg_count != pd.Count)
2349 Type[] d_gargs = method.GetGenericArguments ();
2350 TypeInferenceContext context = new TypeInferenceContext (d_gargs);
2352 // A lower-bound inference is made from each argument type Uj of D
2353 // to the corresponding parameter type Tj of M
2354 for (int i = 0; i < arg_count; ++i) {
2355 Type t = pd.Types [i];
2356 if (!t.IsGenericParameter)
2359 context.LowerBoundInference ((Type)arguments[i], t);
2362 if (!context.FixAllTypes ())
2365 return context.InferredTypeArguments;
2368 public override Type[] InferMethodArguments (EmitContext ec, MethodBase method)
2370 Type[] method_generic_args = method.GetGenericArguments ();
2371 TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2372 if (!context.UnfixedVariableExists)
2373 return Type.EmptyTypes;
2375 AParametersCollection pd = TypeManager.GetParameterData (method);
2376 if (!InferInPhases (ec, context, pd))
2379 return context.InferredTypeArguments;
2383 // Implements method type arguments inference
2385 bool InferInPhases (EmitContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
2387 int params_arguments_start;
2388 if (methodParameters.HasParams) {
2389 params_arguments_start = methodParameters.Count - 1;
2391 params_arguments_start = arg_count;
2395 // The first inference phase
2397 Type method_parameter = null;
2398 for (int i = 0; i < arg_count; i++) {
2399 Argument a = (Argument) arguments [i];
2401 if (i < params_arguments_start) {
2402 method_parameter = methodParameters.Types [i];
2403 } else if (i == params_arguments_start) {
2404 if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2405 method_parameter = methodParameters.Types [params_arguments_start];
2407 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2411 // When a lambda expression, an anonymous method
2412 // is used an explicit argument type inference takes a place
2414 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2416 if (am.ExplicitTypeInference (tic, method_parameter))
2421 if (a.Expr is NullLiteral)
2425 // Otherwise an output type inference is made
2427 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2431 // Part of the second phase but because it happens only once
2432 // we don't need to call it in cycle
2434 bool fixed_any = false;
2435 if (!tic.FixIndependentTypeArguments (methodParameters, ref fixed_any))
2438 return DoSecondPhase (ec, tic, methodParameters, !fixed_any);
2441 bool DoSecondPhase (EmitContext ec, TypeInferenceContext tic, AParametersCollection methodParameters, bool fixDependent)
2443 bool fixed_any = false;
2444 if (fixDependent && !tic.FixDependentTypes (methodParameters, ref fixed_any))
2447 // If no further unfixed type variables exist, type inference succeeds
2448 if (!tic.UnfixedVariableExists)
2451 if (!fixed_any && fixDependent)
2454 // For all arguments where the corresponding argument output types
2455 // contain unfixed type variables but the input types do not,
2456 // an output type inference is made
2457 for (int i = 0; i < arg_count; i++) {
2458 Type t_i = methodParameters.Types [i];
2459 if (!TypeManager.IsDelegateType (t_i)) {
2460 if (TypeManager.DropGenericTypeArguments (t_i) != TypeManager.expression_type)
2463 t_i = t_i.GetGenericArguments () [0];
2466 MethodInfo mi = Delegate.GetInvokeMethod (t_i, t_i);
2467 Type rtype = mi.ReturnType;
2470 // Blablabla, because reflection does not work with dynamic types
2471 Type[] g_args = t_i.GetGenericArguments ();
2472 rtype = g_args[rtype.GenericParameterPosition];
2475 if (tic.IsReturnTypeNonDependent (mi, rtype))
2476 score -= tic.OutputTypeInference (ec, ((Argument) arguments [i]).Expr, t_i);
2480 return DoSecondPhase (ec, tic, methodParameters, true);
2484 public class TypeInferenceContext
2486 readonly Type[] unfixed_types;
2487 readonly Type[] fixed_types;
2488 readonly ArrayList[] bounds;
2490 public TypeInferenceContext (Type[] typeArguments)
2492 if (typeArguments.Length == 0)
2493 throw new ArgumentException ("Empty generic arguments");
2495 fixed_types = new Type [typeArguments.Length];
2496 for (int i = 0; i < typeArguments.Length; ++i) {
2497 if (typeArguments [i].IsGenericParameter) {
2498 if (bounds == null) {
2499 bounds = new ArrayList [typeArguments.Length];
2500 unfixed_types = new Type [typeArguments.Length];
2502 unfixed_types [i] = typeArguments [i];
2504 fixed_types [i] = typeArguments [i];
2509 public Type[] InferredTypeArguments {
2515 void AddToBounds (Type t, int index)
2518 // Some types cannot be used as type arguments
2520 if (t == TypeManager.void_type || t.IsPointer)
2523 ArrayList a = bounds [index];
2525 a = new ArrayList ();
2533 // SPEC: does not cover type inference using constraints
2535 //if (TypeManager.IsGenericParameter (t)) {
2536 // GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
2537 // if (constraints != null) {
2538 // //if (constraints.EffectiveBaseClass != null)
2539 // // t = constraints.EffectiveBaseClass;
2545 bool AllTypesAreFixed (Type[] types)
2547 foreach (Type t in types) {
2548 if (t.IsGenericParameter) {
2554 if (t.IsGenericType)
2555 return AllTypesAreFixed (t.GetGenericArguments ());
2562 // 26.3.3.8 Exact Inference
2564 public int ExactInference (Type u, Type v)
2566 // If V is an array type
2571 if (u.GetArrayRank () != v.GetArrayRank ())
2574 return ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
2577 // If V is constructed type and U is constructed type
2578 if (v.IsGenericType && !v.IsGenericTypeDefinition) {
2579 if (!u.IsGenericType)
2582 Type [] ga_u = u.GetGenericArguments ();
2583 Type [] ga_v = v.GetGenericArguments ();
2584 if (ga_u.Length != ga_v.Length)
2588 for (int i = 0; i < ga_u.Length; ++i)
2589 score += ExactInference (ga_u [i], ga_v [i]);
2591 return score > 0 ? 1 : 0;
2594 // If V is one of the unfixed type arguments
2595 int pos = IsUnfixed (v);
2599 AddToBounds (u, pos);
2603 public bool FixAllTypes ()
2605 for (int i = 0; i < unfixed_types.Length; ++i) {
2613 // All unfixed type variables Xi are fixed for which all of the following hold:
2614 // a, There is at least one type variable Xj that depends on Xi
2615 // b, Xi has a non-empty set of bounds
2617 public bool FixDependentTypes (AParametersCollection methodParameters, ref bool fixed_any)
2619 for (int i = 0; i < unfixed_types.Length; ++i) {
2620 if (unfixed_types[i] == null)
2623 if (bounds[i] == null)
2636 // All unfixed type variables Xi which depend on no Xj are fixed
2638 public bool FixIndependentTypeArguments (AParametersCollection methodParameters, ref bool fixed_any)
2640 ArrayList types_to_fix = new ArrayList (unfixed_types);
2641 for (int i = 0; i < methodParameters.Types.Length; ++i) {
2642 Type t = methodParameters.Types [i];
2643 if (t.IsGenericParameter)
2646 if (!TypeManager.IsDelegateType (t)) {
2647 if (TypeManager.DropGenericTypeArguments (t) != TypeManager.expression_type)
2650 t = t.GetGenericArguments () [0];
2653 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
2654 Type rtype = invoke.ReturnType;
2655 if (!rtype.IsGenericParameter && !rtype.IsGenericType)
2659 // Blablabla, because reflection does not work with dynamic types
2660 if (rtype.IsGenericParameter) {
2661 Type [] g_args = t.GetGenericArguments ();
2662 rtype = g_args [rtype.GenericParameterPosition];
2665 // Remove dependent types, they cannot be fixed yet
2666 RemoveDependentTypes (types_to_fix, rtype);
2669 foreach (Type t in types_to_fix) {
2673 int idx = IsUnfixed (t);
2674 if (idx >= 0 && !FixType (idx)) {
2679 fixed_any = types_to_fix.Count > 0;
2686 public bool FixType (int i)
2688 // It's already fixed
2689 if (unfixed_types[i] == null)
2690 throw new InternalErrorException ("Type argument has been already fixed");
2692 ArrayList candidates = (ArrayList)bounds [i];
2693 if (candidates == null)
2696 if (candidates.Count == 1) {
2697 unfixed_types[i] = null;
2698 fixed_types[i] = (Type)candidates[0];
2703 // Determines a unique type from which there is
2704 // a standard implicit conversion to all the other
2707 Type best_candidate = null;
2709 int candidates_count = candidates.Count;
2710 for (int ci = 0; ci < candidates_count; ++ci) {
2711 Type candidate = (Type)candidates [ci];
2712 for (cii = 0; cii < candidates_count; ++cii) {
2716 if (!Convert.ImplicitConversionExists (null,
2717 new TypeExpression ((Type)candidates [cii], Location.Null), candidate)) {
2722 if (cii != candidates_count)
2725 if (best_candidate != null)
2728 best_candidate = candidate;
2731 if (best_candidate == null)
2734 unfixed_types[i] = null;
2735 fixed_types[i] = best_candidate;
2740 // Uses inferred types to inflate delegate type argument
2742 public Type InflateGenericArgument (Type parameter)
2744 if (parameter.IsGenericParameter) {
2746 // Inflate method generic argument (MVAR) only
2748 if (parameter.DeclaringMethod == null)
2751 return fixed_types [parameter.GenericParameterPosition];
2754 if (parameter.IsGenericType) {
2755 Type [] parameter_targs = parameter.GetGenericArguments ();
2756 for (int ii = 0; ii < parameter_targs.Length; ++ii) {
2757 parameter_targs [ii] = InflateGenericArgument (parameter_targs [ii]);
2759 return parameter.GetGenericTypeDefinition ().MakeGenericType (parameter_targs);
2766 // Tests whether all delegate input arguments are fixed and generic output type
2767 // requires output type inference
2769 public bool IsReturnTypeNonDependent (MethodInfo invoke, Type returnType)
2771 if (returnType.IsGenericParameter) {
2772 if (IsFixed (returnType))
2774 } else if (returnType.IsGenericType) {
2775 if (TypeManager.IsDelegateType (returnType)) {
2776 invoke = Delegate.GetInvokeMethod (returnType, returnType);
2777 return IsReturnTypeNonDependent (invoke, invoke.ReturnType);
2780 Type[] g_args = returnType.GetGenericArguments ();
2782 // At least one unfixed return type has to exist
2783 if (AllTypesAreFixed (g_args))
2789 // All generic input arguments have to be fixed
2790 AParametersCollection d_parameters = TypeManager.GetParameterData (invoke);
2791 return AllTypesAreFixed (d_parameters.Types);
2794 bool IsFixed (Type type)
2796 return IsUnfixed (type) == -1;
2799 int IsUnfixed (Type type)
2801 if (!type.IsGenericParameter)
2804 //return unfixed_types[type.GenericParameterPosition] != null;
2805 for (int i = 0; i < unfixed_types.Length; ++i) {
2806 if (unfixed_types [i] == type)
2814 // 26.3.3.9 Lower-bound Inference
2816 public int LowerBoundInference (Type u, Type v)
2818 // If V is one of the unfixed type arguments
2819 int pos = IsUnfixed (v);
2821 AddToBounds (u, pos);
2825 // If U is an array type
2827 int u_dim = u.GetArrayRank ();
2829 Type u_e = TypeManager.GetElementType (u);
2832 if (u_dim != v.GetArrayRank ())
2835 v_e = TypeManager.GetElementType (v);
2838 return LowerBoundInference (u_e, v_e);
2841 return ExactInference (u_e, v_e);
2847 if (v.IsGenericType) {
2848 Type g_v = v.GetGenericTypeDefinition ();
2849 if ((g_v != TypeManager.generic_ilist_type) && (g_v != TypeManager.generic_icollection_type) &&
2850 (g_v != TypeManager.generic_ienumerable_type))
2853 v_e = TypeManager.GetTypeArguments (v)[0];
2856 return LowerBoundInference (u_e, v_e);
2859 return ExactInference (u_e, v_e);
2861 } else if (v.IsGenericType && !v.IsGenericTypeDefinition) {
2863 // if V is a constructed type C<V1..Vk> and there is a unique set of types U1..Uk
2864 // such that a standard implicit conversion exists from U to C<U1..Uk> then an exact
2865 // inference is made from each Ui for the corresponding Vi
2867 ArrayList u_candidates = new ArrayList ();
2868 if (u.IsGenericType)
2869 u_candidates.Add (u);
2871 for (Type t = u.BaseType; t != null; t = t.BaseType) {
2872 if (t.IsGenericType && !t.IsGenericTypeDefinition)
2873 u_candidates.Add (t);
2876 // TODO: Implement GetGenericInterfaces only and remove
2877 // the if from foreach
2878 u_candidates.AddRange (TypeManager.GetInterfaces (u));
2880 Type open_v = v.GetGenericTypeDefinition ();
2882 foreach (Type u_candidate in u_candidates) {
2883 if (!u_candidate.IsGenericType || u_candidate.IsGenericTypeDefinition)
2886 if (TypeManager.DropGenericTypeArguments (u_candidate) != open_v)
2889 Type [] ga_u = u_candidate.GetGenericArguments ();
2890 Type [] ga_v = v.GetGenericArguments ();
2891 bool all_exact = true;
2892 for (int i = 0; i < ga_u.Length; ++i)
2893 if (ExactInference (ga_u [i], ga_v [i]) == 0)
2896 if (all_exact && score == 0)
2906 // 26.3.3.6 Output Type Inference
2908 public int OutputTypeInference (EmitContext ec, Expression e, Type t)
2910 // If e is a lambda or anonymous method with inferred return type
2911 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
2913 Type rt = ame.InferReturnType (ec, this, t);
2914 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
2917 AParametersCollection pd = TypeManager.GetParameterData (invoke);
2918 return ame.Parameters.Count == pd.Count ? 1 : 0;
2921 Type rtype = invoke.ReturnType;
2923 // Blablabla, because reflection does not work with dynamic types
2924 Type [] g_args = t.GetGenericArguments ();
2925 rtype = g_args [rtype.GenericParameterPosition];
2927 return LowerBoundInference (rt, rtype) + 1;
2931 // if E is a method group and T is a delegate type or expression tree type
2932 // return type Tb with parameter types T1..Tk and return type Tb, and overload
2933 // resolution of E with the types T1..Tk yields a single method with return type U,
2934 // then a lower-bound inference is made from U for Tb.
2936 if (e is MethodGroupExpr) {
2937 // TODO: Or expression tree
2938 if (!TypeManager.IsDelegateType (t))
2941 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
2942 Type rtype = invoke.ReturnType;
2944 // Blablabla, because reflection does not work with dynamic types
2945 Type [] g_args = t.GetGenericArguments ();
2946 rtype = g_args [rtype.GenericParameterPosition];
2949 if (!TypeManager.IsGenericType (rtype))
2952 MethodGroupExpr mg = (MethodGroupExpr) e;
2953 ArrayList args = DelegateCreation.CreateDelegateMethodArguments (invoke, e.Location);
2954 mg = mg.OverloadResolve (ec, ref args, true, e.Location);
2958 // TODO: What should happen when return type is of generic type ?
2959 throw new NotImplementedException ();
2960 // return LowerBoundInference (null, rtype) + 1;
2964 // if e is an expression with type U, then
2965 // a lower-bound inference is made from U for T
2967 return LowerBoundInference (e.Type, t) * 2;
2970 static void RemoveDependentTypes (ArrayList types, Type returnType)
2972 if (returnType.IsGenericParameter) {
2973 types [returnType.GenericParameterPosition] = null;
2977 if (returnType.IsGenericType) {
2978 foreach (Type t in returnType.GetGenericArguments ()) {
2979 RemoveDependentTypes (types, t);
2984 public bool UnfixedVariableExists {
2986 if (unfixed_types == null)
2989 foreach (Type ut in unfixed_types)