2 // generic.cs: Generics support
4 // Authors: Martin Baulig (martin@ximian.com)
5 // Miguel de Icaza (miguel@ximian.com)
7 // Licensed under the terms of the GNU GPL
9 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
10 // (C) 2004 Novell, Inc
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.Globalization;
16 using System.Collections;
18 using System.Text.RegularExpressions;
20 namespace Mono.CSharp {
22 public abstract class GenericConstraints {
23 public abstract GenericParameterAttributes Attributes {
27 public bool HasConstructorConstraint {
28 get { return (Attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0; }
31 public bool HasReferenceTypeConstraint {
32 get { return (Attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0; }
35 public bool HasValueTypeConstraint {
36 get { return (Attributes & GenericParameterAttributes.ValueTypeConstraint) != 0; }
39 public virtual bool HasClassConstraint {
40 get { return ClassConstraint != null; }
43 public abstract Type ClassConstraint {
47 public abstract Type[] InterfaceConstraints {
51 public abstract Type EffectiveBaseClass {
56 // Returns whether the type parameter is "known to be a reference type".
58 public virtual bool IsReferenceType {
60 if (HasReferenceTypeConstraint)
62 if (HasValueTypeConstraint)
65 if (ClassConstraint != null) {
66 if (ClassConstraint.IsValueType)
69 if (ClassConstraint != TypeManager.object_type)
73 foreach (Type t in InterfaceConstraints) {
74 if (!t.IsGenericParameter)
77 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
78 if ((gc != null) && gc.IsReferenceType)
87 // Returns whether the type parameter is "known to be a value type".
89 public virtual bool IsValueType {
91 if (HasValueTypeConstraint)
93 if (HasReferenceTypeConstraint)
96 if (ClassConstraint != null) {
97 if (!ClassConstraint.IsValueType)
100 if (ClassConstraint != TypeManager.value_type)
104 foreach (Type t in InterfaceConstraints) {
105 if (!t.IsGenericParameter)
108 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
109 if ((gc != null) && gc.IsValueType)
118 public enum SpecialConstraint
126 // Tracks the constraints for a type parameter
128 public class Constraints : GenericConstraints {
130 ArrayList constraints;
134 // name is the identifier, constraints is an arraylist of
135 // Expressions (with types) or `true' for the constructor constraint.
137 public Constraints (string name, ArrayList constraints,
141 this.constraints = constraints;
145 public string TypeParameter {
151 GenericParameterAttributes attrs;
152 TypeExpr class_constraint;
153 ArrayList iface_constraints;
154 ArrayList type_param_constraints;
155 int num_constraints, first_constraint;
156 Type class_constraint_type;
157 Type[] iface_constraint_types;
158 Type effective_base_type;
160 public bool Resolve (EmitContext ec)
162 iface_constraints = new ArrayList ();
163 type_param_constraints = new ArrayList ();
165 foreach (object obj in constraints) {
166 if (HasConstructorConstraint) {
167 Report.Error (401, loc,
168 "The new() constraint must be last.");
172 if (obj is SpecialConstraint) {
173 SpecialConstraint sc = (SpecialConstraint) obj;
175 if (sc == SpecialConstraint.Constructor) {
176 if (!HasValueTypeConstraint) {
177 attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
182 451, loc, "The new () constraint " +
183 "cannot be used with the `struct' " +
188 if ((num_constraints > 0) || HasReferenceTypeConstraint || HasValueTypeConstraint) {
189 Report.Error (449, loc,
190 "The `class' or `struct' " +
191 "constraint must be first");
195 if (sc == SpecialConstraint.ReferenceType)
196 attrs |= GenericParameterAttributes.ReferenceTypeConstraint;
198 attrs |= GenericParameterAttributes.ValueTypeConstraint;
203 if (obj is ConstructedType) {
204 ConstructedType cexpr = (ConstructedType) obj;
205 if (!cexpr.ResolveConstructedType (ec))
209 expr = ((Expression) obj).ResolveAsTypeTerminal (ec);
214 TypeParameterExpr texpr = expr as TypeParameterExpr;
216 type_param_constraints.Add (expr);
217 else if (expr.IsInterface)
218 iface_constraints.Add (expr);
219 else if (class_constraint != null) {
220 Report.Error (406, loc,
221 "`{0}': the class constraint for `{1}' " +
222 "must come before any other constraints.",
225 } else if (HasReferenceTypeConstraint || HasValueTypeConstraint) {
226 Report.Error (450, loc, "`{0}': cannot specify both " +
227 "a constraint class and the `class' " +
228 "or `struct' constraint.", expr.Name);
231 class_constraint = expr;
239 bool CheckTypeParameterConstraints (TypeParameter tparam, Hashtable seen)
241 seen.Add (tparam, true);
243 Constraints constraints = tparam.Constraints;
244 if (constraints == null)
247 if (constraints.HasValueTypeConstraint) {
248 Report.Error (456, loc, "Type parameter `{0}' has " +
249 "the `struct' constraint, so it cannot " +
250 "be used as a constraint for `{1}'",
255 if (constraints.type_param_constraints == null)
258 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
259 if (seen.Contains (expr.TypeParameter)) {
260 Report.Error (454, loc, "Circular constraint " +
261 "dependency involving `{0}' and `{1}'",
262 tparam.Name, expr.Name);
266 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
273 public bool ResolveTypes (EmitContext ec)
275 if (effective_base_type != null)
278 foreach (object obj in constraints) {
279 ConstructedType cexpr = obj as ConstructedType;
283 if (!cexpr.CheckConstraints (ec))
287 foreach (TypeParameterExpr expr in type_param_constraints) {
288 Hashtable seen = new Hashtable ();
289 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
293 ArrayList list = new ArrayList ();
295 foreach (TypeExpr iface_constraint in iface_constraints) {
296 foreach (Type type in list) {
297 if (!type.Equals (iface_constraint.Type))
300 Report.Error (405, loc,
301 "Duplicate constraint `{0}' for type " +
302 "parameter `{1}'.", iface_constraint.Type,
307 list.Add (iface_constraint.Type);
310 foreach (TypeParameterExpr expr in type_param_constraints) {
311 foreach (Type type in list) {
312 if (!type.Equals (expr.Type))
315 Report.Error (405, loc,
316 "Duplicate constraint `{0}' for type " +
317 "parameter `{1}'.", expr.Type, name);
321 list.Add (expr.Type);
324 iface_constraint_types = new Type [list.Count];
325 list.CopyTo (iface_constraint_types, 0);
327 if (class_constraint != null) {
328 class_constraint_type = class_constraint.Type;
329 if (class_constraint_type == null)
332 if (class_constraint_type.IsSealed) {
333 Report.Error (701, loc,
334 "`{0}' is not a valid bound. Bounds " +
335 "must be interfaces or non sealed " +
336 "classes", class_constraint_type);
340 if ((class_constraint_type == TypeManager.array_type) ||
341 (class_constraint_type == TypeManager.delegate_type) ||
342 (class_constraint_type == TypeManager.enum_type) ||
343 (class_constraint_type == TypeManager.value_type) ||
344 (class_constraint_type == TypeManager.object_type)) {
345 Report.Error (702, loc,
346 "Bound cannot be special class `{0}'",
347 class_constraint_type);
352 if (class_constraint_type != null)
353 effective_base_type = class_constraint_type;
354 else if (HasValueTypeConstraint)
355 effective_base_type = TypeManager.value_type;
357 effective_base_type = TypeManager.object_type;
362 public bool CheckDependencies (EmitContext ec)
364 foreach (TypeParameterExpr expr in type_param_constraints) {
365 if (!CheckDependencies (expr.TypeParameter, ec))
372 bool CheckDependencies (TypeParameter tparam, EmitContext ec)
374 Constraints constraints = tparam.Constraints;
375 if (constraints == null)
378 if (HasValueTypeConstraint && constraints.HasClassConstraint) {
379 Report.Error (455, loc, "Type parameter `{0}' inherits " +
380 "conflicting constraints `{1}' and `{2}'",
381 name, constraints.ClassConstraint,
386 if (HasClassConstraint && constraints.HasClassConstraint) {
387 Type t1 = ClassConstraint;
388 TypeExpr e1 = class_constraint;
389 Type t2 = constraints.ClassConstraint;
390 TypeExpr e2 = constraints.class_constraint;
392 if (!Convert.ImplicitReferenceConversionExists (ec, e1, t2) &&
393 !Convert.ImplicitReferenceConversionExists (ec, e2, t1)) {
394 Report.Error (455, loc,
395 "Type parameter `{0}' inherits " +
396 "conflicting constraints `{1}' and `{2}'",
402 if (constraints.type_param_constraints == null)
405 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
406 if (!CheckDependencies (expr.TypeParameter, ec))
413 public void Define (GenericTypeParameterBuilder type)
415 type.SetGenericParameterAttributes (attrs);
418 public override GenericParameterAttributes Attributes {
419 get { return attrs; }
422 public override bool HasClassConstraint {
423 get { return class_constraint != null; }
426 public override Type ClassConstraint {
427 get { return class_constraint_type; }
430 public override Type[] InterfaceConstraints {
431 get { return iface_constraint_types; }
434 public override Type EffectiveBaseClass {
435 get { return effective_base_type; }
438 internal bool IsSubclassOf (Type t)
440 if ((class_constraint_type != null) &&
441 class_constraint_type.IsSubclassOf (t))
444 if (iface_constraint_types == null)
447 foreach (Type iface in iface_constraint_types) {
448 if (TypeManager.IsSubclassOf (iface, t))
455 public bool CheckInterfaceMethod (EmitContext ec, GenericConstraints gc)
457 if (gc.Attributes != attrs)
460 if (HasClassConstraint != gc.HasClassConstraint)
462 if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
465 int gc_icount = gc.InterfaceConstraints != null ?
466 gc.InterfaceConstraints.Length : 0;
467 int icount = InterfaceConstraints != null ?
468 InterfaceConstraints.Length : 0;
470 if (gc_icount != icount)
473 foreach (Type iface in gc.InterfaceConstraints) {
475 foreach (Type check in InterfaceConstraints) {
476 if (TypeManager.IsEqual (iface, check)) {
491 // This type represents a generic type parameter
493 public class TypeParameter : MemberCore, IMemberContainer {
495 GenericConstraints gc;
496 Constraints constraints;
498 GenericTypeParameterBuilder type;
500 public TypeParameter (TypeContainer parent, string name,
501 Constraints constraints, Location loc)
502 : base (parent, new MemberName (name), null, loc)
505 this.constraints = constraints;
509 public GenericConstraints GenericConstraints {
511 return gc != null ? gc : constraints;
515 public Constraints Constraints {
521 public bool HasConstructorConstraint {
523 if (constraints != null)
524 return constraints.HasConstructorConstraint;
536 public bool Resolve (DeclSpace ds)
538 if (constraints != null) {
539 if (!constraints.Resolve (ds.EmitContext)) {
548 public void Define (GenericTypeParameterBuilder type)
550 if (this.type != null)
551 throw new InvalidOperationException ();
554 TypeManager.AddTypeParameter (type, this);
557 public void DefineConstraints ()
559 if (constraints != null)
560 constraints.Define (type);
563 public bool ResolveType (EmitContext ec)
565 if (constraints != null) {
566 if (!constraints.ResolveTypes (ec)) {
575 public bool DefineType (EmitContext ec)
577 return DefineType (ec, null, null, false);
580 public bool DefineType (EmitContext ec, MethodBuilder builder,
581 MethodInfo implementing, bool is_override)
583 if (!ResolveType (ec))
586 if (implementing != null) {
587 if (is_override && (constraints != null)) {
589 460, loc, "Constraints for override and " +
590 "explicit interface implementation methods " +
591 "are inherited from the base method so they " +
592 "cannot be specified directly");
596 MethodBase mb = implementing;
597 if (mb.Mono_IsInflatedMethod)
598 mb = mb.GetGenericMethodDefinition ();
600 int pos = type.GenericParameterPosition;
601 ParameterData pd = Invocation.GetParameterData (mb);
602 GenericConstraints temp_gc = pd.GenericConstraints (pos);
603 Type mparam = mb.GetGenericArguments () [pos];
606 gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
607 else if (constraints != null)
608 gc = new InflatedConstraints (constraints, implementing.DeclaringType);
611 if (constraints != null) {
614 else if (!constraints.CheckInterfaceMethod (ec, gc))
617 if (!is_override && (temp_gc != null))
622 Report.SymbolRelatedToPreviousError (implementing);
625 425, loc, "The constraints for type " +
626 "parameter `{0}' of method `{1}' must match " +
627 "the constraints for type parameter `{2}' " +
628 "of interface method `{3}'. Consider using " +
629 "an explicit interface implementation instead",
630 Name, TypeManager.CSharpSignature (builder),
631 mparam, TypeManager.CSharpSignature (mb));
635 gc = (GenericConstraints) constraints;
641 if (gc.HasClassConstraint)
642 type.SetBaseTypeConstraint (gc.ClassConstraint);
644 type.SetInterfaceConstraints (gc.InterfaceConstraints);
645 TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
650 public bool CheckDependencies (EmitContext ec)
652 if (constraints != null)
653 return constraints.CheckDependencies (ec);
658 public override string DocCommentHeader {
660 throw new InvalidOperationException (
661 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
669 public override bool Define ()
674 protected override void VerifyObsoleteAttribute ()
677 public override void ApplyAttributeBuilder (Attribute a,
678 CustomAttributeBuilder cb)
681 public override AttributeTargets AttributeTargets {
683 return (AttributeTargets) 0;
687 public override string[] ValidAttributeTargets {
689 return new string [0];
697 string IMemberContainer.Name {
701 MemberCache IMemberContainer.BaseCache {
705 bool IMemberContainer.IsInterface {
709 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
711 return FindMembers (mt, bf, null, null);
714 MemberCache IMemberContainer.MemberCache {
718 public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
719 MemberFilter filter, object criteria)
721 if (constraints == null)
722 return MemberList.Empty;
724 ArrayList members = new ArrayList ();
726 GenericConstraints gc = (GenericConstraints) constraints;
728 if (gc.HasClassConstraint) {
729 MemberList list = TypeManager.FindMembers (
730 gc.ClassConstraint, mt, bf, filter, criteria);
732 members.AddRange (list);
735 foreach (Type t in gc.InterfaceConstraints) {
736 MemberList list = TypeManager.FindMembers (
737 t, mt, bf, filter, criteria);
739 members.AddRange (list);
742 return new MemberList (members);
745 public bool IsSubclassOf (Type t)
750 if (constraints != null)
751 return constraints.IsSubclassOf (t);
756 public override string ToString ()
758 return "TypeParameter[" + name + "]";
761 protected class InflatedConstraints : GenericConstraints
763 GenericConstraints gc;
765 Type class_constraint;
766 Type[] iface_constraints;
770 public InflatedConstraints (GenericConstraints gc, Type declaring)
773 this.declaring = declaring;
775 dargs = TypeManager.GetTypeArguments (declaring);
777 ArrayList list = new ArrayList ();
778 if (gc.HasClassConstraint)
779 list.Add (inflate (gc.ClassConstraint));
780 foreach (Type iface in gc.InterfaceConstraints)
781 list.Add (inflate (iface));
783 bool has_class_constr = false;
784 if (list.Count > 0) {
785 Type first = (Type) list [0];
786 has_class_constr = !first.IsInterface && !first.IsGenericParameter;
789 if ((list.Count > 0) && has_class_constr) {
790 class_constraint = (Type) list [0];
791 iface_constraints = new Type [list.Count - 1];
792 list.CopyTo (1, iface_constraints, 0, list.Count - 1);
794 iface_constraints = new Type [list.Count];
795 list.CopyTo (iface_constraints, 0);
798 if (HasValueTypeConstraint)
799 base_type = TypeManager.value_type;
800 else if (class_constraint != null)
801 base_type = class_constraint;
803 base_type = TypeManager.object_type;
806 Type inflate (Type t)
810 if (t.IsGenericParameter)
811 return dargs [t.GenericParameterPosition];
812 if (t.IsGenericInstance) {
813 t = t.GetGenericTypeDefinition ();
814 t = t.BindGenericParameters (dargs);
820 public override GenericParameterAttributes Attributes {
821 get { return gc.Attributes; }
824 public override Type ClassConstraint {
825 get { return class_constraint; }
828 public override Type EffectiveBaseClass {
829 get { return base_type; }
832 public override Type[] InterfaceConstraints {
833 get { return iface_constraints; }
839 // This type represents a generic type parameter reference.
841 // These expressions are born in a fully resolved state.
843 public class TypeParameterExpr : TypeExpr {
844 TypeParameter type_parameter;
846 public override string Name {
848 return type_parameter.Name;
852 public override string FullName {
854 return type_parameter.Name;
858 public TypeParameter TypeParameter {
860 return type_parameter;
864 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
866 this.type_parameter = type_parameter;
870 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
872 type = type_parameter.Type;
877 public override bool IsInterface {
878 get { return false; }
881 public override bool CheckAccessLevel (DeclSpace ds)
886 public void Error_CannotUseAsUnmanagedType (Location loc)
888 Report.Error (-203, loc, "Can not use type parameter as unamanged type");
892 public class TypeArguments {
893 public readonly Location Location;
900 public TypeArguments (Location loc)
902 args = new ArrayList ();
906 public TypeArguments (int dimension, Location loc)
908 this.dimension = dimension;
912 public void Add (Expression type)
915 throw new InvalidOperationException ();
920 public void Add (TypeArguments new_args)
923 throw new InvalidOperationException ();
925 args.AddRange (new_args.args);
928 public string[] GetDeclarations ()
930 string[] ret = new string [args.Count];
931 for (int i = 0; i < args.Count; i++) {
932 SimpleName sn = args [i] as SimpleName;
938 Report.Error (81, Location, "Type parameter declaration " +
939 "must be an identifier not a type");
945 public Type[] Arguments {
951 public bool HasTypeArguments {
953 return has_type_args;
966 public bool IsUnbound {
968 return dimension > 0;
972 public override string ToString ()
974 StringBuilder s = new StringBuilder ();
977 for (int i = 0; i < count; i++){
979 // FIXME: Use TypeManager.CSharpname once we have the type
982 s.Append (args [i].ToString ());
986 return s.ToString ();
989 public bool Resolve (EmitContext ec)
991 int count = args.Count;
994 atypes = new Type [count];
996 for (int i = 0; i < count; i++){
997 TypeExpr te = ((Expression) args [i]).ResolveAsTypeTerminal (ec);
1002 if (te is TypeParameterExpr)
1003 has_type_args = true;
1005 atypes [i] = te.Type;
1011 public class ConstructedType : TypeExpr {
1012 string name, full_name;
1014 Type[] gen_params, atypes;
1017 public ConstructedType (string name, TypeArguments args, Location l)
1020 this.name = MemberName.MakeName (name, args.Count);
1023 eclass = ExprClass.Type;
1024 full_name = name + "<" + args.ToString () + ">";
1027 public ConstructedType (string name, TypeParameter[] type_params, Location l)
1028 : this (type_params, l)
1033 full_name = name + "<" + args.ToString () + ">";
1036 public ConstructedType (FullNamedExpression fname, TypeArguments args, Location l)
1039 this.name = fname.FullName;
1042 eclass = ExprClass.Type;
1043 full_name = name + "<" + args.ToString () + ">";
1046 protected ConstructedType (TypeArguments args, Location l)
1051 eclass = ExprClass.Type;
1054 protected ConstructedType (TypeParameter[] type_params, Location l)
1058 args = new TypeArguments (l);
1059 foreach (TypeParameter type_param in type_params)
1060 args.Add (new TypeParameterExpr (type_param, l));
1062 eclass = ExprClass.Type;
1065 public ConstructedType (Type t, TypeParameter[] type_params, Location l)
1066 : this (type_params, l)
1068 gt = t.GetGenericTypeDefinition ();
1070 this.name = gt.FullName;
1071 full_name = gt.FullName + "<" + args.ToString () + ">";
1074 public ConstructedType (Type t, TypeArguments args, Location l)
1077 gt = t.GetGenericTypeDefinition ();
1079 this.name = gt.FullName;
1080 full_name = gt.FullName + "<" + args.ToString () + ">";
1083 public TypeArguments TypeArguments {
1084 get { return args; }
1087 protected string DeclarationName {
1089 StringBuilder sb = new StringBuilder ();
1090 sb.Append (gt.FullName);
1092 for (int i = 0; i < gen_params.Length; i++) {
1095 sb.Append (gen_params [i]);
1098 return sb.ToString ();
1102 protected bool CheckConstraint (EmitContext ec, Type ptype, Expression expr,
1105 if (TypeManager.HasGenericArguments (ctype)) {
1106 Type[] types = TypeManager.GetTypeArguments (ctype);
1108 TypeArguments new_args = new TypeArguments (loc);
1110 for (int i = 0; i < types.Length; i++) {
1113 if (t.IsGenericParameter) {
1114 int pos = t.GenericParameterPosition;
1115 t = args.Arguments [pos];
1117 new_args.Add (new TypeExpression (t, loc));
1120 TypeExpr ct = new ConstructedType (ctype, new_args, loc);
1121 if (ct.ResolveAsTypeTerminal (ec) == null)
1126 return Convert.ImplicitStandardConversionExists (ec, expr, ctype);
1129 protected bool CheckConstraints (EmitContext ec, int index)
1131 Type atype = atypes [index];
1132 Type ptype = gen_params [index];
1137 Expression aexpr = new EmptyExpression (atype);
1139 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1143 bool is_class, is_struct;
1144 if (atype.IsGenericParameter) {
1145 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1147 is_class = agc.HasReferenceTypeConstraint;
1148 is_struct = agc.HasValueTypeConstraint;
1150 is_class = is_struct = false;
1153 is_class = atype.IsClass;
1154 is_struct = atype.IsValueType;
1158 // First, check the `class' and `struct' constraints.
1160 if (gc.HasReferenceTypeConstraint && !is_class) {
1161 Report.Error (452, loc, "The type `{0}' must be " +
1162 "a reference type in order to use it " +
1163 "as type parameter `{1}' in the " +
1164 "generic type or method `{2}'.",
1165 atype, ptype, DeclarationName);
1167 } else if (gc.HasValueTypeConstraint && !is_struct) {
1168 Report.Error (453, loc, "The type `{0}' must be " +
1169 "a value type in order to use it " +
1170 "as type parameter `{1}' in the " +
1171 "generic type or method `{2}'.",
1172 atype, ptype, DeclarationName);
1177 // The class constraint comes next.
1179 if (gc.HasClassConstraint) {
1180 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint)) {
1181 Report.Error (309, loc, "The type `{0}' must be " +
1182 "convertible to `{1}' in order to " +
1183 "use it as parameter `{2}' in the " +
1184 "generic type or method `{3}'",
1185 atype, gc.ClassConstraint, ptype, DeclarationName);
1191 // Now, check the interface constraints.
1193 foreach (Type it in gc.InterfaceConstraints) {
1195 if (it.IsGenericParameter)
1196 itype = atypes [it.GenericParameterPosition];
1200 if (!CheckConstraint (ec, ptype, aexpr, itype)) {
1201 Report.Error (309, loc, "The type `{0}' must be " +
1202 "convertible to `{1}' in order to " +
1203 "use it as parameter `{2}' in the " +
1204 "generic type or method `{3}'",
1205 atype, itype, ptype, DeclarationName);
1211 // Finally, check the constructor constraint.
1214 if (!gc.HasConstructorConstraint)
1217 if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
1220 MethodGroupExpr mg = Expression.MemberLookup (
1221 ec, atype, ".ctor", MemberTypes.Constructor,
1222 BindingFlags.Public | BindingFlags.Instance |
1223 BindingFlags.DeclaredOnly, loc)
1226 if (atype.IsAbstract || (mg == null) || !mg.IsInstance) {
1227 Report.Error (310, loc, "The type `{0}' must have a public " +
1228 "parameterless constructor in order to use it " +
1229 "as parameter `{1}' in the generic type or " +
1230 "method `{2}'", atype, ptype, DeclarationName);
1237 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
1239 if (!ResolveConstructedType (ec))
1245 public bool CheckConstraints (EmitContext ec)
1247 for (int i = 0; i < gen_params.Length; i++) {
1248 if (!CheckConstraints (ec, i))
1255 public override TypeExpr ResolveAsTypeTerminal (EmitContext ec)
1257 if (base.ResolveAsTypeTerminal (ec) == null)
1260 if (!CheckConstraints (ec))
1266 public bool ResolveConstructedType (EmitContext ec)
1271 return DoResolveType (ec);
1274 // First, resolve the generic type.
1277 Type nested = ec.DeclSpace.FindNestedType (loc, name, out ds);
1278 if (nested != null) {
1279 gt = nested.GetGenericTypeDefinition ();
1281 TypeArguments new_args = new TypeArguments (loc);
1283 foreach (TypeParameter param in ds.TypeParameters)
1284 new_args.Add (new TypeParameterExpr (param, loc));
1286 new_args.Add (args);
1289 return DoResolveType (ec);
1295 SimpleName sn = new SimpleName (name, loc);
1296 TypeExpr resolved = sn.ResolveAsTypeTerminal (ec);
1297 if (resolved == null)
1302 Report.Error (246, loc, "Cannot find type `{0}'<...>",
1307 num_args = TypeManager.GetNumberOfTypeArguments (t);
1308 if (num_args == 0) {
1309 Report.Error (308, loc,
1310 "The non-generic type `{0}' cannot " +
1311 "be used with type arguments.",
1312 TypeManager.CSharpName (t));
1316 gt = t.GetGenericTypeDefinition ();
1317 return DoResolveType (ec);
1320 bool DoResolveType (EmitContext ec)
1323 // Resolve the arguments.
1325 if (args.Resolve (ec) == false)
1328 gen_params = gt.GetGenericArguments ();
1329 atypes = args.Arguments;
1331 if (atypes.Length != gen_params.Length) {
1332 Report.Error (305, loc,
1333 "Using the generic type `{0}' " +
1334 "requires {1} type arguments",
1335 TypeManager.GetFullName (gt),
1341 // Now bind the parameters.
1343 type = gt.BindGenericParameters (atypes);
1347 public Expression GetSimpleName (EmitContext ec)
1349 return new SimpleName (Basename, args, loc);
1352 public override bool CheckAccessLevel (DeclSpace ds)
1354 return ds.CheckAccessLevel (gt);
1357 public override bool AsAccessible (DeclSpace ds, int flags)
1359 return ds.AsAccessible (gt, flags);
1362 public override bool IsClass {
1363 get { return gt.IsClass; }
1366 public override bool IsValueType {
1367 get { return gt.IsValueType; }
1370 public override bool IsInterface {
1371 get { return gt.IsInterface; }
1374 public override bool IsSealed {
1375 get { return gt.IsSealed; }
1378 public override bool IsAttribute {
1379 get { return false; }
1382 public override bool Equals (object obj)
1384 ConstructedType cobj = obj as ConstructedType;
1388 if ((type == null) || (cobj.type == null))
1391 return type == cobj.type;
1394 public override int GetHashCode ()
1396 return base.GetHashCode ();
1399 public string Basename {
1401 int pos = name.LastIndexOf ('`');
1403 return name.Substring (0, pos);
1409 public override string Name {
1416 public override string FullName {
1423 public class GenericMethod : DeclSpace
1425 public GenericMethod (NamespaceEntry ns, TypeContainer parent,
1426 MemberName name, Location l)
1427 : base (ns, parent, name, null, l)
1430 public override TypeBuilder DefineType ()
1432 throw new Exception ();
1435 public override bool Define ()
1437 for (int i = 0; i < TypeParameters.Length; i++)
1438 if (!TypeParameters [i].Resolve (Parent))
1444 public bool Define (MethodBuilder mb, Type return_type)
1449 GenericTypeParameterBuilder[] gen_params;
1450 string[] names = MemberName.TypeArguments.GetDeclarations ();
1451 gen_params = mb.DefineGenericParameters (names);
1452 for (int i = 0; i < TypeParameters.Length; i++)
1453 TypeParameters [i].Define (gen_params [i]);
1455 ec = new EmitContext (
1456 this, this, Location, null, return_type, ModFlags, false);
1458 for (int i = 0; i < TypeParameters.Length; i++) {
1459 if (!TypeParameters [i].ResolveType (ec))
1466 public bool DefineType (EmitContext ec, MethodBuilder mb,
1467 MethodInfo implementing, bool is_override)
1469 for (int i = 0; i < TypeParameters.Length; i++)
1470 if (!TypeParameters [i].DefineType (
1471 ec, mb, implementing, is_override))
1477 public override bool DefineMembers (TypeContainer parent)
1482 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1483 MemberFilter filter, object criteria)
1485 throw new Exception ();
1488 public override MemberCache MemberCache {
1494 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1499 protected override void VerifyObsoleteAttribute()
1504 public override AttributeTargets AttributeTargets {
1506 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1510 public override string DocCommentHeader {
1511 get { return "M:"; }
1515 public class DefaultValueExpression : Expression
1518 LocalTemporary temp_storage;
1520 public DefaultValueExpression (Expression expr, Location loc)
1526 public override Expression DoResolve (EmitContext ec)
1528 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
1533 if (type.IsGenericParameter || TypeManager.IsValueType (type))
1534 temp_storage = new LocalTemporary (ec, type);
1536 eclass = ExprClass.Variable;
1540 public override void Emit (EmitContext ec)
1542 if (temp_storage != null) {
1543 temp_storage.AddressOf (ec, AddressOp.LoadStore);
1544 ec.ig.Emit (OpCodes.Initobj, type);
1545 temp_storage.Emit (ec);
1547 ec.ig.Emit (OpCodes.Ldnull);
1551 public partial class TypeManager
1554 // A list of core types that the compiler requires or uses
1556 static public Type new_constraint_attr_type;
1557 static public Type activator_type;
1558 static public Type generic_ienumerator_type;
1559 static public Type generic_ienumerable_type;
1560 static public Type generic_nullable_type;
1563 // Tracks the generic parameters.
1565 static PtrHashtable builder_to_type_param;
1568 // These methods are called by code generated by the compiler
1570 static public MethodInfo activator_create_instance;
1572 static void InitGenerics ()
1574 builder_to_type_param = new PtrHashtable ();
1577 static void CleanUpGenerics ()
1579 builder_to_type_param = null;
1582 static void InitGenericCoreTypes ()
1584 activator_type = CoreLookupType ("System.Activator");
1585 new_constraint_attr_type = CoreLookupType (
1586 "System.Runtime.CompilerServices.NewConstraintAttribute");
1588 generic_ienumerator_type = CoreLookupType ("System.Collections.Generic.IEnumerator", 1);
1589 generic_ienumerable_type = CoreLookupType ("System.Collections.Generic.IEnumerable", 1);
1590 generic_nullable_type = CoreLookupType ("System.Nullable", 1);
1593 static void InitGenericCodeHelpers ()
1596 Type [] type_arg = { type_type };
1597 activator_create_instance = GetMethod (
1598 activator_type, "CreateInstance", type_arg);
1601 static Type CoreLookupType (string name, int arity)
1603 return CoreLookupType (MemberName.MakeName (name, arity));
1606 public static void AddTypeParameter (Type t, TypeParameter tparam)
1608 if (!builder_to_type_param.Contains (t))
1609 builder_to_type_param.Add (t, tparam);
1612 public static TypeContainer LookupGenericTypeContainer (Type t)
1614 while (t.IsGenericInstance)
1615 t = t.GetGenericTypeDefinition ();
1617 return LookupTypeContainer (t);
1620 public static TypeParameter LookupTypeParameter (Type t)
1622 return (TypeParameter) builder_to_type_param [t];
1625 public static bool HasConstructorConstraint (Type t)
1627 GenericConstraints gc = GetTypeParameterConstraints (t);
1631 return (gc.Attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0;
1634 public static GenericConstraints GetTypeParameterConstraints (Type t)
1636 if (!t.IsGenericParameter)
1637 throw new InvalidOperationException ();
1639 TypeParameter tparam = LookupTypeParameter (t);
1641 return tparam.GenericConstraints;
1643 return new ReflectionConstraints (t);
1646 public static bool IsGeneric (Type t)
1648 DeclSpace ds = (DeclSpace) builder_to_declspace [t];
1650 return ds.IsGeneric;
1653 public static bool HasGenericArguments (Type t)
1655 return GetNumberOfTypeArguments (t) > 0;
1658 public static int GetNumberOfTypeArguments (Type t)
1660 DeclSpace tc = LookupDeclSpace (t);
1662 return tc.IsGeneric ? tc.CountTypeParameters : 0;
1664 return t.HasGenericArguments ? t.GetGenericArguments ().Length : 0;
1667 public static Type[] GetTypeArguments (Type t)
1669 DeclSpace tc = LookupDeclSpace (t);
1672 return Type.EmptyTypes;
1674 TypeParameter[] tparam = tc.TypeParameters;
1675 Type[] ret = new Type [tparam.Length];
1676 for (int i = 0; i < tparam.Length; i++) {
1677 ret [i] = tparam [i].Type;
1678 if (ret [i] == null)
1679 throw new InternalErrorException ();
1684 return t.GetGenericArguments ();
1687 public static bool IsEqual (Type a, Type b)
1692 if ((a is TypeBuilder) && a.IsGenericTypeDefinition && b.IsGenericInstance) {
1694 // `a' is a generic type definition's TypeBuilder and `b' is a
1695 // generic instance of the same type.
1701 // void Test (Stack<T> stack) { }
1704 // The first argument of `Test' will be the generic instance
1705 // "Stack<!0>" - which is the same type than the "Stack" TypeBuilder.
1708 // We hit this via Closure.Filter() for gen-82.cs.
1710 if (a != b.GetGenericTypeDefinition ())
1713 Type[] aparams = a.GetGenericArguments ();
1714 Type[] bparams = b.GetGenericArguments ();
1716 if (aparams.Length != bparams.Length)
1719 for (int i = 0; i < aparams.Length; i++)
1720 if (!IsEqual (aparams [i], bparams [i]))
1726 if (a.IsGenericParameter && b.IsGenericParameter) {
1727 if ((a.DeclaringMethod == null) || (b.DeclaringMethod == null))
1729 return a.GenericParameterPosition == b.GenericParameterPosition;
1732 if (a.IsArray && b.IsArray) {
1733 if (a.GetArrayRank () != b.GetArrayRank ())
1735 return IsEqual (a.GetElementType (), b.GetElementType ());
1738 if (a.IsGenericInstance && b.IsGenericInstance) {
1739 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
1742 Type[] aargs = a.GetGenericArguments ();
1743 Type[] bargs = b.GetGenericArguments ();
1745 if (aargs.Length != bargs.Length)
1748 for (int i = 0; i < aargs.Length; i++) {
1749 if (!IsEqual (aargs [i], bargs [i]))
1759 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_infered, Type[] method_infered)
1761 if (a.IsGenericParameter) {
1763 // If a is an array of a's type, they may never
1767 b = b.GetElementType ();
1773 // If b is a generic parameter or an actual type,
1774 // they may become equal:
1776 // class X<T,U> : I<T>, I<U>
1777 // class X<T> : I<T>, I<float>
1779 if (b.IsGenericParameter || !b.IsGenericInstance) {
1780 int pos = a.GenericParameterPosition;
1781 Type[] args = a.DeclaringMethod != null ? method_infered : class_infered;
1782 if (args [pos] == null) {
1787 return args [pos] == a;
1791 // We're now comparing a type parameter with a
1792 // generic instance. They may become equal unless
1793 // the type parameter appears anywhere in the
1794 // generic instance:
1796 // class X<T,U> : I<T>, I<X<U>>
1797 // -> error because you could instanciate it as
1800 // class X<T> : I<T>, I<X<T>> -> ok
1803 Type[] bargs = GetTypeArguments (b);
1804 for (int i = 0; i < bargs.Length; i++) {
1805 if (a.Equals (bargs [i]))
1812 if (b.IsGenericParameter)
1813 return MayBecomeEqualGenericTypes (b, a, class_infered, method_infered);
1816 // At this point, neither a nor b are a type parameter.
1818 // If one of them is a generic instance, let
1819 // MayBecomeEqualGenericInstances() compare them (if the
1820 // other one is not a generic instance, they can never
1824 if (a.IsGenericInstance || b.IsGenericInstance)
1825 return MayBecomeEqualGenericInstances (a, b, class_infered, method_infered);
1828 // If both of them are arrays.
1831 if (a.IsArray && b.IsArray) {
1832 if (a.GetArrayRank () != b.GetArrayRank ())
1835 a = a.GetElementType ();
1836 b = b.GetElementType ();
1838 return MayBecomeEqualGenericTypes (a, b, class_infered, method_infered);
1842 // Ok, two ordinary types.
1845 return a.Equals (b);
1849 // Checks whether two generic instances may become equal for some
1850 // particular instantiation (26.3.1).
1852 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
1853 Type[] class_infered, Type[] method_infered)
1855 if (!a.IsGenericInstance || !b.IsGenericInstance)
1857 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
1860 return MayBecomeEqualGenericInstances (
1861 GetTypeArguments (a), GetTypeArguments (b), class_infered, method_infered);
1864 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
1865 Type[] class_infered, Type[] method_infered)
1867 if (aargs.Length != bargs.Length)
1870 for (int i = 0; i < aargs.Length; i++) {
1871 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_infered, method_infered))
1878 public static bool IsEqualGenericInstance (Type type, Type parent)
1880 int tcount = GetNumberOfTypeArguments (type);
1881 int pcount = GetNumberOfTypeArguments (parent);
1883 if (type.IsGenericInstance)
1884 type = type.GetGenericTypeDefinition ();
1885 if (parent.IsGenericInstance)
1886 parent = parent.GetGenericTypeDefinition ();
1888 if (tcount != pcount)
1891 return type.Equals (parent);
1894 static public bool IsGenericMethod (MethodBase mb)
1896 if (mb.DeclaringType is TypeBuilder) {
1897 IMethodData method = (IMethodData) builder_to_method [mb];
1901 return method.GenericMethod != null;
1904 return mb.IsGenericMethodDefinition;
1911 static bool InferType (Type pt, Type at, Type[] infered)
1913 if (pt.IsGenericParameter && (pt.DeclaringMethod != null)) {
1914 int pos = pt.GenericParameterPosition;
1916 if (infered [pos] == null) {
1918 while (check.IsArray)
1919 check = check.GetElementType ();
1928 if (infered [pos] != at)
1934 if (!pt.ContainsGenericParameters) {
1935 if (at.ContainsGenericParameters)
1936 return InferType (at, pt, infered);
1943 (at.GetArrayRank () != pt.GetArrayRank ()))
1946 return InferType (pt.GetElementType (), at.GetElementType (), infered);
1951 (pt.GetArrayRank () != at.GetArrayRank ()))
1954 return InferType (pt.GetElementType (), at.GetElementType (), infered);
1957 if (pt.IsByRef && at.IsByRef)
1958 return InferType (pt.GetElementType (), at.GetElementType (), infered);
1959 ArrayList list = new ArrayList ();
1960 if (at.IsGenericInstance)
1963 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
1966 list.AddRange (TypeManager.GetInterfaces (at));
1969 bool found_one = false;
1971 foreach (Type type in list) {
1972 if (!type.IsGenericInstance)
1975 Type[] infered_types = new Type [infered.Length];
1977 if (!InferGenericInstance (pt, type, infered_types))
1980 for (int i = 0; i < infered_types.Length; i++) {
1981 if (infered [i] == null) {
1982 infered [i] = infered_types [i];
1986 if (infered [i] != infered_types [i])
1996 static bool InferGenericInstance (Type pt, Type at, Type[] infered_types)
1998 Type[] at_args = at.GetGenericArguments ();
1999 Type[] pt_args = pt.GetGenericArguments ();
2001 if (at_args.Length != pt_args.Length)
2004 for (int i = 0; i < at_args.Length; i++) {
2005 if (!InferType (pt_args [i], at_args [i], infered_types))
2009 for (int i = 0; i < infered_types.Length; i++) {
2010 if (infered_types [i] == null)
2017 public static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
2018 ref MethodBase method)
2020 if ((arguments == null) || !TypeManager.IsGenericMethod (method))
2025 if (arguments == null)
2028 arg_count = arguments.Count;
2030 ParameterData pd = Invocation.GetParameterData (method);
2032 int pd_count = pd.Count;
2037 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2040 if (pd_count - 1 > arg_count)
2043 if (pd_count == 1 && arg_count == 0)
2046 Type[] method_args = method.GetGenericArguments ();
2047 Type[] infered_types = new Type [method_args.Length];
2050 // If we have come this far, the case which
2051 // remains is when the number of parameters is
2052 // less than or equal to the argument count.
2054 for (int i = 0; i < pd_count - 1; ++i) {
2055 Argument a = (Argument) arguments [i];
2057 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2060 Type pt = pd.ParameterType (i);
2063 if (!InferType (pt, at, infered_types))
2067 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
2069 for (int i = pd_count - 1; i < arg_count; i++) {
2070 Argument a = (Argument) arguments [i];
2072 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2075 if (!InferType (element_type, a.Type, infered_types))
2079 for (int i = 0; i < infered_types.Length; i++)
2080 if (infered_types [i] == null)
2083 method = method.BindGenericParameters (infered_types);
2087 public static bool InferTypeArguments (Type[] param_types, Type[] arg_types, Type[] infered_types)
2089 if (infered_types == null)
2092 for (int i = 0; i < arg_types.Length; i++) {
2093 if (arg_types [i] == null)
2096 if (!InferType (param_types [i], arg_types [i], infered_types))
2100 for (int i = 0; i < infered_types.Length; i++)
2101 if (infered_types [i] == null)
2107 public static bool InferTypeArguments (EmitContext ec, ArrayList arguments,
2108 ref MethodBase method)
2110 if (!TypeManager.IsGenericMethod (method))
2114 if (arguments != null)
2115 arg_count = arguments.Count;
2119 ParameterData pd = Invocation.GetParameterData (method);
2120 if (arg_count != pd.Count)
2123 Type[] method_args = method.GetGenericArguments ();
2125 bool is_open = false;
2126 for (int i = 0; i < method_args.Length; i++) {
2127 if (method_args [i].IsGenericParameter) {
2135 Type[] infered_types = new Type [method_args.Length];
2137 Type[] param_types = new Type [pd.Count];
2138 Type[] arg_types = new Type [pd.Count];
2140 for (int i = 0; i < arg_count; i++) {
2141 param_types [i] = pd.ParameterType (i);
2143 Argument a = (Argument) arguments [i];
2144 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2147 arg_types [i] = a.Type;
2150 if (!InferTypeArguments (param_types, arg_types, infered_types))
2153 method = method.BindGenericParameters (infered_types);
2157 public static bool InferTypeArguments (EmitContext ec, ParameterData apd,
2158 ref MethodBase method)
2160 if (!TypeManager.IsGenericMethod (method))
2163 ParameterData pd = Invocation.GetParameterData (method);
2164 if (apd.Count != pd.Count)
2167 Type[] method_args = method.GetGenericArguments ();
2168 Type[] infered_types = new Type [method_args.Length];
2170 Type[] param_types = new Type [pd.Count];
2171 Type[] arg_types = new Type [pd.Count];
2173 for (int i = 0; i < apd.Count; i++) {
2174 param_types [i] = pd.ParameterType (i);
2175 arg_types [i] = apd.ParameterType (i);
2178 if (!InferTypeArguments (param_types, arg_types, infered_types))
2181 method = method.BindGenericParameters (infered_types);