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 {
23 /// Abstract base class for type parameter constraints.
24 /// The type parameter can come from a generic type definition or from reflection.
26 public abstract class GenericConstraints {
27 public abstract GenericParameterAttributes Attributes {
31 public bool HasConstructorConstraint {
32 get { return (Attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0; }
35 public bool HasReferenceTypeConstraint {
36 get { return (Attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0; }
39 public bool HasValueTypeConstraint {
40 get { return (Attributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0; }
43 public virtual bool HasClassConstraint {
44 get { return ClassConstraint != null; }
47 public abstract Type ClassConstraint {
51 public abstract Type[] InterfaceConstraints {
55 public abstract Type EffectiveBaseClass {
60 // Returns whether the type parameter is "known to be a reference type".
62 public virtual bool IsReferenceType {
64 if (HasReferenceTypeConstraint)
66 if (HasValueTypeConstraint)
69 if (ClassConstraint != null) {
70 if (ClassConstraint.IsValueType)
73 if (ClassConstraint != TypeManager.object_type)
77 foreach (Type t in InterfaceConstraints) {
78 if (!t.IsGenericParameter)
81 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
82 if ((gc != null) && gc.IsReferenceType)
91 // Returns whether the type parameter is "known to be a value type".
93 public virtual bool IsValueType {
95 if (HasValueTypeConstraint)
97 if (HasReferenceTypeConstraint)
100 if (ClassConstraint != null) {
101 if (!ClassConstraint.IsValueType)
104 if (ClassConstraint != TypeManager.value_type)
108 foreach (Type t in InterfaceConstraints) {
109 if (!t.IsGenericParameter)
112 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
113 if ((gc != null) && gc.IsValueType)
122 public enum SpecialConstraint
130 /// Tracks the constraints for a type parameter from a generic type definition.
132 public class Constraints : GenericConstraints {
134 ArrayList constraints;
138 // name is the identifier, constraints is an arraylist of
139 // Expressions (with types) or `true' for the constructor constraint.
141 public Constraints (string name, ArrayList constraints,
145 this.constraints = constraints;
149 public string TypeParameter {
155 GenericParameterAttributes attrs;
156 TypeExpr class_constraint;
157 ArrayList iface_constraints;
158 ArrayList type_param_constraints;
160 Type class_constraint_type;
161 Type[] iface_constraint_types;
162 Type effective_base_type;
166 /// Resolve the constraints - but only resolve things into Expression's, not
167 /// into actual types.
169 public bool Resolve (EmitContext ec)
174 iface_constraints = new ArrayList ();
175 type_param_constraints = new ArrayList ();
177 foreach (object obj in constraints) {
178 if (HasConstructorConstraint) {
179 Report.Error (401, loc,
180 "The new() constraint must be last.");
184 if (obj is SpecialConstraint) {
185 SpecialConstraint sc = (SpecialConstraint) obj;
187 if (sc == SpecialConstraint.Constructor) {
188 if (!HasValueTypeConstraint) {
189 attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
194 451, loc, "The new () constraint " +
195 "cannot be used with the `struct' " +
200 if ((num_constraints > 0) || HasReferenceTypeConstraint || HasValueTypeConstraint) {
201 Report.Error (449, loc,
202 "The `class' or `struct' " +
203 "constraint must be first");
207 if (sc == SpecialConstraint.ReferenceType)
208 attrs |= GenericParameterAttributes.ReferenceTypeConstraint;
210 attrs |= GenericParameterAttributes.NotNullableValueTypeConstraint;
214 int errors = Report.Errors;
215 FullNamedExpression fn = ((Expression) obj).ResolveAsTypeStep (ec);
218 if (errors != Report.Errors)
221 Report.Error (246, loc, "Cannot find type '{0}'", obj);
226 ConstructedType cexpr = fn as ConstructedType;
228 if (!cexpr.ResolveConstructedType (ec))
233 expr = fn.ResolveAsTypeTerminal (ec);
238 TypeParameterExpr texpr = expr as TypeParameterExpr;
240 type_param_constraints.Add (expr);
241 else if (expr.IsInterface)
242 iface_constraints.Add (expr);
243 else if (class_constraint != null) {
244 Report.Error (406, loc,
245 "`{0}': the class constraint for `{1}' " +
246 "must come before any other constraints.",
249 } else if (HasReferenceTypeConstraint || HasValueTypeConstraint) {
250 Report.Error (450, loc, "`{0}': cannot specify both " +
251 "a constraint class and the `class' " +
252 "or `struct' constraint.", expr.Name);
255 class_constraint = expr;
264 bool CheckTypeParameterConstraints (TypeParameter tparam, Hashtable seen)
266 seen.Add (tparam, true);
268 Constraints constraints = tparam.Constraints;
269 if (constraints == null)
272 if (constraints.HasValueTypeConstraint) {
273 Report.Error (456, loc, "Type parameter `{0}' has " +
274 "the `struct' constraint, so it cannot " +
275 "be used as a constraint for `{1}'",
280 if (constraints.type_param_constraints == null)
283 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
284 if (seen.Contains (expr.TypeParameter)) {
285 Report.Error (454, loc, "Circular constraint " +
286 "dependency involving `{0}' and `{1}'",
287 tparam.Name, expr.Name);
291 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
299 /// Resolve the constraints into actual types.
301 public bool ResolveTypes (EmitContext ec)
303 if (effective_base_type != null)
306 foreach (object obj in constraints) {
307 ConstructedType cexpr = obj as ConstructedType;
311 if (!cexpr.CheckConstraints (ec))
315 foreach (TypeParameterExpr expr in type_param_constraints) {
316 Hashtable seen = new Hashtable ();
317 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
321 ArrayList list = new ArrayList ();
323 foreach (TypeExpr iface_constraint in iface_constraints) {
324 foreach (Type type in list) {
325 if (!type.Equals (iface_constraint.Type))
328 Report.Error (405, loc,
329 "Duplicate constraint `{0}' for type " +
330 "parameter `{1}'.", iface_constraint.Type,
335 TypeExpr te = iface_constraint.ResolveAsTypeTerminal (ec);
342 foreach (TypeParameterExpr expr in type_param_constraints) {
343 foreach (Type type in list) {
344 if (!type.Equals (expr.Type))
347 Report.Error (405, loc,
348 "Duplicate constraint `{0}' for type " +
349 "parameter `{1}'.", expr.Type, name);
353 list.Add (expr.Type);
356 ArrayList new_list = new ArrayList ();
357 foreach (Type iface in list) {
358 if (new_list.Contains (iface))
361 new_list.Add (iface);
363 Type [] implementing = TypeManager.GetInterfaces (iface);
365 foreach (Type imp in implementing) {
366 if (!new_list.Contains (imp))
371 iface_constraint_types = new Type [new_list.Count];
372 new_list.CopyTo (iface_constraint_types, 0);
374 if (class_constraint != null) {
375 TypeExpr te = class_constraint.ResolveAsTypeTerminal (ec);
379 class_constraint_type = te.Type;
380 if (class_constraint_type == null)
383 if (class_constraint_type.IsSealed) {
384 Report.Error (701, loc,
385 "`{0}' is not a valid bound. Bounds " +
386 "must be interfaces or non sealed " +
387 "classes", class_constraint_type);
391 if ((class_constraint_type == TypeManager.array_type) ||
392 (class_constraint_type == TypeManager.delegate_type) ||
393 (class_constraint_type == TypeManager.enum_type) ||
394 (class_constraint_type == TypeManager.value_type) ||
395 (class_constraint_type == TypeManager.object_type)) {
396 Report.Error (702, loc,
397 "Bound cannot be special class `{0}'",
398 class_constraint_type);
403 if (class_constraint_type != null)
404 effective_base_type = class_constraint_type;
405 else if (HasValueTypeConstraint)
406 effective_base_type = TypeManager.value_type;
408 effective_base_type = TypeManager.object_type;
414 /// Check whether there are no conflicts in our type parameter constraints.
416 /// This is an example:
420 /// where U : T, struct
422 public bool CheckDependencies (EmitContext ec)
424 foreach (TypeParameterExpr expr in type_param_constraints) {
425 if (!CheckDependencies (expr.TypeParameter, ec))
432 bool CheckDependencies (TypeParameter tparam, EmitContext ec)
434 Constraints constraints = tparam.Constraints;
435 if (constraints == null)
438 if (HasValueTypeConstraint && constraints.HasClassConstraint) {
439 Report.Error (455, loc, "Type parameter `{0}' inherits " +
440 "conflicting constraints `{1}' and `{2}'",
441 name, constraints.ClassConstraint,
446 if (HasClassConstraint && constraints.HasClassConstraint) {
447 Type t1 = ClassConstraint;
448 TypeExpr e1 = class_constraint;
449 Type t2 = constraints.ClassConstraint;
450 TypeExpr e2 = constraints.class_constraint;
452 if (!Convert.ImplicitReferenceConversionExists (ec, e1, t2) &&
453 !Convert.ImplicitReferenceConversionExists (ec, e2, t1)) {
454 Report.Error (455, loc,
455 "Type parameter `{0}' inherits " +
456 "conflicting constraints `{1}' and `{2}'",
462 if (constraints.type_param_constraints == null)
465 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
466 if (!CheckDependencies (expr.TypeParameter, ec))
474 /// Set the attributes on the GenericTypeParameterBuilder.
477 /// This is not done in Resolve() since Resolve() may be called before
478 /// the GenericTypeParameterBuilder is created (partial generic classes).
480 public void Define (GenericTypeParameterBuilder type)
482 type.SetGenericParameterAttributes (attrs);
485 public override GenericParameterAttributes Attributes {
486 get { return attrs; }
489 public override bool HasClassConstraint {
490 get { return class_constraint != null; }
493 public override Type ClassConstraint {
494 get { return class_constraint_type; }
497 public override Type[] InterfaceConstraints {
498 get { return iface_constraint_types; }
501 public override Type EffectiveBaseClass {
502 get { return effective_base_type; }
505 public bool IsSubclassOf (Type t)
507 if ((class_constraint_type != null) &&
508 class_constraint_type.IsSubclassOf (t))
511 if (iface_constraint_types == null)
514 foreach (Type iface in iface_constraint_types) {
515 if (TypeManager.IsSubclassOf (iface, t))
523 /// This is used when we're implementing a generic interface method.
524 /// Each method type parameter in implementing method must have the same
525 /// constraints than the corresponding type parameter in the interface
526 /// method. To do that, we're called on each of the implementing method's
529 public bool CheckInterfaceMethod (EmitContext ec, GenericConstraints gc)
531 if (gc.Attributes != attrs)
534 if (HasClassConstraint != gc.HasClassConstraint)
536 if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
539 int gc_icount = gc.InterfaceConstraints != null ?
540 gc.InterfaceConstraints.Length : 0;
541 int icount = InterfaceConstraints != null ?
542 InterfaceConstraints.Length : 0;
544 if (gc_icount != icount)
547 foreach (Type iface in gc.InterfaceConstraints) {
549 foreach (Type check in InterfaceConstraints) {
550 if (TypeManager.IsEqual (iface, check)) {
565 /// A type parameter from a generic type definition.
567 public class TypeParameter : MemberCore, IMemberContainer {
569 GenericConstraints gc;
570 Constraints constraints;
572 GenericTypeParameterBuilder type;
574 public TypeParameter (TypeContainer parent, string name,
575 Constraints constraints, Location loc)
576 : base (parent, new MemberName (name, loc), null)
579 this.constraints = constraints;
583 public GenericConstraints GenericConstraints {
585 return gc != null ? gc : constraints;
589 public Constraints Constraints {
595 public bool HasConstructorConstraint {
597 if (constraints != null)
598 return constraints.HasConstructorConstraint;
611 /// This is the first method which is called during the resolving
612 /// process; we're called immediately after creating the type parameters
613 /// with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
616 /// We're either called from TypeContainer.DefineType() or from
617 /// GenericMethod.Define() (called from Method.Define()).
619 public void Define (GenericTypeParameterBuilder type)
621 if (this.type != null)
622 throw new InvalidOperationException ();
625 TypeManager.AddTypeParameter (type, this);
629 /// This is the second method which is called during the resolving
630 /// process - in case of class type parameters, we're called from
631 /// TypeContainer.ResolveType() - after it resolved the class'es
632 /// base class and interfaces. For method type parameters, we're
633 /// called immediately after Define().
635 /// We're just resolving the constraints into expressions here, we
636 /// don't resolve them into actual types.
638 /// Note that in the special case of partial generic classes, we may be
639 /// called _before_ Define() and we may also be called multiple types.
641 public bool Resolve (DeclSpace ds)
643 if (constraints != null) {
644 if (!constraints.Resolve (ds.EmitContext)) {
654 /// This is the third method which is called during the resolving
655 /// process. We're called immediately after calling Resolve() on
656 /// all of the current class'es type parameters.
658 /// All we do is setting the attributes on the GenericTypeParameterBuilder.
661 /// This is not done in Resolve() since Resolve() may be called before
662 /// Define() for partial generic classes.
664 public void DefineConstraints ()
666 if (constraints != null)
667 constraints.Define (type);
671 /// This is the forth method which is called during the resolving
672 /// process. We're called immediately after calling DefineConstraints()
673 /// on all of the current class'es type parameters.
675 /// Our job is to resolve the constraints to actual types.
677 /// Note that we may have circular dependencies on type parameters - this
678 /// is why Resolve() and ResolveType() are separate.
680 public bool ResolveType (EmitContext ec)
682 if (constraints != null) {
683 if (!constraints.ResolveTypes (ec)) {
693 /// This is the fith and last method which is called during the resolving
694 /// process. We're called after everything is fully resolved and actually
695 /// register the constraints with SRE and the TypeManager.
697 public bool DefineType (EmitContext ec)
699 return DefineType (ec, null, null, false);
703 /// This is the fith and last method which is called during the resolving
704 /// process. We're called after everything is fully resolved and actually
705 /// register the constraints with SRE and the TypeManager.
707 /// The `builder', `implementing' and `is_override' arguments are only
708 /// applicable to method type parameters.
710 public bool DefineType (EmitContext ec, MethodBuilder builder,
711 MethodInfo implementing, bool is_override)
713 if (!ResolveType (ec))
716 if (implementing != null) {
717 if (is_override && (constraints != null)) {
719 460, loc, "Constraints for override and " +
720 "explicit interface implementation methods " +
721 "are inherited from the base method so they " +
722 "cannot be specified directly");
726 MethodBase mb = implementing;
727 if (mb.Mono_IsInflatedMethod)
728 mb = mb.GetGenericMethodDefinition ();
730 int pos = type.GenericParameterPosition;
731 ParameterData pd = TypeManager.GetParameterData (mb);
732 GenericConstraints temp_gc = pd.GenericConstraints (pos);
733 Type mparam = mb.GetGenericArguments () [pos];
736 gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
737 else if (constraints != null)
738 gc = new InflatedConstraints (constraints, implementing.DeclaringType);
741 if (constraints != null) {
744 else if (!constraints.CheckInterfaceMethod (ec, gc))
747 if (!is_override && (temp_gc != null))
752 Report.SymbolRelatedToPreviousError (implementing);
755 425, loc, "The constraints for type " +
756 "parameter `{0}' of method `{1}' must match " +
757 "the constraints for type parameter `{2}' " +
758 "of interface method `{3}'. Consider using " +
759 "an explicit interface implementation instead",
760 Name, TypeManager.CSharpSignature (builder),
761 mparam, TypeManager.CSharpSignature (mb));
765 gc = (GenericConstraints) constraints;
771 if (gc.HasClassConstraint)
772 type.SetBaseTypeConstraint (gc.ClassConstraint);
774 type.SetInterfaceConstraints (gc.InterfaceConstraints);
775 TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
781 /// Check whether there are no conflicts in our type parameter constraints.
783 /// This is an example:
787 /// where U : T, struct
789 public bool CheckDependencies (EmitContext ec)
791 if (constraints != null)
792 return constraints.CheckDependencies (ec);
798 /// This is called for each part of a partial generic type definition.
800 /// If `new_constraints' is not null and we don't already have constraints,
801 /// they become our constraints. If we already have constraints, we must
802 /// check that they're the same.
805 public bool UpdateConstraints (EmitContext ec, Constraints new_constraints)
808 throw new InvalidOperationException ();
810 if (constraints == null) {
811 new_constraints = constraints;
813 } else if (new_constraints == null)
816 if (!new_constraints.Resolve (ec))
818 if (!new_constraints.ResolveTypes (ec))
821 return constraints.CheckInterfaceMethod (ec, new_constraints);
824 public override string DocCommentHeader {
826 throw new InvalidOperationException (
827 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
835 public override bool Define ()
840 public override void ApplyAttributeBuilder (Attribute a,
841 CustomAttributeBuilder cb)
844 public override AttributeTargets AttributeTargets {
846 return (AttributeTargets) 0;
850 public override string[] ValidAttributeTargets {
852 return new string [0];
860 string IMemberContainer.Name {
864 MemberCache IMemberContainer.BaseCache {
868 bool IMemberContainer.IsInterface {
872 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
874 return FindMembers (mt, bf, null, null);
877 MemberCache IMemberContainer.MemberCache {
881 public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
882 MemberFilter filter, object criteria)
884 if (constraints == null)
885 return MemberList.Empty;
887 ArrayList members = new ArrayList ();
889 GenericConstraints gc = (GenericConstraints) constraints;
891 if (gc.HasClassConstraint) {
892 MemberList list = TypeManager.FindMembers (
893 gc.ClassConstraint, mt, bf, filter, criteria);
895 members.AddRange (list);
898 foreach (Type t in gc.InterfaceConstraints) {
899 MemberList list = TypeManager.FindMembers (
900 t, mt, bf, filter, criteria);
902 members.AddRange (list);
905 return new MemberList (members);
908 public bool IsSubclassOf (Type t)
913 if (constraints != null)
914 return constraints.IsSubclassOf (t);
919 public override string ToString ()
921 return "TypeParameter[" + name + "]";
924 protected class InflatedConstraints : GenericConstraints
926 GenericConstraints gc;
928 Type class_constraint;
929 Type[] iface_constraints;
932 public InflatedConstraints (GenericConstraints gc, Type declaring)
936 dargs = TypeManager.GetTypeArguments (declaring);
938 ArrayList list = new ArrayList ();
939 if (gc.HasClassConstraint)
940 list.Add (inflate (gc.ClassConstraint));
941 foreach (Type iface in gc.InterfaceConstraints)
942 list.Add (inflate (iface));
944 bool has_class_constr = false;
945 if (list.Count > 0) {
946 Type first = (Type) list [0];
947 has_class_constr = !first.IsInterface && !first.IsGenericParameter;
950 if ((list.Count > 0) && has_class_constr) {
951 class_constraint = (Type) list [0];
952 iface_constraints = new Type [list.Count - 1];
953 list.CopyTo (1, iface_constraints, 0, list.Count - 1);
955 iface_constraints = new Type [list.Count];
956 list.CopyTo (iface_constraints, 0);
959 if (HasValueTypeConstraint)
960 base_type = TypeManager.value_type;
961 else if (class_constraint != null)
962 base_type = class_constraint;
964 base_type = TypeManager.object_type;
967 Type inflate (Type t)
971 if (t.IsGenericParameter)
972 return dargs [t.GenericParameterPosition];
973 if (t.IsGenericInstance) {
974 t = t.GetGenericTypeDefinition ();
975 t = t.MakeGenericType (dargs);
981 public override GenericParameterAttributes Attributes {
982 get { return gc.Attributes; }
985 public override Type ClassConstraint {
986 get { return class_constraint; }
989 public override Type EffectiveBaseClass {
990 get { return base_type; }
993 public override Type[] InterfaceConstraints {
994 get { return iface_constraints; }
1000 /// A TypeExpr which already resolved to a type parameter.
1002 public class TypeParameterExpr : TypeExpr {
1003 TypeParameter type_parameter;
1005 public override string Name {
1007 return type_parameter.Name;
1011 public override string FullName {
1013 return type_parameter.Name;
1017 public TypeParameter TypeParameter {
1019 return type_parameter;
1023 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1025 this.type_parameter = type_parameter;
1029 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
1031 type = type_parameter.Type;
1036 public override bool IsInterface {
1037 get { return false; }
1040 public override bool CheckAccessLevel (DeclSpace ds)
1045 public void Error_CannotUseAsUnmanagedType (Location loc)
1047 Report.Error (-203, loc, "Can not use type parameter as unamanged type");
1052 /// Tracks the type arguments when instantiating a generic type. We're used in
1053 /// ConstructedType.
1055 public class TypeArguments {
1056 public readonly Location Location;
1063 public TypeArguments (Location loc)
1065 args = new ArrayList ();
1066 this.Location = loc;
1069 public TypeArguments (int dimension, Location loc)
1071 this.dimension = dimension;
1072 this.Location = loc;
1075 public void Add (Expression type)
1078 throw new InvalidOperationException ();
1083 public void Add (TypeArguments new_args)
1086 throw new InvalidOperationException ();
1088 args.AddRange (new_args.args);
1092 /// We're used during the parsing process: the parser can't distinguish
1093 /// between type parameters and type arguments. Because of that, the
1094 /// parser creates a `MemberName' with `TypeArguments' for both cases and
1095 /// in case of a generic type definition, we call GetDeclarations().
1097 public string[] GetDeclarations ()
1099 string[] ret = new string [args.Count];
1100 for (int i = 0; i < args.Count; i++) {
1101 SimpleName sn = args [i] as SimpleName;
1107 Report.Error (81, Location, "Type parameter declaration " +
1108 "must be an identifier not a type");
1115 /// We may only be used after Resolve() is called and return the fully
1118 public Type[] Arguments {
1124 public bool HasTypeArguments {
1126 return has_type_args;
1139 public bool IsUnbound {
1141 return dimension > 0;
1145 public override string ToString ()
1147 StringBuilder s = new StringBuilder ();
1150 for (int i = 0; i < count; i++){
1152 // FIXME: Use TypeManager.CSharpname once we have the type
1155 s.Append (args [i].ToString ());
1159 return s.ToString ();
1163 /// Resolve the type arguments.
1165 public bool Resolve (EmitContext ec)
1167 int count = args.Count;
1170 atypes = new Type [count];
1172 for (int i = 0; i < count; i++){
1173 TypeExpr te = ((Expression) args [i]).ResolveAsTypeTerminal (ec);
1178 if (te is TypeParameterExpr)
1179 has_type_args = true;
1181 if (te.Type.IsPointer) {
1182 Report.Error (306, Location, "The type `{0}' may not be used " +
1183 "as a type argument.", TypeManager.CSharpName (te.Type));
1187 atypes [i] = te.Type;
1194 /// An instantiation of a generic type.
1196 public class ConstructedType : TypeExpr {
1198 FullNamedExpression name;
1200 Type[] gen_params, atypes;
1204 /// Instantiate the generic type `fname' with the type arguments `args'.
1206 public ConstructedType (FullNamedExpression fname, TypeArguments args, Location l)
1212 eclass = ExprClass.Type;
1213 full_name = name + "<" + args.ToString () + ">";
1216 protected ConstructedType (TypeArguments args, Location l)
1221 eclass = ExprClass.Type;
1224 protected ConstructedType (TypeParameter[] type_params, Location l)
1228 args = new TypeArguments (l);
1229 foreach (TypeParameter type_param in type_params)
1230 args.Add (new TypeParameterExpr (type_param, l));
1232 eclass = ExprClass.Type;
1236 /// This is used to construct the `this' type inside a generic type definition.
1238 public ConstructedType (Type t, TypeParameter[] type_params, Location l)
1239 : this (type_params, l)
1241 gt = t.GetGenericTypeDefinition ();
1243 this.name = new TypeExpression (gt, l);
1244 full_name = gt.FullName + "<" + args.ToString () + ">";
1248 /// Instantiate the generic type `t' with the type arguments `args'.
1249 /// Use this constructor if you already know the fully resolved
1252 public ConstructedType (Type t, TypeArguments args, Location l)
1255 gt = t.GetGenericTypeDefinition ();
1257 this.name = new TypeExpression (gt, l);
1258 full_name = gt.FullName + "<" + args.ToString () + ">";
1261 public TypeArguments TypeArguments {
1262 get { return args; }
1265 protected string DeclarationName {
1267 StringBuilder sb = new StringBuilder ();
1268 sb.Append (gt.FullName);
1270 for (int i = 0; i < gen_params.Length; i++) {
1273 sb.Append (gen_params [i]);
1276 return sb.ToString ();
1280 protected bool CheckConstraint (EmitContext ec, Type ptype, Expression expr,
1283 if (TypeManager.HasGenericArguments (ctype)) {
1284 Type[] types = TypeManager.GetTypeArguments (ctype);
1286 TypeArguments new_args = new TypeArguments (loc);
1288 for (int i = 0; i < types.Length; i++) {
1291 if (t.IsGenericParameter) {
1292 int pos = t.GenericParameterPosition;
1293 t = args.Arguments [pos];
1295 new_args.Add (new TypeExpression (t, loc));
1298 TypeExpr ct = new ConstructedType (ctype, new_args, loc);
1299 if (ct.ResolveAsTypeStep (ec) == null)
1304 return Convert.ImplicitStandardConversionExists (ec, expr, ctype);
1307 protected bool CheckConstraints (EmitContext ec, int index)
1309 Type atype = atypes [index];
1310 Type ptype = gen_params [index];
1315 Expression aexpr = new EmptyExpression (atype);
1317 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1321 bool is_class, is_struct;
1322 if (atype.IsGenericParameter) {
1323 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1325 is_class = agc.HasReferenceTypeConstraint;
1326 is_struct = agc.HasValueTypeConstraint;
1328 is_class = is_struct = false;
1331 is_class = atype.IsClass;
1332 is_struct = atype.IsValueType;
1336 // First, check the `class' and `struct' constraints.
1338 if (gc.HasReferenceTypeConstraint && !is_class) {
1339 Report.Error (452, loc, "The type `{0}' must be " +
1340 "a reference type in order to use it " +
1341 "as type parameter `{1}' in the " +
1342 "generic type or method `{2}'.",
1343 atype, ptype, DeclarationName);
1345 } else if (gc.HasValueTypeConstraint && !is_struct) {
1346 Report.Error (453, loc, "The type `{0}' must be " +
1347 "a value type in order to use it " +
1348 "as type parameter `{1}' in the " +
1349 "generic type or method `{2}'.",
1350 atype, ptype, DeclarationName);
1355 // The class constraint comes next.
1357 if (gc.HasClassConstraint) {
1358 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint)) {
1359 Report.Error (309, loc, "The type `{0}' must be " +
1360 "convertible to `{1}' in order to " +
1361 "use it as parameter `{2}' in the " +
1362 "generic type or method `{3}'",
1363 atype, gc.ClassConstraint, ptype, DeclarationName);
1369 // Now, check the interface constraints.
1371 foreach (Type it in gc.InterfaceConstraints) {
1373 if (it.IsGenericParameter)
1374 itype = atypes [it.GenericParameterPosition];
1378 if (!CheckConstraint (ec, ptype, aexpr, itype)) {
1379 Report.Error (309, loc, "The type `{0}' must be " +
1380 "convertible to `{1}' in order to " +
1381 "use it as parameter `{2}' in the " +
1382 "generic type or method `{3}'",
1383 atype, itype, ptype, DeclarationName);
1389 // Finally, check the constructor constraint.
1392 if (!gc.HasConstructorConstraint)
1395 if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
1398 MethodGroupExpr mg = Expression.MemberLookup (
1399 ec, atype, ".ctor", MemberTypes.Constructor,
1400 BindingFlags.Public | BindingFlags.Instance |
1401 BindingFlags.DeclaredOnly, loc)
1404 if (!atype.IsAbstract && (mg != null) && mg.IsInstance) {
1405 foreach (MethodBase mb in mg.Methods) {
1406 ParameterData pd = TypeManager.GetParameterData (mb);
1412 Report.Error (310, loc, "The type `{0}' must have a public " +
1413 "parameterless constructor in order to use it " +
1414 "as parameter `{1}' in the generic type or " +
1415 "method `{2}'", atype, ptype, DeclarationName);
1419 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
1421 if (!ResolveConstructedType (ec))
1428 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1429 /// after fully resolving the constructed type.
1431 public bool CheckConstraints (EmitContext ec)
1433 for (int i = 0; i < gen_params.Length; i++) {
1434 if (!CheckConstraints (ec, i))
1442 /// Resolve the constructed type, but don't check the constraints.
1444 public bool ResolveConstructedType (EmitContext ec)
1448 // If we already know the fully resolved generic type.
1450 return DoResolveType (ec);
1456 Report.Error (246, loc, "Cannot find type `{0}'<...>", Name);
1460 num_args = TypeManager.GetNumberOfTypeArguments (t);
1461 if (num_args == 0) {
1462 Report.Error (308, loc,
1463 "The non-generic type `{0}' cannot " +
1464 "be used with type arguments.",
1465 TypeManager.CSharpName (t));
1469 gt = t.GetGenericTypeDefinition ();
1470 return DoResolveType (ec);
1473 bool DoResolveType (EmitContext ec)
1476 // Resolve the arguments.
1478 if (args.Resolve (ec) == false)
1481 gen_params = gt.GetGenericArguments ();
1482 atypes = args.Arguments;
1484 if (atypes.Length != gen_params.Length) {
1485 Report.Error (305, loc,
1486 "Using the generic type `{0}' " +
1487 "requires {1} type arguments",
1488 TypeManager.GetFullName (gt),
1494 // Now bind the parameters.
1496 type = gt.MakeGenericType (atypes);
1500 public Expression GetSimpleName (EmitContext ec)
1505 public override bool CheckAccessLevel (DeclSpace ds)
1507 return ds.CheckAccessLevel (gt);
1510 public override bool AsAccessible (DeclSpace ds, int flags)
1512 return ds.AsAccessible (gt, flags);
1515 public override bool IsClass {
1516 get { return gt.IsClass; }
1519 public override bool IsValueType {
1520 get { return gt.IsValueType; }
1523 public override bool IsInterface {
1524 get { return gt.IsInterface; }
1527 public override bool IsSealed {
1528 get { return gt.IsSealed; }
1531 public override bool Equals (object obj)
1533 ConstructedType cobj = obj as ConstructedType;
1537 if ((type == null) || (cobj.type == null))
1540 return type == cobj.type;
1543 public override int GetHashCode ()
1545 return base.GetHashCode ();
1548 public override string Name {
1555 public override string FullName {
1563 /// A generic method definition.
1565 public class GenericMethod : DeclSpace
1567 public GenericMethod (NamespaceEntry ns, TypeContainer parent, MemberName name)
1568 : base (ns, parent, name, null)
1571 public override TypeBuilder DefineType ()
1573 throw new Exception ();
1576 public override bool Define ()
1578 ec = new EmitContext (this, this, Location, null, null, ModFlags, false);
1580 for (int i = 0; i < TypeParameters.Length; i++)
1581 if (!TypeParameters [i].Resolve (this))
1588 /// Define and resolve the type parameters.
1589 /// We're called from Method.Define().
1591 public bool Define (MethodBuilder mb)
1593 GenericTypeParameterBuilder[] gen_params;
1594 string[] names = MemberName.TypeArguments.GetDeclarations ();
1595 gen_params = mb.DefineGenericParameters (names);
1596 for (int i = 0; i < TypeParameters.Length; i++)
1597 TypeParameters [i].Define (gen_params [i]);
1602 for (int i = 0; i < TypeParameters.Length; i++) {
1603 if (!TypeParameters [i].ResolveType (ec))
1611 /// We're called from MethodData.Define() after creating the MethodBuilder.
1613 public bool DefineType (EmitContext ec, MethodBuilder mb,
1614 MethodInfo implementing, bool is_override)
1616 for (int i = 0; i < TypeParameters.Length; i++)
1617 if (!TypeParameters [i].DefineType (
1618 ec, mb, implementing, is_override))
1624 public override bool DefineMembers (TypeContainer parent)
1629 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1630 MemberFilter filter, object criteria)
1632 throw new Exception ();
1635 public override MemberCache MemberCache {
1641 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1646 public override AttributeTargets AttributeTargets {
1648 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1652 public override string DocCommentHeader {
1653 get { return "M:"; }
1657 public class DefaultValueExpression : Expression
1661 public DefaultValueExpression (Expression expr, Location loc)
1667 public override Expression DoResolve (EmitContext ec)
1669 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
1675 eclass = ExprClass.Variable;
1679 public override void Emit (EmitContext ec)
1681 if (type.IsGenericParameter || TypeManager.IsValueType (type)) {
1682 LocalTemporary temp_storage = new LocalTemporary (ec, type);
1684 temp_storage.AddressOf (ec, AddressOp.LoadStore);
1685 ec.ig.Emit (OpCodes.Initobj, type);
1686 temp_storage.Emit (ec);
1688 ec.ig.Emit (OpCodes.Ldnull);
1692 public class NullableType : TypeExpr
1694 Expression underlying;
1696 public NullableType (Expression underlying, Location l)
1698 this.underlying = underlying;
1701 eclass = ExprClass.Type;
1704 public NullableType (Type type, Location loc)
1705 : this (new TypeExpression (type, loc), loc)
1708 public override string Name {
1709 get { return underlying.ToString () + "?"; }
1712 public override string FullName {
1713 get { return underlying.ToString () + "?"; }
1716 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
1718 TypeArguments args = new TypeArguments (loc);
1719 args.Add (underlying);
1721 ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
1722 return ctype.ResolveAsTypeTerminal (ec);
1726 public partial class TypeManager
1729 // A list of core types that the compiler requires or uses
1731 static public Type new_constraint_attr_type;
1732 static public Type activator_type;
1733 static public Type generic_ienumerator_type;
1734 static public Type generic_ienumerable_type;
1735 static public Type generic_nullable_type;
1738 // Tracks the generic parameters.
1740 static PtrHashtable builder_to_type_param;
1743 // These methods are called by code generated by the compiler
1745 static public MethodInfo activator_create_instance;
1747 static void InitGenerics ()
1749 builder_to_type_param = new PtrHashtable ();
1752 static void CleanUpGenerics ()
1754 builder_to_type_param = null;
1757 static void InitGenericCoreTypes ()
1759 activator_type = CoreLookupType ("System", "Activator");
1760 new_constraint_attr_type = CoreLookupType (
1761 "System.Runtime.CompilerServices", "NewConstraintAttribute");
1763 generic_ienumerator_type = CoreLookupType (
1764 "System.Collections.Generic", "IEnumerator", 1);
1765 generic_ienumerable_type = CoreLookupType (
1766 "System.Collections.Generic", "IEnumerable", 1);
1767 generic_nullable_type = CoreLookupType (
1768 "System", "Nullable", 1);
1771 static void InitGenericCodeHelpers ()
1774 Type [] type_arg = { type_type };
1775 activator_create_instance = GetMethod (
1776 activator_type, "CreateInstance", type_arg);
1779 static Type CoreLookupType (string ns, string name, int arity)
1781 return CoreLookupType (ns, MemberName.MakeName (name, arity));
1784 public static void AddTypeParameter (Type t, TypeParameter tparam)
1786 if (!builder_to_type_param.Contains (t))
1787 builder_to_type_param.Add (t, tparam);
1790 public static TypeContainer LookupGenericTypeContainer (Type t)
1792 while (t.IsGenericInstance)
1793 t = t.GetGenericTypeDefinition ();
1795 return LookupTypeContainer (t);
1798 public static TypeParameter LookupTypeParameter (Type t)
1800 return (TypeParameter) builder_to_type_param [t];
1803 public static GenericConstraints GetTypeParameterConstraints (Type t)
1805 if (!t.IsGenericParameter)
1806 throw new InvalidOperationException ();
1808 TypeParameter tparam = LookupTypeParameter (t);
1810 return tparam.GenericConstraints;
1812 return new ReflectionConstraints (t);
1815 public static bool IsGeneric (Type t)
1817 DeclSpace ds = (DeclSpace) builder_to_declspace [t];
1819 return ds.IsGeneric;
1822 public static bool HasGenericArguments (Type t)
1824 return GetNumberOfTypeArguments (t) > 0;
1827 public static int GetNumberOfTypeArguments (Type t)
1829 DeclSpace tc = LookupDeclSpace (t);
1831 return tc.IsGeneric ? tc.CountTypeParameters : 0;
1833 return t.IsGenericType ? t.GetGenericArguments ().Length : 0;
1836 public static Type[] GetTypeArguments (Type t)
1838 DeclSpace tc = LookupDeclSpace (t);
1841 return Type.EmptyTypes;
1843 TypeParameter[] tparam = tc.TypeParameters;
1844 Type[] ret = new Type [tparam.Length];
1845 for (int i = 0; i < tparam.Length; i++) {
1846 ret [i] = tparam [i].Type;
1847 if (ret [i] == null)
1848 throw new InternalErrorException ();
1853 return t.GetGenericArguments ();
1857 // Whether `array' is an array of T and `enumerator' is `IEnumerable<T>'.
1858 // For instance "string[]" -> "IEnumerable<string>".
1860 public static bool IsIEnumerable (Type array, Type enumerator)
1862 if (!array.IsArray || !enumerator.IsGenericInstance)
1865 if (enumerator.GetGenericTypeDefinition () != generic_ienumerable_type)
1868 Type[] args = GetTypeArguments (enumerator);
1869 return args [0] == GetElementType (array);
1872 public static bool IsEqual (Type a, Type b)
1877 if ((a is TypeBuilder) && a.IsGenericTypeDefinition && b.IsGenericInstance) {
1879 // `a' is a generic type definition's TypeBuilder and `b' is a
1880 // generic instance of the same type.
1886 // void Test (Stack<T> stack) { }
1889 // The first argument of `Test' will be the generic instance
1890 // "Stack<!0>" - which is the same type than the "Stack" TypeBuilder.
1893 // We hit this via Closure.Filter() for gen-82.cs.
1895 if (a != b.GetGenericTypeDefinition ())
1898 Type[] aparams = a.GetGenericArguments ();
1899 Type[] bparams = b.GetGenericArguments ();
1901 if (aparams.Length != bparams.Length)
1904 for (int i = 0; i < aparams.Length; i++)
1905 if (!IsEqual (aparams [i], bparams [i]))
1911 if ((b is TypeBuilder) && b.IsGenericTypeDefinition && a.IsGenericInstance)
1912 return IsEqual (b, a);
1914 if (a.IsGenericParameter && b.IsGenericParameter) {
1915 if (a.DeclaringMethod != b.DeclaringMethod &&
1916 (a.DeclaringMethod == null || b.DeclaringMethod == null))
1918 return a.GenericParameterPosition == b.GenericParameterPosition;
1921 if (a.IsArray && b.IsArray) {
1922 if (a.GetArrayRank () != b.GetArrayRank ())
1924 return IsEqual (a.GetElementType (), b.GetElementType ());
1927 if (a.IsGenericInstance && b.IsGenericInstance) {
1928 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
1931 Type[] aargs = a.GetGenericArguments ();
1932 Type[] bargs = b.GetGenericArguments ();
1934 if (aargs.Length != bargs.Length)
1937 for (int i = 0; i < aargs.Length; i++) {
1938 if (!IsEqual (aargs [i], bargs [i]))
1949 /// Check whether `a' and `b' may become equal generic types.
1951 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_infered,
1952 Type[] method_infered)
1954 if (a.IsGenericParameter) {
1956 // If a is an array of a's type, they may never
1960 b = b.GetElementType ();
1966 // If b is a generic parameter or an actual type,
1967 // they may become equal:
1969 // class X<T,U> : I<T>, I<U>
1970 // class X<T> : I<T>, I<float>
1972 if (b.IsGenericParameter || !b.IsGenericInstance) {
1973 int pos = a.GenericParameterPosition;
1974 Type[] args = a.DeclaringMethod != null ? method_infered : class_infered;
1975 if (args [pos] == null) {
1980 return args [pos] == a;
1984 // We're now comparing a type parameter with a
1985 // generic instance. They may become equal unless
1986 // the type parameter appears anywhere in the
1987 // generic instance:
1989 // class X<T,U> : I<T>, I<X<U>>
1990 // -> error because you could instanciate it as
1993 // class X<T> : I<T>, I<X<T>> -> ok
1996 Type[] bargs = GetTypeArguments (b);
1997 for (int i = 0; i < bargs.Length; i++) {
1998 if (a.Equals (bargs [i]))
2005 if (b.IsGenericParameter)
2006 return MayBecomeEqualGenericTypes (b, a, class_infered, method_infered);
2009 // At this point, neither a nor b are a type parameter.
2011 // If one of them is a generic instance, let
2012 // MayBecomeEqualGenericInstances() compare them (if the
2013 // other one is not a generic instance, they can never
2017 if (a.IsGenericInstance || b.IsGenericInstance)
2018 return MayBecomeEqualGenericInstances (a, b, class_infered, method_infered);
2021 // If both of them are arrays.
2024 if (a.IsArray && b.IsArray) {
2025 if (a.GetArrayRank () != b.GetArrayRank ())
2028 a = a.GetElementType ();
2029 b = b.GetElementType ();
2031 return MayBecomeEqualGenericTypes (a, b, class_infered, method_infered);
2035 // Ok, two ordinary types.
2038 return a.Equals (b);
2042 // Checks whether two generic instances may become equal for some
2043 // particular instantiation (26.3.1).
2045 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
2046 Type[] class_infered,
2047 Type[] method_infered)
2049 if (!a.IsGenericInstance || !b.IsGenericInstance)
2051 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2054 return MayBecomeEqualGenericInstances (
2055 GetTypeArguments (a), GetTypeArguments (b), class_infered, method_infered);
2058 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
2059 Type[] class_infered,
2060 Type[] method_infered)
2062 if (aargs.Length != bargs.Length)
2065 for (int i = 0; i < aargs.Length; i++) {
2066 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_infered, method_infered))
2074 /// Check whether `type' and `parent' are both instantiations of the same
2075 /// generic type. Note that we do not check the type parameters here.
2077 public static bool IsInstantiationOfSameGenericType (Type type, Type parent)
2079 int tcount = GetNumberOfTypeArguments (type);
2080 int pcount = GetNumberOfTypeArguments (parent);
2082 if (type.IsGenericInstance)
2083 type = type.GetGenericTypeDefinition ();
2084 if (parent.IsGenericInstance)
2085 parent = parent.GetGenericTypeDefinition ();
2087 if (tcount != pcount)
2090 return type.Equals (parent);
2093 public static bool IsGenericMethod (MethodBase mb)
2095 if (mb.DeclaringType is TypeBuilder) {
2096 IMethodData method = (IMethodData) builder_to_method [mb];
2100 return method.GenericMethod != null;
2103 return mb.IsGenericMethodDefinition;
2110 static bool InferType (Type pt, Type at, Type[] infered)
2112 if (pt.IsGenericParameter && (pt.DeclaringMethod != null)) {
2113 int pos = pt.GenericParameterPosition;
2115 if (infered [pos] == null) {
2117 while (check.IsArray)
2118 check = check.GetElementType ();
2127 if (infered [pos] != at)
2133 if (!pt.ContainsGenericParameters) {
2134 if (at.ContainsGenericParameters)
2135 return InferType (at, pt, infered);
2142 (at.GetArrayRank () != pt.GetArrayRank ()))
2145 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2150 (pt.GetArrayRank () != at.GetArrayRank ()))
2153 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2156 if (pt.IsByRef && at.IsByRef)
2157 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2158 ArrayList list = new ArrayList ();
2159 if (at.IsGenericInstance)
2161 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
2164 list.AddRange (TypeManager.GetInterfaces (at));
2166 bool found_one = false;
2168 foreach (Type type in list) {
2169 if (!type.IsGenericInstance)
2172 Type[] infered_types = new Type [infered.Length];
2174 if (!InferGenericInstance (pt, type, infered_types))
2177 for (int i = 0; i < infered_types.Length; i++) {
2178 if (infered [i] == null) {
2179 infered [i] = infered_types [i];
2183 if (infered [i] != infered_types [i])
2193 static bool InferGenericInstance (Type pt, Type at, Type[] infered_types)
2195 Type[] at_args = at.GetGenericArguments ();
2196 Type[] pt_args = pt.GetGenericArguments ();
2198 if (at_args.Length != pt_args.Length)
2201 for (int i = 0; i < at_args.Length; i++) {
2202 if (!InferType (pt_args [i], at_args [i], infered_types))
2206 for (int i = 0; i < infered_types.Length; i++) {
2207 if (infered_types [i] == null)
2215 /// Type inference. Try to infer the type arguments from the params method
2216 /// `method', which is invoked with the arguments `arguments'. This is used
2217 /// when resolving an Invocation or a DelegateInvocation and the user
2218 /// did not explicitly specify type arguments.
2220 public static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
2221 ref MethodBase method)
2223 if ((arguments == null) || !TypeManager.IsGenericMethod (method))
2228 if (arguments == null)
2231 arg_count = arguments.Count;
2233 ParameterData pd = TypeManager.GetParameterData (method);
2235 int pd_count = pd.Count;
2240 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2243 if (pd_count - 1 > arg_count)
2246 if (pd_count == 1 && arg_count == 0)
2249 Type[] method_args = method.GetGenericArguments ();
2250 Type[] infered_types = new Type [method_args.Length];
2253 // If we have come this far, the case which
2254 // remains is when the number of parameters is
2255 // less than or equal to the argument count.
2257 for (int i = 0; i < pd_count - 1; ++i) {
2258 Argument a = (Argument) arguments [i];
2260 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2263 Type pt = pd.ParameterType (i);
2266 if (!InferType (pt, at, infered_types))
2270 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
2272 for (int i = pd_count - 1; i < arg_count; i++) {
2273 Argument a = (Argument) arguments [i];
2275 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2278 if (!InferType (element_type, a.Type, infered_types))
2282 for (int i = 0; i < infered_types.Length; i++)
2283 if (infered_types [i] == null)
2286 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2290 static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
2291 Type[] infered_types)
2293 if (infered_types == null)
2296 for (int i = 0; i < arg_types.Length; i++) {
2297 if (arg_types [i] == null)
2300 if (!InferType (param_types [i], arg_types [i], infered_types))
2304 for (int i = 0; i < infered_types.Length; i++)
2305 if (infered_types [i] == null)
2312 /// Type inference. Try to infer the type arguments from `method',
2313 /// which is invoked with the arguments `arguments'. This is used
2314 /// when resolving an Invocation or a DelegateInvocation and the user
2315 /// did not explicitly specify type arguments.
2317 public static bool InferTypeArguments (EmitContext ec, ArrayList arguments,
2318 ref MethodBase method)
2320 if (!TypeManager.IsGenericMethod (method))
2324 if (arguments != null)
2325 arg_count = arguments.Count;
2329 ParameterData pd = TypeManager.GetParameterData (method);
2330 if (arg_count != pd.Count)
2333 Type[] method_args = method.GetGenericArguments ();
2335 bool is_open = false;
2336 for (int i = 0; i < method_args.Length; i++) {
2337 if (method_args [i].IsGenericParameter) {
2345 Type[] infered_types = new Type [method_args.Length];
2347 Type[] param_types = new Type [pd.Count];
2348 Type[] arg_types = new Type [pd.Count];
2350 for (int i = 0; i < arg_count; i++) {
2351 param_types [i] = pd.ParameterType (i);
2353 Argument a = (Argument) arguments [i];
2354 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr) ||
2355 (a.Expr is AnonymousMethod))
2358 arg_types [i] = a.Type;
2361 if (!InferTypeArguments (param_types, arg_types, infered_types))
2364 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2371 public static bool InferTypeArguments (EmitContext ec, ParameterData apd,
2372 ref MethodBase method)
2374 if (!TypeManager.IsGenericMethod (method))
2377 ParameterData pd = TypeManager.GetParameterData (method);
2378 if (apd.Count != pd.Count)
2381 Type[] method_args = method.GetGenericArguments ();
2382 Type[] infered_types = new Type [method_args.Length];
2384 Type[] param_types = new Type [pd.Count];
2385 Type[] arg_types = new Type [pd.Count];
2387 for (int i = 0; i < apd.Count; i++) {
2388 param_types [i] = pd.ParameterType (i);
2389 arg_types [i] = apd.ParameterType (i);
2392 if (!InferTypeArguments (param_types, arg_types, infered_types))
2395 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2399 public static bool IsNullableType (Type t)
2401 if (!t.IsGenericInstance)
2404 Type gt = t.GetGenericTypeDefinition ();
2405 return gt == generic_nullable_type;
2409 public abstract class Nullable
2411 protected sealed class NullableInfo
2413 public readonly Type Type;
2414 public readonly Type UnderlyingType;
2415 public readonly MethodInfo HasValue;
2416 public readonly MethodInfo Value;
2417 public readonly ConstructorInfo Constructor;
2419 public NullableInfo (Type type)
2422 UnderlyingType = TypeManager.GetTypeArguments (type) [0];
2424 PropertyInfo has_value_pi = type.GetProperty ("HasValue");
2425 PropertyInfo value_pi = type.GetProperty ("Value");
2427 HasValue = has_value_pi.GetGetMethod (false);
2428 Value = value_pi.GetGetMethod (false);
2429 Constructor = type.GetConstructor (new Type[] { UnderlyingType });
2433 protected class Unwrap : Expression, IMemoryLocation, IAssignMethod
2438 LocalTemporary temp;
2441 public Unwrap (Expression expr, Location loc)
2447 public override Expression DoResolve (EmitContext ec)
2449 expr = expr.Resolve (ec);
2453 if (!(expr is IMemoryLocation))
2454 temp = new LocalTemporary (ec, expr.Type);
2456 info = new NullableInfo (expr.Type);
2457 type = info.UnderlyingType;
2458 eclass = expr.eclass;
2462 public override void Emit (EmitContext ec)
2464 AddressOf (ec, AddressOp.LoadStore);
2465 ec.ig.EmitCall (OpCodes.Call, info.Value, null);
2468 public void EmitCheck (EmitContext ec)
2470 AddressOf (ec, AddressOp.LoadStore);
2471 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
2474 void create_temp (EmitContext ec)
2476 if ((temp != null) && !has_temp) {
2483 public void AddressOf (EmitContext ec, AddressOp mode)
2487 temp.AddressOf (ec, AddressOp.LoadStore);
2489 ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
2492 public void Emit (EmitContext ec, bool leave_copy)
2505 public void EmitAssign (EmitContext ec, Expression source,
2506 bool leave_copy, bool prepare_for_load)
2509 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2512 ec.ig.Emit (OpCodes.Dup);
2514 Expression empty = new EmptyExpression (expr.Type);
2515 ((IAssignMethod) expr).EmitAssign (ec, empty, false, prepare_for_load);
2519 protected class Wrap : Expression
2524 public Wrap (Expression expr, Location loc)
2530 public override Expression DoResolve (EmitContext ec)
2532 expr = expr.Resolve (ec);
2536 TypeExpr target_type = new NullableType (expr.Type, loc);
2537 target_type = target_type.ResolveAsTypeTerminal (ec);
2538 if (target_type == null)
2541 type = target_type.Type;
2542 info = new NullableInfo (type);
2543 eclass = ExprClass.Value;
2547 public override void Emit (EmitContext ec)
2550 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2554 public class NullableLiteral : Expression, IMemoryLocation {
2555 public NullableLiteral (Type target_type, Location loc)
2557 this.type = target_type;
2560 eclass = ExprClass.Value;
2563 public override Expression DoResolve (EmitContext ec)
2568 public override void Emit (EmitContext ec)
2570 LocalTemporary value_target = new LocalTemporary (ec, type);
2572 value_target.AddressOf (ec, AddressOp.Store);
2573 ec.ig.Emit (OpCodes.Initobj, type);
2574 value_target.Emit (ec);
2577 public void AddressOf (EmitContext ec, AddressOp Mode)
2579 LocalTemporary value_target = new LocalTemporary (ec, type);
2581 value_target.AddressOf (ec, AddressOp.Store);
2582 ec.ig.Emit (OpCodes.Initobj, type);
2583 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
2587 public abstract class Lifted : Expression, IMemoryLocation
2589 Expression expr, underlying, wrap, null_value;
2592 protected Lifted (Expression expr, Location loc)
2598 public override Expression DoResolve (EmitContext ec)
2600 expr = expr.Resolve (ec);
2604 unwrap = (Unwrap) new Unwrap (expr, loc).Resolve (ec);
2608 underlying = ResolveUnderlying (unwrap, ec);
2609 if (underlying == null)
2612 wrap = new Wrap (underlying, loc).Resolve (ec);
2616 null_value = new NullableLiteral (wrap.Type, loc).Resolve (ec);
2617 if (null_value == null)
2621 eclass = ExprClass.Value;
2625 protected abstract Expression ResolveUnderlying (Expression unwrap, EmitContext ec);
2627 public override void Emit (EmitContext ec)
2629 ILGenerator ig = ec.ig;
2630 Label is_null_label = ig.DefineLabel ();
2631 Label end_label = ig.DefineLabel ();
2633 unwrap.EmitCheck (ec);
2634 ig.Emit (OpCodes.Brfalse, is_null_label);
2637 ig.Emit (OpCodes.Br, end_label);
2639 ig.MarkLabel (is_null_label);
2640 null_value.Emit (ec);
2642 ig.MarkLabel (end_label);
2645 public void AddressOf (EmitContext ec, AddressOp mode)
2647 unwrap.AddressOf (ec, mode);
2651 public class LiftedConversion : Lifted
2653 public readonly bool IsUser;
2654 public readonly bool IsExplicit;
2655 public readonly Type TargetType;
2657 public LiftedConversion (Expression expr, Type target_type, bool is_user,
2658 bool is_explicit, Location loc)
2661 this.IsUser = is_user;
2662 this.IsExplicit = is_explicit;
2663 this.TargetType = target_type;
2666 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2668 Type type = TypeManager.GetTypeArguments (TargetType) [0];
2671 return Convert.UserDefinedConversion (ec, unwrap, type, loc, IsExplicit);
2674 return Convert.ExplicitConversion (ec, unwrap, type, loc);
2676 return Convert.ImplicitConversion (ec, unwrap, type, loc);
2681 public class LiftedUnaryOperator : Lifted
2683 public readonly Unary.Operator Oper;
2685 public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
2691 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2693 return new Unary (Oper, unwrap, loc);
2697 public class LiftedConditional : Lifted
2699 Expression true_expr, false_expr;
2701 public LiftedConditional (Expression expr, Expression true_expr, Expression false_expr,
2705 this.true_expr = true_expr;
2706 this.false_expr = false_expr;
2709 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2711 return new Conditional (unwrap, true_expr, false_expr);
2715 public class LiftedBinaryOperator : Expression
2717 public readonly Binary.Operator Oper;
2719 Expression left, right, underlying, null_value, bool_wrap;
2720 Unwrap left_unwrap, right_unwrap;
2721 bool is_equality, is_comparision, is_boolean;
2723 public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
2732 public override Expression DoResolve (EmitContext ec)
2734 if (TypeManager.IsNullableType (left.Type)) {
2735 left_unwrap = new Unwrap (left, loc);
2736 left = left_unwrap.Resolve (ec);
2741 if (TypeManager.IsNullableType (right.Type)) {
2742 right_unwrap = new Unwrap (right, loc);
2743 right = right_unwrap.Resolve (ec);
2748 if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr) ||
2749 (Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr)) &&
2750 ((left.Type == TypeManager.bool_type) && (right.Type == TypeManager.bool_type))) {
2751 Expression empty = new EmptyExpression (TypeManager.bool_type);
2752 bool_wrap = new Wrap (empty, loc).Resolve (ec);
2753 null_value = new NullableLiteral (bool_wrap.Type, loc).Resolve (ec);
2755 type = bool_wrap.Type;
2757 } else if ((Oper == Binary.Operator.Equality) || (Oper == Binary.Operator.Inequality)) {
2758 if (!(left is NullLiteral) && !(right is NullLiteral)) {
2759 underlying = new Binary (Oper, left, right).Resolve (ec);
2760 if (underlying == null)
2764 type = TypeManager.bool_type;
2766 } else if ((Oper == Binary.Operator.LessThan) ||
2767 (Oper == Binary.Operator.GreaterThan) ||
2768 (Oper == Binary.Operator.LessThanOrEqual) ||
2769 (Oper == Binary.Operator.GreaterThanOrEqual)) {
2770 underlying = new Binary (Oper, left, right).Resolve (ec);
2771 if (underlying == null)
2774 type = TypeManager.bool_type;
2775 is_comparision = true;
2777 underlying = new Binary (Oper, left, right).Resolve (ec);
2778 if (underlying == null)
2781 underlying = new Wrap (underlying, loc).Resolve (ec);
2782 if (underlying == null)
2785 type = underlying.Type;
2786 null_value = new NullableLiteral (type, loc).Resolve (ec);
2789 eclass = ExprClass.Value;
2793 void EmitBoolean (EmitContext ec)
2795 ILGenerator ig = ec.ig;
2797 Label left_is_null_label = ig.DefineLabel ();
2798 Label right_is_null_label = ig.DefineLabel ();
2799 Label is_null_label = ig.DefineLabel ();
2800 Label wrap_label = ig.DefineLabel ();
2801 Label end_label = ig.DefineLabel ();
2803 if (left_unwrap != null) {
2804 left_unwrap.EmitCheck (ec);
2805 ig.Emit (OpCodes.Brfalse, left_is_null_label);
2809 ig.Emit (OpCodes.Dup);
2810 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
2811 ig.Emit (OpCodes.Brtrue, wrap_label);
2813 ig.Emit (OpCodes.Brfalse, wrap_label);
2815 if (right_unwrap != null) {
2816 right_unwrap.EmitCheck (ec);
2817 ig.Emit (OpCodes.Brfalse, right_is_null_label);
2820 if ((Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr))
2821 ig.Emit (OpCodes.Pop);
2824 if (Oper == Binary.Operator.BitwiseOr)
2825 ig.Emit (OpCodes.Or);
2826 else if (Oper == Binary.Operator.BitwiseAnd)
2827 ig.Emit (OpCodes.And);
2828 ig.Emit (OpCodes.Br, wrap_label);
2830 ig.MarkLabel (left_is_null_label);
2831 if (right_unwrap != null) {
2832 right_unwrap.EmitCheck (ec);
2833 ig.Emit (OpCodes.Brfalse, is_null_label);
2837 ig.Emit (OpCodes.Dup);
2838 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
2839 ig.Emit (OpCodes.Brtrue, wrap_label);
2841 ig.Emit (OpCodes.Brfalse, wrap_label);
2843 ig.MarkLabel (right_is_null_label);
2844 ig.Emit (OpCodes.Pop);
2845 ig.MarkLabel (is_null_label);
2846 null_value.Emit (ec);
2847 ig.Emit (OpCodes.Br, end_label);
2849 ig.MarkLabel (wrap_label);
2850 ig.Emit (OpCodes.Nop);
2851 bool_wrap.Emit (ec);
2852 ig.Emit (OpCodes.Nop);
2854 ig.MarkLabel (end_label);
2857 void EmitEquality (EmitContext ec)
2859 ILGenerator ig = ec.ig;
2861 Label left_not_null_label = ig.DefineLabel ();
2862 Label false_label = ig.DefineLabel ();
2863 Label true_label = ig.DefineLabel ();
2864 Label end_label = ig.DefineLabel ();
2866 if (left_unwrap != null) {
2867 left_unwrap.EmitCheck (ec);
2868 if (right is NullLiteral) {
2869 if (Oper == Binary.Operator.Equality)
2870 ig.Emit (OpCodes.Brfalse, true_label);
2872 ig.Emit (OpCodes.Brfalse, false_label);
2873 } else if (right_unwrap != null) {
2874 ig.Emit (OpCodes.Dup);
2875 ig.Emit (OpCodes.Brtrue, left_not_null_label);
2876 right_unwrap.EmitCheck (ec);
2877 ig.Emit (OpCodes.Ceq);
2878 if (Oper == Binary.Operator.Inequality) {
2879 ig.Emit (OpCodes.Ldc_I4_0);
2880 ig.Emit (OpCodes.Ceq);
2882 ig.Emit (OpCodes.Br, end_label);
2884 ig.MarkLabel (left_not_null_label);
2885 ig.Emit (OpCodes.Pop);
2887 if (Oper == Binary.Operator.Equality)
2888 ig.Emit (OpCodes.Brfalse, false_label);
2890 ig.Emit (OpCodes.Brfalse, true_label);
2894 if (right_unwrap != null) {
2895 right_unwrap.EmitCheck (ec);
2896 if (left is NullLiteral) {
2897 if (Oper == Binary.Operator.Equality)
2898 ig.Emit (OpCodes.Brfalse, true_label);
2900 ig.Emit (OpCodes.Brfalse, false_label);
2902 if (Oper == Binary.Operator.Equality)
2903 ig.Emit (OpCodes.Brfalse, false_label);
2905 ig.Emit (OpCodes.Brfalse, true_label);
2909 bool left_is_null = left is NullLiteral;
2910 bool right_is_null = right is NullLiteral;
2911 if (left_is_null || right_is_null) {
2912 if (((Oper == Binary.Operator.Equality) && (left_is_null == right_is_null)) ||
2913 ((Oper == Binary.Operator.Inequality) && (left_is_null != right_is_null)))
2914 ig.Emit (OpCodes.Br, true_label);
2916 ig.Emit (OpCodes.Br, false_label);
2918 underlying.Emit (ec);
2919 ig.Emit (OpCodes.Br, end_label);
2922 ig.MarkLabel (false_label);
2923 ig.Emit (OpCodes.Ldc_I4_0);
2924 ig.Emit (OpCodes.Br, end_label);
2926 ig.MarkLabel (true_label);
2927 ig.Emit (OpCodes.Ldc_I4_1);
2929 ig.MarkLabel (end_label);
2932 void EmitComparision (EmitContext ec)
2934 ILGenerator ig = ec.ig;
2936 Label is_null_label = ig.DefineLabel ();
2937 Label end_label = ig.DefineLabel ();
2939 if (left_unwrap != null) {
2940 left_unwrap.EmitCheck (ec);
2941 ig.Emit (OpCodes.Brfalse, is_null_label);
2944 if (right_unwrap != null) {
2945 right_unwrap.EmitCheck (ec);
2946 ig.Emit (OpCodes.Brfalse, is_null_label);
2949 underlying.Emit (ec);
2950 ig.Emit (OpCodes.Br, end_label);
2952 ig.MarkLabel (is_null_label);
2953 ig.Emit (OpCodes.Ldc_I4_0);
2955 ig.MarkLabel (end_label);
2958 public override void Emit (EmitContext ec)
2963 } else if (is_equality) {
2966 } else if (is_comparision) {
2967 EmitComparision (ec);
2971 ILGenerator ig = ec.ig;
2973 Label is_null_label = ig.DefineLabel ();
2974 Label end_label = ig.DefineLabel ();
2976 if (left_unwrap != null) {
2977 left_unwrap.EmitCheck (ec);
2978 ig.Emit (OpCodes.Brfalse, is_null_label);
2981 if (right_unwrap != null) {
2982 right_unwrap.EmitCheck (ec);
2983 ig.Emit (OpCodes.Brfalse, is_null_label);
2986 underlying.Emit (ec);
2987 ig.Emit (OpCodes.Br, end_label);
2989 ig.MarkLabel (is_null_label);
2990 null_value.Emit (ec);
2992 ig.MarkLabel (end_label);
2996 public class OperatorTrueOrFalse : Expression
2998 public readonly bool IsTrue;
3003 public OperatorTrueOrFalse (Expression expr, bool is_true, Location loc)
3005 this.IsTrue = is_true;
3010 public override Expression DoResolve (EmitContext ec)
3012 unwrap = new Unwrap (expr, loc);
3013 expr = unwrap.Resolve (ec);
3017 if (unwrap.Type != TypeManager.bool_type)
3020 type = TypeManager.bool_type;
3021 eclass = ExprClass.Value;
3025 public override void Emit (EmitContext ec)
3027 ILGenerator ig = ec.ig;
3029 Label is_null_label = ig.DefineLabel ();
3030 Label end_label = ig.DefineLabel ();
3032 unwrap.EmitCheck (ec);
3033 ig.Emit (OpCodes.Brfalse, is_null_label);
3037 ig.Emit (OpCodes.Ldc_I4_0);
3038 ig.Emit (OpCodes.Ceq);
3040 ig.Emit (OpCodes.Br, end_label);
3042 ig.MarkLabel (is_null_label);
3043 ig.Emit (OpCodes.Ldc_I4_0);
3045 ig.MarkLabel (end_label);
3049 public class NullCoalescingOperator : Expression
3051 Expression left, right;
3055 public NullCoalescingOperator (Expression left, Expression right, Location loc)
3061 eclass = ExprClass.Value;
3064 public override Expression DoResolve (EmitContext ec)
3069 left = left.Resolve (ec);
3073 right = right.Resolve (ec);
3077 Type ltype = left.Type, rtype = right.Type;
3079 if (!TypeManager.IsNullableType (ltype) && ltype.IsValueType) {
3080 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3084 if (TypeManager.IsNullableType (ltype)) {
3085 NullableInfo info = new NullableInfo (ltype);
3087 unwrap = (Unwrap) new Unwrap (left, loc).Resolve (ec);
3091 expr = Convert.ImplicitConversion (ec, right, info.UnderlyingType, loc);
3099 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
3105 if (unwrap != null) {
3106 expr = Convert.ImplicitConversion (ec, unwrap, rtype, loc);
3115 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3119 public override void Emit (EmitContext ec)
3121 ILGenerator ig = ec.ig;
3123 Label is_null_label = ig.DefineLabel ();
3124 Label end_label = ig.DefineLabel ();
3126 if (unwrap != null) {
3127 unwrap.EmitCheck (ec);
3128 ig.Emit (OpCodes.Brfalse, is_null_label);
3131 ig.Emit (OpCodes.Br, end_label);
3133 ig.MarkLabel (is_null_label);
3136 ig.MarkLabel (end_label);
3139 ig.Emit (OpCodes.Dup);
3140 ig.Emit (OpCodes.Brtrue, end_label);
3142 ig.MarkLabel (is_null_label);
3144 ig.Emit (OpCodes.Pop);
3147 ig.MarkLabel (end_label);
3152 public class LiftedUnaryMutator : ExpressionStatement
3154 public readonly UnaryMutator.Mode Mode;
3155 Expression expr, null_value;
3156 UnaryMutator underlying;
3159 public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
3165 eclass = ExprClass.Value;
3168 public override Expression DoResolve (EmitContext ec)
3170 expr = expr.Resolve (ec);
3174 unwrap = (Unwrap) new Unwrap (expr, loc).Resolve (ec);
3178 underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
3179 if (underlying == null)
3182 null_value = new NullableLiteral (expr.Type, loc).Resolve (ec);
3183 if (null_value == null)
3190 void DoEmit (EmitContext ec, bool is_expr)
3192 ILGenerator ig = ec.ig;
3193 Label is_null_label = ig.DefineLabel ();
3194 Label end_label = ig.DefineLabel ();
3196 unwrap.EmitCheck (ec);
3197 ig.Emit (OpCodes.Brfalse, is_null_label);
3200 underlying.Emit (ec);
3202 underlying.EmitStatement (ec);
3203 ig.Emit (OpCodes.Br, end_label);
3205 ig.MarkLabel (is_null_label);
3207 null_value.Emit (ec);
3209 ig.MarkLabel (end_label);
3212 public override void Emit (EmitContext ec)
3217 public override void EmitStatement (EmitContext ec)