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;
202 FullNamedExpression fn = ((Expression) obj).ResolveAsTypeStep (ec);
207 ConstructedType cexpr = fn as ConstructedType;
209 if (!cexpr.ResolveConstructedType (ec))
214 expr = fn.ResolveAsTypeTerminal (ec);
219 TypeParameterExpr texpr = expr as TypeParameterExpr;
221 type_param_constraints.Add (expr);
222 else if (expr.IsInterface)
223 iface_constraints.Add (expr);
224 else if (class_constraint != null) {
225 Report.Error (406, loc,
226 "`{0}': the class constraint for `{1}' " +
227 "must come before any other constraints.",
230 } else if (HasReferenceTypeConstraint || HasValueTypeConstraint) {
231 Report.Error (450, loc, "`{0}': cannot specify both " +
232 "a constraint class and the `class' " +
233 "or `struct' constraint.", expr.Name);
236 class_constraint = expr;
244 bool CheckTypeParameterConstraints (TypeParameter tparam, Hashtable seen)
246 seen.Add (tparam, true);
248 Constraints constraints = tparam.Constraints;
249 if (constraints == null)
252 if (constraints.HasValueTypeConstraint) {
253 Report.Error (456, loc, "Type parameter `{0}' has " +
254 "the `struct' constraint, so it cannot " +
255 "be used as a constraint for `{1}'",
260 if (constraints.type_param_constraints == null)
263 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
264 if (seen.Contains (expr.TypeParameter)) {
265 Report.Error (454, loc, "Circular constraint " +
266 "dependency involving `{0}' and `{1}'",
267 tparam.Name, expr.Name);
271 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
278 public bool ResolveTypes (EmitContext ec)
280 if (effective_base_type != null)
283 foreach (object obj in constraints) {
284 ConstructedType cexpr = obj as ConstructedType;
288 if (!cexpr.CheckConstraints (ec))
292 foreach (TypeParameterExpr expr in type_param_constraints) {
293 Hashtable seen = new Hashtable ();
294 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
298 ArrayList list = new ArrayList ();
300 foreach (TypeExpr iface_constraint in iface_constraints) {
301 foreach (Type type in list) {
302 if (!type.Equals (iface_constraint.Type))
305 Report.Error (405, loc,
306 "Duplicate constraint `{0}' for type " +
307 "parameter `{1}'.", iface_constraint.Type,
312 TypeExpr te = iface_constraint.ResolveAsTypeTerminal (ec);
319 foreach (TypeParameterExpr expr in type_param_constraints) {
320 foreach (Type type in list) {
321 if (!type.Equals (expr.Type))
324 Report.Error (405, loc,
325 "Duplicate constraint `{0}' for type " +
326 "parameter `{1}'.", expr.Type, name);
330 list.Add (expr.Type);
333 iface_constraint_types = new Type [list.Count];
334 list.CopyTo (iface_constraint_types, 0);
336 if (class_constraint != null) {
337 TypeExpr te = class_constraint.ResolveAsTypeTerminal (ec);
341 class_constraint_type = te.Type;
342 if (class_constraint_type == null)
345 if (class_constraint_type.IsSealed) {
346 Report.Error (701, loc,
347 "`{0}' is not a valid bound. Bounds " +
348 "must be interfaces or non sealed " +
349 "classes", class_constraint_type);
353 if ((class_constraint_type == TypeManager.array_type) ||
354 (class_constraint_type == TypeManager.delegate_type) ||
355 (class_constraint_type == TypeManager.enum_type) ||
356 (class_constraint_type == TypeManager.value_type) ||
357 (class_constraint_type == TypeManager.object_type)) {
358 Report.Error (702, loc,
359 "Bound cannot be special class `{0}'",
360 class_constraint_type);
365 if (class_constraint_type != null)
366 effective_base_type = class_constraint_type;
367 else if (HasValueTypeConstraint)
368 effective_base_type = TypeManager.value_type;
370 effective_base_type = TypeManager.object_type;
375 public bool CheckDependencies (EmitContext ec)
377 foreach (TypeParameterExpr expr in type_param_constraints) {
378 if (!CheckDependencies (expr.TypeParameter, ec))
385 bool CheckDependencies (TypeParameter tparam, EmitContext ec)
387 Constraints constraints = tparam.Constraints;
388 if (constraints == null)
391 if (HasValueTypeConstraint && constraints.HasClassConstraint) {
392 Report.Error (455, loc, "Type parameter `{0}' inherits " +
393 "conflicting constraints `{1}' and `{2}'",
394 name, constraints.ClassConstraint,
399 if (HasClassConstraint && constraints.HasClassConstraint) {
400 Type t1 = ClassConstraint;
401 TypeExpr e1 = class_constraint;
402 Type t2 = constraints.ClassConstraint;
403 TypeExpr e2 = constraints.class_constraint;
405 if (!Convert.ImplicitReferenceConversionExists (ec, e1, t2) &&
406 !Convert.ImplicitReferenceConversionExists (ec, e2, t1)) {
407 Report.Error (455, loc,
408 "Type parameter `{0}' inherits " +
409 "conflicting constraints `{1}' and `{2}'",
415 if (constraints.type_param_constraints == null)
418 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
419 if (!CheckDependencies (expr.TypeParameter, ec))
426 public void Define (GenericTypeParameterBuilder type)
428 type.SetGenericParameterAttributes (attrs);
431 public override GenericParameterAttributes Attributes {
432 get { return attrs; }
435 public override bool HasClassConstraint {
436 get { return class_constraint != null; }
439 public override Type ClassConstraint {
440 get { return class_constraint_type; }
443 public override Type[] InterfaceConstraints {
444 get { return iface_constraint_types; }
447 public override Type EffectiveBaseClass {
448 get { return effective_base_type; }
451 internal bool IsSubclassOf (Type t)
453 if ((class_constraint_type != null) &&
454 class_constraint_type.IsSubclassOf (t))
457 if (iface_constraint_types == null)
460 foreach (Type iface in iface_constraint_types) {
461 if (TypeManager.IsSubclassOf (iface, t))
468 public bool CheckInterfaceMethod (EmitContext ec, GenericConstraints gc)
470 if (gc.Attributes != attrs)
473 if (HasClassConstraint != gc.HasClassConstraint)
475 if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
478 int gc_icount = gc.InterfaceConstraints != null ?
479 gc.InterfaceConstraints.Length : 0;
480 int icount = InterfaceConstraints != null ?
481 InterfaceConstraints.Length : 0;
483 if (gc_icount != icount)
486 foreach (Type iface in gc.InterfaceConstraints) {
488 foreach (Type check in InterfaceConstraints) {
489 if (TypeManager.IsEqual (iface, check)) {
504 // This type represents a generic type parameter
506 public class TypeParameter : MemberCore, IMemberContainer {
508 GenericConstraints gc;
509 Constraints constraints;
511 GenericTypeParameterBuilder type;
513 public TypeParameter (TypeContainer parent, string name,
514 Constraints constraints, Location loc)
515 : base (parent, new MemberName (name), null, loc)
518 this.constraints = constraints;
522 public GenericConstraints GenericConstraints {
524 return gc != null ? gc : constraints;
528 public Constraints Constraints {
534 public bool HasConstructorConstraint {
536 if (constraints != null)
537 return constraints.HasConstructorConstraint;
549 public bool Resolve (DeclSpace ds)
551 if (constraints != null) {
552 if (!constraints.Resolve (ds.EmitContext)) {
561 public void Define (GenericTypeParameterBuilder type)
563 if (this.type != null)
564 throw new InvalidOperationException ();
567 TypeManager.AddTypeParameter (type, this);
570 public void DefineConstraints ()
572 if (constraints != null)
573 constraints.Define (type);
576 public bool ResolveType (EmitContext ec)
578 if (constraints != null) {
579 if (!constraints.ResolveTypes (ec)) {
588 public bool DefineType (EmitContext ec)
590 return DefineType (ec, null, null, false);
593 public bool DefineType (EmitContext ec, MethodBuilder builder,
594 MethodInfo implementing, bool is_override)
596 if (!ResolveType (ec))
599 if (implementing != null) {
600 if (is_override && (constraints != null)) {
602 460, loc, "Constraints for override and " +
603 "explicit interface implementation methods " +
604 "are inherited from the base method so they " +
605 "cannot be specified directly");
609 MethodBase mb = implementing;
610 if (mb.Mono_IsInflatedMethod)
611 mb = mb.GetGenericMethodDefinition ();
613 int pos = type.GenericParameterPosition;
614 ParameterData pd = TypeManager.GetParameterData (mb);
615 GenericConstraints temp_gc = pd.GenericConstraints (pos);
616 Type mparam = mb.GetGenericArguments () [pos];
619 gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
620 else if (constraints != null)
621 gc = new InflatedConstraints (constraints, implementing.DeclaringType);
624 if (constraints != null) {
627 else if (!constraints.CheckInterfaceMethod (ec, gc))
630 if (!is_override && (temp_gc != null))
635 Report.SymbolRelatedToPreviousError (implementing);
638 425, loc, "The constraints for type " +
639 "parameter `{0}' of method `{1}' must match " +
640 "the constraints for type parameter `{2}' " +
641 "of interface method `{3}'. Consider using " +
642 "an explicit interface implementation instead",
643 Name, TypeManager.CSharpSignature (builder),
644 mparam, TypeManager.CSharpSignature (mb));
648 gc = (GenericConstraints) constraints;
654 if (gc.HasClassConstraint)
655 type.SetBaseTypeConstraint (gc.ClassConstraint);
657 type.SetInterfaceConstraints (gc.InterfaceConstraints);
658 TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
663 public bool CheckDependencies (EmitContext ec)
665 if (constraints != null)
666 return constraints.CheckDependencies (ec);
671 public bool UpdateConstraints (EmitContext ec, Constraints new_constraints)
674 // We're used in partial generic type definitions.
675 // If `check' is false, we just encountered the first ClassPart which has
676 // constraints - they become our "real" constraints.
677 // Otherwise we're called after the type parameters have already been defined
678 // and check whether the constraints are the same in all parts.
681 throw new InvalidOperationException ();
683 if (constraints == null) {
684 new_constraints = constraints;
686 } else if (new_constraints == null)
689 if (!new_constraints.Resolve (ec))
691 if (!new_constraints.ResolveTypes (ec))
694 return constraints.CheckInterfaceMethod (ec, new_constraints);
697 public override string DocCommentHeader {
699 throw new InvalidOperationException (
700 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
708 public override bool Define ()
713 protected override void VerifyObsoleteAttribute ()
716 public override void ApplyAttributeBuilder (Attribute a,
717 CustomAttributeBuilder cb)
720 public override AttributeTargets AttributeTargets {
722 return (AttributeTargets) 0;
726 public override string[] ValidAttributeTargets {
728 return new string [0];
736 string IMemberContainer.Name {
740 MemberCache IMemberContainer.BaseCache {
744 bool IMemberContainer.IsInterface {
748 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
750 return FindMembers (mt, bf, null, null);
753 MemberCache IMemberContainer.MemberCache {
757 public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
758 MemberFilter filter, object criteria)
760 if (constraints == null)
761 return MemberList.Empty;
763 ArrayList members = new ArrayList ();
765 GenericConstraints gc = (GenericConstraints) constraints;
767 if (gc.HasClassConstraint) {
768 MemberList list = TypeManager.FindMembers (
769 gc.ClassConstraint, mt, bf, filter, criteria);
771 members.AddRange (list);
774 foreach (Type t in gc.InterfaceConstraints) {
775 MemberList list = TypeManager.FindMembers (
776 t, mt, bf, filter, criteria);
778 members.AddRange (list);
781 return new MemberList (members);
784 public bool IsSubclassOf (Type t)
789 if (constraints != null)
790 return constraints.IsSubclassOf (t);
795 public override string ToString ()
797 return "TypeParameter[" + name + "]";
800 protected class InflatedConstraints : GenericConstraints
802 GenericConstraints gc;
804 Type class_constraint;
805 Type[] iface_constraints;
809 public InflatedConstraints (GenericConstraints gc, Type declaring)
812 this.declaring = declaring;
814 dargs = TypeManager.GetTypeArguments (declaring);
816 ArrayList list = new ArrayList ();
817 if (gc.HasClassConstraint)
818 list.Add (inflate (gc.ClassConstraint));
819 foreach (Type iface in gc.InterfaceConstraints)
820 list.Add (inflate (iface));
822 bool has_class_constr = false;
823 if (list.Count > 0) {
824 Type first = (Type) list [0];
825 has_class_constr = !first.IsInterface && !first.IsGenericParameter;
828 if ((list.Count > 0) && has_class_constr) {
829 class_constraint = (Type) list [0];
830 iface_constraints = new Type [list.Count - 1];
831 list.CopyTo (1, iface_constraints, 0, list.Count - 1);
833 iface_constraints = new Type [list.Count];
834 list.CopyTo (iface_constraints, 0);
837 if (HasValueTypeConstraint)
838 base_type = TypeManager.value_type;
839 else if (class_constraint != null)
840 base_type = class_constraint;
842 base_type = TypeManager.object_type;
845 Type inflate (Type t)
849 if (t.IsGenericParameter)
850 return dargs [t.GenericParameterPosition];
851 if (t.IsGenericInstance) {
852 t = t.GetGenericTypeDefinition ();
853 t = t.BindGenericParameters (dargs);
859 public override GenericParameterAttributes Attributes {
860 get { return gc.Attributes; }
863 public override Type ClassConstraint {
864 get { return class_constraint; }
867 public override Type EffectiveBaseClass {
868 get { return base_type; }
871 public override Type[] InterfaceConstraints {
872 get { return iface_constraints; }
878 // This type represents a generic type parameter reference.
880 // These expressions are born in a fully resolved state.
882 public class TypeParameterExpr : TypeExpr {
883 TypeParameter type_parameter;
885 public override string Name {
887 return type_parameter.Name;
891 public override string FullName {
893 return type_parameter.Name;
897 public TypeParameter TypeParameter {
899 return type_parameter;
903 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
905 this.type_parameter = type_parameter;
909 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
911 type = type_parameter.Type;
916 public override bool IsInterface {
917 get { return false; }
920 public override bool CheckAccessLevel (DeclSpace ds)
925 public void Error_CannotUseAsUnmanagedType (Location loc)
927 Report.Error (-203, loc, "Can not use type parameter as unamanged type");
931 public class TypeArguments {
932 public readonly Location Location;
939 public TypeArguments (Location loc)
941 args = new ArrayList ();
945 public TypeArguments (int dimension, Location loc)
947 this.dimension = dimension;
951 public void Add (Expression type)
954 throw new InvalidOperationException ();
959 public void Add (TypeArguments new_args)
962 throw new InvalidOperationException ();
964 args.AddRange (new_args.args);
967 public string[] GetDeclarations ()
969 string[] ret = new string [args.Count];
970 for (int i = 0; i < args.Count; i++) {
971 SimpleName sn = args [i] as SimpleName;
977 Report.Error (81, Location, "Type parameter declaration " +
978 "must be an identifier not a type");
984 public Type[] Arguments {
990 public bool HasTypeArguments {
992 return has_type_args;
1005 public bool IsUnbound {
1007 return dimension > 0;
1011 public override string ToString ()
1013 StringBuilder s = new StringBuilder ();
1016 for (int i = 0; i < count; i++){
1018 // FIXME: Use TypeManager.CSharpname once we have the type
1021 s.Append (args [i].ToString ());
1025 return s.ToString ();
1028 public bool Resolve (EmitContext ec)
1030 int count = args.Count;
1033 atypes = new Type [count];
1035 for (int i = 0; i < count; i++){
1036 TypeExpr te = ((Expression) args [i]).ResolveAsTypeTerminal (ec);
1041 if (te is TypeParameterExpr)
1042 has_type_args = true;
1044 if (te.Type.IsPointer) {
1045 Report.Error (306, Location, "The type `{0}' may not be used " +
1046 "as a type argument.", TypeManager.CSharpName (te.Type));
1050 atypes [i] = te.Type;
1056 public class ConstructedType : TypeExpr {
1058 FullNamedExpression name;
1060 Type[] gen_params, atypes;
1063 public ConstructedType (FullNamedExpression fname, TypeArguments args, Location l)
1069 eclass = ExprClass.Type;
1070 full_name = name + "<" + args.ToString () + ">";
1073 protected ConstructedType (TypeArguments args, Location l)
1078 eclass = ExprClass.Type;
1081 protected ConstructedType (TypeParameter[] type_params, Location l)
1085 args = new TypeArguments (l);
1086 foreach (TypeParameter type_param in type_params)
1087 args.Add (new TypeParameterExpr (type_param, l));
1089 eclass = ExprClass.Type;
1092 public ConstructedType (Type t, TypeParameter[] type_params, Location l)
1093 : this (type_params, l)
1095 gt = t.GetGenericTypeDefinition ();
1097 this.name = new TypeExpression (gt, l);
1098 full_name = gt.FullName + "<" + args.ToString () + ">";
1101 public ConstructedType (Type t, TypeArguments args, Location l)
1104 gt = t.GetGenericTypeDefinition ();
1106 this.name = new TypeExpression (gt, l);
1107 full_name = gt.FullName + "<" + args.ToString () + ">";
1110 public TypeArguments TypeArguments {
1111 get { return args; }
1114 protected string DeclarationName {
1116 StringBuilder sb = new StringBuilder ();
1117 sb.Append (gt.FullName);
1119 for (int i = 0; i < gen_params.Length; i++) {
1122 sb.Append (gen_params [i]);
1125 return sb.ToString ();
1129 protected bool CheckConstraint (EmitContext ec, Type ptype, Expression expr,
1132 if (TypeManager.HasGenericArguments (ctype)) {
1133 Type[] types = TypeManager.GetTypeArguments (ctype);
1135 TypeArguments new_args = new TypeArguments (loc);
1137 for (int i = 0; i < types.Length; i++) {
1140 if (t.IsGenericParameter) {
1141 int pos = t.GenericParameterPosition;
1142 t = args.Arguments [pos];
1144 new_args.Add (new TypeExpression (t, loc));
1147 TypeExpr ct = new ConstructedType (ctype, new_args, loc);
1148 if (ct.ResolveAsTypeTerminal (ec) == null)
1153 return Convert.ImplicitStandardConversionExists (ec, expr, ctype);
1156 protected bool CheckConstraints (EmitContext ec, int index)
1158 Type atype = atypes [index];
1159 Type ptype = gen_params [index];
1164 Expression aexpr = new EmptyExpression (atype);
1166 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1170 bool is_class, is_struct;
1171 if (atype.IsGenericParameter) {
1172 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1174 is_class = agc.HasReferenceTypeConstraint;
1175 is_struct = agc.HasValueTypeConstraint;
1177 is_class = is_struct = false;
1180 is_class = atype.IsClass;
1181 is_struct = atype.IsValueType;
1185 // First, check the `class' and `struct' constraints.
1187 if (gc.HasReferenceTypeConstraint && !is_class) {
1188 Report.Error (452, loc, "The type `{0}' must be " +
1189 "a reference type in order to use it " +
1190 "as type parameter `{1}' in the " +
1191 "generic type or method `{2}'.",
1192 atype, ptype, DeclarationName);
1194 } else if (gc.HasValueTypeConstraint && !is_struct) {
1195 Report.Error (453, loc, "The type `{0}' must be " +
1196 "a value type in order to use it " +
1197 "as type parameter `{1}' in the " +
1198 "generic type or method `{2}'.",
1199 atype, ptype, DeclarationName);
1204 // The class constraint comes next.
1206 if (gc.HasClassConstraint) {
1207 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint)) {
1208 Report.Error (309, loc, "The type `{0}' must be " +
1209 "convertible to `{1}' in order to " +
1210 "use it as parameter `{2}' in the " +
1211 "generic type or method `{3}'",
1212 atype, gc.ClassConstraint, ptype, DeclarationName);
1218 // Now, check the interface constraints.
1220 foreach (Type it in gc.InterfaceConstraints) {
1222 if (it.IsGenericParameter)
1223 itype = atypes [it.GenericParameterPosition];
1227 if (!CheckConstraint (ec, ptype, aexpr, itype)) {
1228 Report.Error (309, loc, "The type `{0}' must be " +
1229 "convertible to `{1}' in order to " +
1230 "use it as parameter `{2}' in the " +
1231 "generic type or method `{3}'",
1232 atype, itype, ptype, DeclarationName);
1238 // Finally, check the constructor constraint.
1241 if (!gc.HasConstructorConstraint)
1244 if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
1247 MethodGroupExpr mg = Expression.MemberLookup (
1248 ec, atype, ".ctor", MemberTypes.Constructor,
1249 BindingFlags.Public | BindingFlags.Instance |
1250 BindingFlags.DeclaredOnly, loc)
1253 if (atype.IsAbstract || (mg == null) || !mg.IsInstance) {
1254 Report.Error (310, loc, "The type `{0}' must have a public " +
1255 "parameterless constructor in order to use it " +
1256 "as parameter `{1}' in the generic type or " +
1257 "method `{2}'", atype, ptype, DeclarationName);
1264 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
1266 if (!ResolveConstructedType (ec))
1272 public bool CheckConstraints (EmitContext ec)
1274 for (int i = 0; i < gen_params.Length; i++) {
1275 if (!CheckConstraints (ec, i))
1282 public bool ResolveConstructedType (EmitContext ec)
1287 return DoResolveType (ec);
1293 Report.Error (246, loc, "Cannot find type `{0}'<...>", Name);
1297 num_args = TypeManager.GetNumberOfTypeArguments (t);
1298 if (num_args == 0) {
1299 Report.Error (308, loc,
1300 "The non-generic type `{0}' cannot " +
1301 "be used with type arguments.",
1302 TypeManager.CSharpName (t));
1306 gt = t.GetGenericTypeDefinition ();
1307 return DoResolveType (ec);
1310 bool DoResolveType (EmitContext ec)
1313 // Resolve the arguments.
1315 if (args.Resolve (ec) == false)
1318 gen_params = gt.GetGenericArguments ();
1319 atypes = args.Arguments;
1321 if (atypes.Length != gen_params.Length) {
1322 Report.Error (305, loc,
1323 "Using the generic type `{0}' " +
1324 "requires {1} type arguments",
1325 TypeManager.GetFullName (gt),
1331 // Now bind the parameters.
1333 type = gt.BindGenericParameters (atypes);
1337 public Expression GetSimpleName (EmitContext ec)
1342 public override bool CheckAccessLevel (DeclSpace ds)
1344 return ds.CheckAccessLevel (gt);
1347 public override bool AsAccessible (DeclSpace ds, int flags)
1349 return ds.AsAccessible (gt, flags);
1352 public override bool IsClass {
1353 get { return gt.IsClass; }
1356 public override bool IsValueType {
1357 get { return gt.IsValueType; }
1360 public override bool IsInterface {
1361 get { return gt.IsInterface; }
1364 public override bool IsSealed {
1365 get { return gt.IsSealed; }
1368 public override bool Equals (object obj)
1370 ConstructedType cobj = obj as ConstructedType;
1374 if ((type == null) || (cobj.type == null))
1377 return type == cobj.type;
1380 public override int GetHashCode ()
1382 return base.GetHashCode ();
1385 public override string Name {
1392 public override string FullName {
1399 public class GenericMethod : DeclSpace
1401 public GenericMethod (NamespaceEntry ns, TypeContainer parent,
1402 MemberName name, Location l)
1403 : base (ns, parent, name, null, l)
1406 public override TypeBuilder DefineType ()
1408 throw new Exception ();
1411 public override bool Define ()
1413 ec = new EmitContext (this, this, Location, null, null, ModFlags, false);
1415 for (int i = 0; i < TypeParameters.Length; i++)
1416 if (!TypeParameters [i].Resolve (this))
1422 public bool Define (MethodBuilder mb)
1424 GenericTypeParameterBuilder[] gen_params;
1425 string[] names = MemberName.TypeArguments.GetDeclarations ();
1426 gen_params = mb.DefineGenericParameters (names);
1427 for (int i = 0; i < TypeParameters.Length; i++)
1428 TypeParameters [i].Define (gen_params [i]);
1433 for (int i = 0; i < TypeParameters.Length; i++) {
1434 if (!TypeParameters [i].ResolveType (ec))
1441 public bool DefineType (EmitContext ec, MethodBuilder mb,
1442 MethodInfo implementing, bool is_override)
1444 for (int i = 0; i < TypeParameters.Length; i++)
1445 if (!TypeParameters [i].DefineType (
1446 ec, mb, implementing, is_override))
1452 public override bool DefineMembers (TypeContainer parent)
1457 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1458 MemberFilter filter, object criteria)
1460 throw new Exception ();
1463 public override MemberCache MemberCache {
1469 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1474 protected override void VerifyObsoleteAttribute()
1479 public override AttributeTargets AttributeTargets {
1481 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1485 public override string DocCommentHeader {
1486 get { return "M:"; }
1490 public class DefaultValueExpression : Expression
1493 LocalTemporary temp_storage;
1495 public DefaultValueExpression (Expression expr, Location loc)
1501 public override Expression DoResolve (EmitContext ec)
1503 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
1508 if (type.IsGenericParameter || TypeManager.IsValueType (type))
1509 temp_storage = new LocalTemporary (ec, type);
1511 eclass = ExprClass.Variable;
1515 public override void Emit (EmitContext ec)
1517 if (temp_storage != null) {
1518 temp_storage.AddressOf (ec, AddressOp.LoadStore);
1519 ec.ig.Emit (OpCodes.Initobj, type);
1520 temp_storage.Emit (ec);
1522 ec.ig.Emit (OpCodes.Ldnull);
1526 public class NullableType : TypeExpr
1528 Expression underlying;
1530 public NullableType (Expression underlying, Location l)
1532 this.underlying = underlying;
1535 eclass = ExprClass.Type;
1538 public NullableType (Type type, Location loc)
1539 : this (new TypeExpression (type, loc), loc)
1542 public override string Name {
1543 get { return underlying.ToString () + "?"; }
1546 public override string FullName {
1547 get { return underlying.ToString () + "?"; }
1550 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
1552 TypeArguments args = new TypeArguments (loc);
1553 args.Add (underlying);
1555 ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
1556 return ctype.ResolveAsTypeTerminal (ec);
1560 public partial class TypeManager
1563 // A list of core types that the compiler requires or uses
1565 static public Type new_constraint_attr_type;
1566 static public Type activator_type;
1567 static public Type generic_ienumerator_type;
1568 static public Type generic_ienumerable_type;
1569 static public Type generic_nullable_type;
1572 // Tracks the generic parameters.
1574 static PtrHashtable builder_to_type_param;
1577 // These methods are called by code generated by the compiler
1579 static public MethodInfo activator_create_instance;
1581 static void InitGenerics ()
1583 builder_to_type_param = new PtrHashtable ();
1586 static void CleanUpGenerics ()
1588 builder_to_type_param = null;
1591 static void InitGenericCoreTypes ()
1593 activator_type = CoreLookupType ("System.Activator");
1594 new_constraint_attr_type = CoreLookupType (
1595 "System.Runtime.CompilerServices.NewConstraintAttribute");
1597 generic_ienumerator_type = CoreLookupType ("System.Collections.Generic.IEnumerator", 1);
1598 generic_ienumerable_type = CoreLookupType ("System.Collections.Generic.IEnumerable", 1);
1599 generic_nullable_type = CoreLookupType ("System.Nullable", 1);
1602 static void InitGenericCodeHelpers ()
1605 Type [] type_arg = { type_type };
1606 activator_create_instance = GetMethod (
1607 activator_type, "CreateInstance", type_arg);
1610 static Type CoreLookupType (string name, int arity)
1612 return CoreLookupType (MemberName.MakeName (name, arity));
1615 public static void AddTypeParameter (Type t, TypeParameter tparam)
1617 if (!builder_to_type_param.Contains (t))
1618 builder_to_type_param.Add (t, tparam);
1621 public static TypeContainer LookupGenericTypeContainer (Type t)
1623 while (t.IsGenericInstance)
1624 t = t.GetGenericTypeDefinition ();
1626 return LookupTypeContainer (t);
1629 public static TypeParameter LookupTypeParameter (Type t)
1631 return (TypeParameter) builder_to_type_param [t];
1634 public static bool HasConstructorConstraint (Type t)
1636 GenericConstraints gc = GetTypeParameterConstraints (t);
1640 return (gc.Attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0;
1643 public static GenericConstraints GetTypeParameterConstraints (Type t)
1645 if (!t.IsGenericParameter)
1646 throw new InvalidOperationException ();
1648 TypeParameter tparam = LookupTypeParameter (t);
1650 return tparam.GenericConstraints;
1652 return new ReflectionConstraints (t);
1655 public static bool IsGeneric (Type t)
1657 DeclSpace ds = (DeclSpace) builder_to_declspace [t];
1659 return ds.IsGeneric;
1662 public static bool HasGenericArguments (Type t)
1664 return GetNumberOfTypeArguments (t) > 0;
1667 public static int GetNumberOfTypeArguments (Type t)
1669 DeclSpace tc = LookupDeclSpace (t);
1671 return tc.IsGeneric ? tc.CountTypeParameters : 0;
1673 return t.HasGenericArguments ? t.GetGenericArguments ().Length : 0;
1676 public static Type[] GetTypeArguments (Type t)
1678 DeclSpace tc = LookupDeclSpace (t);
1681 return Type.EmptyTypes;
1683 TypeParameter[] tparam = tc.TypeParameters;
1684 Type[] ret = new Type [tparam.Length];
1685 for (int i = 0; i < tparam.Length; i++) {
1686 ret [i] = tparam [i].Type;
1687 if (ret [i] == null)
1688 throw new InternalErrorException ();
1693 return t.GetGenericArguments ();
1697 // Whether `array' is an array of T and `enumerator' is `IEnumerable<T>'.
1698 // For instance "string[]" -> "IEnumerable<string>".
1700 public static bool IsIEnumerable (Type array, Type enumerator)
1702 if (!array.IsArray || !enumerator.IsGenericInstance)
1705 if (enumerator.GetGenericTypeDefinition () != generic_ienumerable_type)
1708 Type[] args = GetTypeArguments (enumerator);
1709 return args [0] == GetElementType (array);
1712 public static bool IsEqual (Type a, Type b)
1717 if ((a is TypeBuilder) && a.IsGenericTypeDefinition && b.IsGenericInstance) {
1719 // `a' is a generic type definition's TypeBuilder and `b' is a
1720 // generic instance of the same type.
1726 // void Test (Stack<T> stack) { }
1729 // The first argument of `Test' will be the generic instance
1730 // "Stack<!0>" - which is the same type than the "Stack" TypeBuilder.
1733 // We hit this via Closure.Filter() for gen-82.cs.
1735 if (a != b.GetGenericTypeDefinition ())
1738 Type[] aparams = a.GetGenericArguments ();
1739 Type[] bparams = b.GetGenericArguments ();
1741 if (aparams.Length != bparams.Length)
1744 for (int i = 0; i < aparams.Length; i++)
1745 if (!IsEqual (aparams [i], bparams [i]))
1751 if ((b is TypeBuilder) && b.IsGenericTypeDefinition && a.IsGenericInstance)
1752 return IsEqual (b, a);
1754 if (a.IsGenericParameter && b.IsGenericParameter) {
1755 if ((a.DeclaringMethod == null) || (b.DeclaringMethod == null))
1757 return a.GenericParameterPosition == b.GenericParameterPosition;
1760 if (a.IsArray && b.IsArray) {
1761 if (a.GetArrayRank () != b.GetArrayRank ())
1763 return IsEqual (a.GetElementType (), b.GetElementType ());
1766 if (a.IsGenericInstance && b.IsGenericInstance) {
1767 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
1770 Type[] aargs = a.GetGenericArguments ();
1771 Type[] bargs = b.GetGenericArguments ();
1773 if (aargs.Length != bargs.Length)
1776 for (int i = 0; i < aargs.Length; i++) {
1777 if (!IsEqual (aargs [i], bargs [i]))
1787 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_infered, Type[] method_infered)
1789 if (a.IsGenericParameter) {
1791 // If a is an array of a's type, they may never
1795 b = b.GetElementType ();
1801 // If b is a generic parameter or an actual type,
1802 // they may become equal:
1804 // class X<T,U> : I<T>, I<U>
1805 // class X<T> : I<T>, I<float>
1807 if (b.IsGenericParameter || !b.IsGenericInstance) {
1808 int pos = a.GenericParameterPosition;
1809 Type[] args = a.DeclaringMethod != null ? method_infered : class_infered;
1810 if (args [pos] == null) {
1815 return args [pos] == a;
1819 // We're now comparing a type parameter with a
1820 // generic instance. They may become equal unless
1821 // the type parameter appears anywhere in the
1822 // generic instance:
1824 // class X<T,U> : I<T>, I<X<U>>
1825 // -> error because you could instanciate it as
1828 // class X<T> : I<T>, I<X<T>> -> ok
1831 Type[] bargs = GetTypeArguments (b);
1832 for (int i = 0; i < bargs.Length; i++) {
1833 if (a.Equals (bargs [i]))
1840 if (b.IsGenericParameter)
1841 return MayBecomeEqualGenericTypes (b, a, class_infered, method_infered);
1844 // At this point, neither a nor b are a type parameter.
1846 // If one of them is a generic instance, let
1847 // MayBecomeEqualGenericInstances() compare them (if the
1848 // other one is not a generic instance, they can never
1852 if (a.IsGenericInstance || b.IsGenericInstance)
1853 return MayBecomeEqualGenericInstances (a, b, class_infered, method_infered);
1856 // If both of them are arrays.
1859 if (a.IsArray && b.IsArray) {
1860 if (a.GetArrayRank () != b.GetArrayRank ())
1863 a = a.GetElementType ();
1864 b = b.GetElementType ();
1866 return MayBecomeEqualGenericTypes (a, b, class_infered, method_infered);
1870 // Ok, two ordinary types.
1873 return a.Equals (b);
1877 // Checks whether two generic instances may become equal for some
1878 // particular instantiation (26.3.1).
1880 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
1881 Type[] class_infered, Type[] method_infered)
1883 if (!a.IsGenericInstance || !b.IsGenericInstance)
1885 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
1888 return MayBecomeEqualGenericInstances (
1889 GetTypeArguments (a), GetTypeArguments (b), class_infered, method_infered);
1892 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
1893 Type[] class_infered, Type[] method_infered)
1895 if (aargs.Length != bargs.Length)
1898 for (int i = 0; i < aargs.Length; i++) {
1899 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_infered, method_infered))
1906 public static bool IsEqualGenericInstance (Type type, Type parent)
1908 int tcount = GetNumberOfTypeArguments (type);
1909 int pcount = GetNumberOfTypeArguments (parent);
1911 if (type.IsGenericInstance)
1912 type = type.GetGenericTypeDefinition ();
1913 if (parent.IsGenericInstance)
1914 parent = parent.GetGenericTypeDefinition ();
1916 if (tcount != pcount)
1919 return type.Equals (parent);
1922 static public bool IsGenericMethod (MethodBase mb)
1924 if (mb.DeclaringType is TypeBuilder) {
1925 IMethodData method = (IMethodData) builder_to_method [mb];
1929 return method.GenericMethod != null;
1932 return mb.IsGenericMethodDefinition;
1939 static bool InferType (Type pt, Type at, Type[] infered)
1941 if (pt.IsGenericParameter && (pt.DeclaringMethod != null)) {
1942 int pos = pt.GenericParameterPosition;
1944 if (infered [pos] == null) {
1946 while (check.IsArray)
1947 check = check.GetElementType ();
1956 if (infered [pos] != at)
1962 if (!pt.ContainsGenericParameters) {
1963 if (at.ContainsGenericParameters)
1964 return InferType (at, pt, infered);
1971 (at.GetArrayRank () != pt.GetArrayRank ()))
1974 return InferType (pt.GetElementType (), at.GetElementType (), infered);
1979 (pt.GetArrayRank () != at.GetArrayRank ()))
1982 return InferType (pt.GetElementType (), at.GetElementType (), infered);
1985 if (pt.IsByRef && at.IsByRef)
1986 return InferType (pt.GetElementType (), at.GetElementType (), infered);
1987 ArrayList list = new ArrayList ();
1988 if (at.IsGenericInstance)
1991 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
1994 list.AddRange (TypeManager.GetInterfaces (at));
1997 bool found_one = false;
1999 foreach (Type type in list) {
2000 if (!type.IsGenericInstance)
2003 Type[] infered_types = new Type [infered.Length];
2005 if (!InferGenericInstance (pt, type, infered_types))
2008 for (int i = 0; i < infered_types.Length; i++) {
2009 if (infered [i] == null) {
2010 infered [i] = infered_types [i];
2014 if (infered [i] != infered_types [i])
2024 static bool InferGenericInstance (Type pt, Type at, Type[] infered_types)
2026 Type[] at_args = at.GetGenericArguments ();
2027 Type[] pt_args = pt.GetGenericArguments ();
2029 if (at_args.Length != pt_args.Length)
2032 for (int i = 0; i < at_args.Length; i++) {
2033 if (!InferType (pt_args [i], at_args [i], infered_types))
2037 for (int i = 0; i < infered_types.Length; i++) {
2038 if (infered_types [i] == null)
2045 public static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
2046 ref MethodBase method)
2048 if ((arguments == null) || !TypeManager.IsGenericMethod (method))
2053 if (arguments == null)
2056 arg_count = arguments.Count;
2058 ParameterData pd = TypeManager.GetParameterData (method);
2060 int pd_count = pd.Count;
2065 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2068 if (pd_count - 1 > arg_count)
2071 if (pd_count == 1 && arg_count == 0)
2074 Type[] method_args = method.GetGenericArguments ();
2075 Type[] infered_types = new Type [method_args.Length];
2078 // If we have come this far, the case which
2079 // remains is when the number of parameters is
2080 // less than or equal to the argument count.
2082 for (int i = 0; i < pd_count - 1; ++i) {
2083 Argument a = (Argument) arguments [i];
2085 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2088 Type pt = pd.ParameterType (i);
2091 if (!InferType (pt, at, infered_types))
2095 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
2097 for (int i = pd_count - 1; i < arg_count; i++) {
2098 Argument a = (Argument) arguments [i];
2100 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2103 if (!InferType (element_type, a.Type, infered_types))
2107 for (int i = 0; i < infered_types.Length; i++)
2108 if (infered_types [i] == null)
2111 method = method.BindGenericParameters (infered_types);
2115 public static bool InferTypeArguments (Type[] param_types, Type[] arg_types, Type[] infered_types)
2117 if (infered_types == null)
2120 for (int i = 0; i < arg_types.Length; i++) {
2121 if (arg_types [i] == null)
2124 if (!InferType (param_types [i], arg_types [i], infered_types))
2128 for (int i = 0; i < infered_types.Length; i++)
2129 if (infered_types [i] == null)
2135 public static bool InferTypeArguments (EmitContext ec, ArrayList arguments,
2136 ref MethodBase method)
2138 if (!TypeManager.IsGenericMethod (method))
2142 if (arguments != null)
2143 arg_count = arguments.Count;
2147 ParameterData pd = TypeManager.GetParameterData (method);
2148 if (arg_count != pd.Count)
2151 Type[] method_args = method.GetGenericArguments ();
2153 bool is_open = false;
2154 for (int i = 0; i < method_args.Length; i++) {
2155 if (method_args [i].IsGenericParameter) {
2163 Type[] infered_types = new Type [method_args.Length];
2165 Type[] param_types = new Type [pd.Count];
2166 Type[] arg_types = new Type [pd.Count];
2168 for (int i = 0; i < arg_count; i++) {
2169 param_types [i] = pd.ParameterType (i);
2171 Argument a = (Argument) arguments [i];
2172 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2175 arg_types [i] = a.Type;
2178 if (!InferTypeArguments (param_types, arg_types, infered_types))
2181 method = method.BindGenericParameters (infered_types);
2185 public static bool InferTypeArguments (EmitContext ec, ParameterData apd,
2186 ref MethodBase method)
2188 if (!TypeManager.IsGenericMethod (method))
2191 ParameterData pd = TypeManager.GetParameterData (method);
2192 if (apd.Count != pd.Count)
2195 Type[] method_args = method.GetGenericArguments ();
2196 Type[] infered_types = new Type [method_args.Length];
2198 Type[] param_types = new Type [pd.Count];
2199 Type[] arg_types = new Type [pd.Count];
2201 for (int i = 0; i < apd.Count; i++) {
2202 param_types [i] = pd.ParameterType (i);
2203 arg_types [i] = apd.ParameterType (i);
2206 if (!InferTypeArguments (param_types, arg_types, infered_types))
2209 method = method.BindGenericParameters (infered_types);
2213 public static bool IsNullableType (Type t)
2215 if (!t.IsGenericInstance)
2218 Type gt = t.GetGenericTypeDefinition ();
2219 return gt == generic_nullable_type;
2223 public abstract class Nullable
2225 protected sealed class NullableInfo
2227 public readonly Type Type;
2228 public readonly Type UnderlyingType;
2229 public readonly MethodInfo HasValue;
2230 public readonly MethodInfo Value;
2231 public readonly ConstructorInfo Constructor;
2233 public NullableInfo (Type type)
2236 UnderlyingType = TypeManager.GetTypeArguments (type) [0];
2238 PropertyInfo has_value_pi = type.GetProperty ("HasValue");
2239 PropertyInfo value_pi = type.GetProperty ("Value");
2241 HasValue = has_value_pi.GetGetMethod (false);
2242 Value = value_pi.GetGetMethod (false);
2243 Constructor = type.GetConstructor (new Type[] { UnderlyingType });
2247 protected class Unwrap : Expression, IMemoryLocation, IAssignMethod
2252 LocalTemporary temp;
2255 public Unwrap (Expression expr, Location loc)
2261 public override Expression DoResolve (EmitContext ec)
2263 expr = expr.Resolve (ec);
2267 if (!(expr is IMemoryLocation))
2268 temp = new LocalTemporary (ec, expr.Type);
2270 info = new NullableInfo (expr.Type);
2271 type = info.UnderlyingType;
2272 eclass = expr.eclass;
2276 public override void Emit (EmitContext ec)
2278 AddressOf (ec, AddressOp.LoadStore);
2279 ec.ig.EmitCall (OpCodes.Call, info.Value, null);
2282 public void EmitCheck (EmitContext ec)
2284 AddressOf (ec, AddressOp.LoadStore);
2285 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
2288 void create_temp (EmitContext ec)
2290 if ((temp != null) && !has_temp) {
2297 public void AddressOf (EmitContext ec, AddressOp mode)
2301 temp.AddressOf (ec, AddressOp.LoadStore);
2303 ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
2306 public void Emit (EmitContext ec, bool leave_copy)
2319 public void EmitAssign (EmitContext ec, Expression source,
2320 bool leave_copy, bool prepare_for_load)
2323 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2326 ec.ig.Emit (OpCodes.Dup);
2328 Expression empty = new EmptyExpression (expr.Type);
2329 ((IAssignMethod) expr).EmitAssign (ec, empty, false, prepare_for_load);
2333 protected class Wrap : Expression
2338 public Wrap (Expression expr, Location loc)
2344 public override Expression DoResolve (EmitContext ec)
2346 expr = expr.Resolve (ec);
2350 TypeExpr target_type = new NullableType (expr.Type, loc);
2351 target_type = target_type.ResolveAsTypeTerminal (ec);
2352 if (target_type == null)
2355 type = target_type.Type;
2356 info = new NullableInfo (type);
2357 eclass = ExprClass.Value;
2361 public override void Emit (EmitContext ec)
2364 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2368 public class NullableLiteral : Expression, IMemoryLocation {
2369 public NullableLiteral (Type target_type, Location loc)
2371 this.type = target_type;
2374 eclass = ExprClass.Value;
2377 public override Expression DoResolve (EmitContext ec)
2382 public override void Emit (EmitContext ec)
2384 LocalTemporary value_target = new LocalTemporary (ec, type);
2386 value_target.AddressOf (ec, AddressOp.Store);
2387 ec.ig.Emit (OpCodes.Initobj, type);
2388 value_target.Emit (ec);
2391 public void AddressOf (EmitContext ec, AddressOp Mode)
2393 LocalTemporary value_target = new LocalTemporary (ec, type);
2395 value_target.AddressOf (ec, AddressOp.Store);
2396 ec.ig.Emit (OpCodes.Initobj, type);
2397 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
2401 public abstract class Lifted : Expression, IMemoryLocation
2403 Expression expr, underlying, wrap, null_value;
2406 protected Lifted (Expression expr, Location loc)
2412 public override Expression DoResolve (EmitContext ec)
2414 expr = expr.Resolve (ec);
2418 unwrap = (Unwrap) new Unwrap (expr, loc).Resolve (ec);
2422 underlying = ResolveUnderlying (unwrap, ec);
2423 if (underlying == null)
2426 wrap = new Wrap (underlying, loc).Resolve (ec);
2430 null_value = new NullableLiteral (wrap.Type, loc).Resolve (ec);
2431 if (null_value == null)
2435 eclass = ExprClass.Value;
2439 protected abstract Expression ResolveUnderlying (Expression unwrap, EmitContext ec);
2441 public override void Emit (EmitContext ec)
2443 ILGenerator ig = ec.ig;
2444 Label is_null_label = ig.DefineLabel ();
2445 Label end_label = ig.DefineLabel ();
2447 unwrap.EmitCheck (ec);
2448 ig.Emit (OpCodes.Brfalse, is_null_label);
2451 ig.Emit (OpCodes.Br, end_label);
2453 ig.MarkLabel (is_null_label);
2454 null_value.Emit (ec);
2456 ig.MarkLabel (end_label);
2459 public void AddressOf (EmitContext ec, AddressOp mode)
2461 unwrap.AddressOf (ec, mode);
2465 public class LiftedConversion : Lifted
2467 public readonly bool IsUser;
2468 public readonly bool IsExplicit;
2469 public readonly Type TargetType;
2471 public LiftedConversion (Expression expr, Type target_type, bool is_user,
2472 bool is_explicit, Location loc)
2475 this.IsUser = is_user;
2476 this.IsExplicit = is_explicit;
2477 this.TargetType = target_type;
2480 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2482 Type type = TypeManager.GetTypeArguments (TargetType) [0];
2485 return Convert.UserDefinedConversion (ec, unwrap, type, loc, IsExplicit);
2488 return Convert.ExplicitConversion (ec, unwrap, type, loc);
2490 return Convert.ImplicitConversion (ec, unwrap, type, loc);
2495 public class LiftedUnaryOperator : Lifted
2497 public readonly Unary.Operator Oper;
2499 public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
2505 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2507 return new Unary (Oper, unwrap, loc);
2511 public class LiftedConditional : Lifted
2513 Expression expr, true_expr, false_expr;
2516 public LiftedConditional (Expression expr, Expression true_expr, Expression false_expr,
2520 this.true_expr = true_expr;
2521 this.false_expr = false_expr;
2524 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2526 return new Conditional (unwrap, true_expr, false_expr, loc);
2530 public class LiftedBinaryOperator : Expression
2532 public readonly Binary.Operator Oper;
2534 Expression left, right, underlying, null_value, bool_wrap;
2535 Unwrap left_unwrap, right_unwrap;
2536 bool is_equality, is_comparision, is_boolean;
2538 public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
2547 public override Expression DoResolve (EmitContext ec)
2549 if (TypeManager.IsNullableType (left.Type)) {
2550 left_unwrap = new Unwrap (left, loc);
2551 left = left_unwrap.Resolve (ec);
2556 if (TypeManager.IsNullableType (right.Type)) {
2557 right_unwrap = new Unwrap (right, loc);
2558 right = right_unwrap.Resolve (ec);
2563 if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr) ||
2564 (Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr)) &&
2565 ((left.Type == TypeManager.bool_type) && (right.Type == TypeManager.bool_type))) {
2566 Expression empty = new EmptyExpression (TypeManager.bool_type);
2567 bool_wrap = new Wrap (empty, loc).Resolve (ec);
2568 null_value = new NullableLiteral (bool_wrap.Type, loc).Resolve (ec);
2570 type = bool_wrap.Type;
2572 } else if ((Oper == Binary.Operator.Equality) || (Oper == Binary.Operator.Inequality)) {
2573 if (!(left is NullLiteral) && !(right is NullLiteral)) {
2574 underlying = new Binary (Oper, left, right, loc).Resolve (ec);
2575 if (underlying == null)
2579 type = TypeManager.bool_type;
2581 } else if ((Oper == Binary.Operator.LessThan) ||
2582 (Oper == Binary.Operator.GreaterThan) ||
2583 (Oper == Binary.Operator.LessThanOrEqual) ||
2584 (Oper == Binary.Operator.GreaterThanOrEqual)) {
2585 underlying = new Binary (Oper, left, right, loc).Resolve (ec);
2586 if (underlying == null)
2589 type = TypeManager.bool_type;
2590 is_comparision = true;
2592 underlying = new Binary (Oper, left, right, loc).Resolve (ec);
2593 if (underlying == null)
2596 underlying = new Wrap (underlying, loc).Resolve (ec);
2597 if (underlying == null)
2600 type = underlying.Type;
2601 null_value = new NullableLiteral (type, loc).Resolve (ec);
2604 eclass = ExprClass.Value;
2608 void EmitBoolean (EmitContext ec)
2610 ILGenerator ig = ec.ig;
2612 Label left_is_null_label = ig.DefineLabel ();
2613 Label right_is_null_label = ig.DefineLabel ();
2614 Label is_null_label = ig.DefineLabel ();
2615 Label wrap_label = ig.DefineLabel ();
2616 Label end_label = ig.DefineLabel ();
2618 if (left_unwrap != null) {
2619 left_unwrap.EmitCheck (ec);
2620 ig.Emit (OpCodes.Brfalse, left_is_null_label);
2624 ig.Emit (OpCodes.Dup);
2625 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
2626 ig.Emit (OpCodes.Brtrue, wrap_label);
2628 ig.Emit (OpCodes.Brfalse, wrap_label);
2630 if (right_unwrap != null) {
2631 right_unwrap.EmitCheck (ec);
2632 ig.Emit (OpCodes.Brfalse, right_is_null_label);
2635 if ((Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr))
2636 ig.Emit (OpCodes.Pop);
2639 if (Oper == Binary.Operator.BitwiseOr)
2640 ig.Emit (OpCodes.Or);
2641 else if (Oper == Binary.Operator.BitwiseAnd)
2642 ig.Emit (OpCodes.And);
2643 ig.Emit (OpCodes.Br, wrap_label);
2645 ig.MarkLabel (left_is_null_label);
2646 if (right_unwrap != null) {
2647 right_unwrap.EmitCheck (ec);
2648 ig.Emit (OpCodes.Brfalse, is_null_label);
2652 ig.Emit (OpCodes.Dup);
2653 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
2654 ig.Emit (OpCodes.Brtrue, wrap_label);
2656 ig.Emit (OpCodes.Brfalse, wrap_label);
2658 ig.MarkLabel (right_is_null_label);
2659 ig.Emit (OpCodes.Pop);
2660 ig.MarkLabel (is_null_label);
2661 null_value.Emit (ec);
2662 ig.Emit (OpCodes.Br, end_label);
2664 ig.MarkLabel (wrap_label);
2665 ig.Emit (OpCodes.Nop);
2666 bool_wrap.Emit (ec);
2667 ig.Emit (OpCodes.Nop);
2669 ig.MarkLabel (end_label);
2672 void EmitEquality (EmitContext ec)
2674 ILGenerator ig = ec.ig;
2676 Label left_not_null_label = ig.DefineLabel ();
2677 Label false_label = ig.DefineLabel ();
2678 Label true_label = ig.DefineLabel ();
2679 Label end_label = ig.DefineLabel ();
2681 if (left_unwrap != null) {
2682 left_unwrap.EmitCheck (ec);
2683 if (right is NullLiteral) {
2684 if (Oper == Binary.Operator.Equality)
2685 ig.Emit (OpCodes.Brfalse, true_label);
2687 ig.Emit (OpCodes.Brfalse, false_label);
2688 } else if (right_unwrap != null) {
2689 ig.Emit (OpCodes.Dup);
2690 ig.Emit (OpCodes.Brtrue, left_not_null_label);
2691 right_unwrap.EmitCheck (ec);
2692 ig.Emit (OpCodes.Ceq);
2693 if (Oper == Binary.Operator.Inequality) {
2694 ig.Emit (OpCodes.Ldc_I4_0);
2695 ig.Emit (OpCodes.Ceq);
2697 ig.Emit (OpCodes.Br, end_label);
2699 ig.MarkLabel (left_not_null_label);
2700 ig.Emit (OpCodes.Pop);
2702 if (Oper == Binary.Operator.Equality)
2703 ig.Emit (OpCodes.Brfalse, false_label);
2705 ig.Emit (OpCodes.Brfalse, true_label);
2709 if (right_unwrap != null) {
2710 right_unwrap.EmitCheck (ec);
2711 if (left is NullLiteral) {
2712 if (Oper == Binary.Operator.Equality)
2713 ig.Emit (OpCodes.Brfalse, true_label);
2715 ig.Emit (OpCodes.Brfalse, false_label);
2717 if (Oper == Binary.Operator.Equality)
2718 ig.Emit (OpCodes.Brfalse, false_label);
2720 ig.Emit (OpCodes.Brfalse, true_label);
2724 bool left_is_null = left is NullLiteral;
2725 bool right_is_null = right is NullLiteral;
2726 if (left_is_null || right_is_null) {
2727 if (((Oper == Binary.Operator.Equality) && (left_is_null == right_is_null)) ||
2728 ((Oper == Binary.Operator.Inequality) && (left_is_null != right_is_null)))
2729 ig.Emit (OpCodes.Br, true_label);
2731 ig.Emit (OpCodes.Br, false_label);
2733 underlying.Emit (ec);
2734 ig.Emit (OpCodes.Br, end_label);
2737 ig.MarkLabel (false_label);
2738 ig.Emit (OpCodes.Ldc_I4_0);
2739 ig.Emit (OpCodes.Br, end_label);
2741 ig.MarkLabel (true_label);
2742 ig.Emit (OpCodes.Ldc_I4_1);
2744 ig.MarkLabel (end_label);
2747 void EmitComparision (EmitContext ec)
2749 ILGenerator ig = ec.ig;
2751 Label is_null_label = ig.DefineLabel ();
2752 Label end_label = ig.DefineLabel ();
2754 if (left_unwrap != null) {
2755 left_unwrap.EmitCheck (ec);
2756 ig.Emit (OpCodes.Brfalse, is_null_label);
2759 if (right_unwrap != null) {
2760 right_unwrap.EmitCheck (ec);
2761 ig.Emit (OpCodes.Brfalse, is_null_label);
2764 underlying.Emit (ec);
2765 ig.Emit (OpCodes.Br, end_label);
2767 ig.MarkLabel (is_null_label);
2768 ig.Emit (OpCodes.Ldc_I4_0);
2770 ig.MarkLabel (end_label);
2773 public override void Emit (EmitContext ec)
2778 } else if (is_equality) {
2781 } else if (is_comparision) {
2782 EmitComparision (ec);
2786 ILGenerator ig = ec.ig;
2788 Label is_null_label = ig.DefineLabel ();
2789 Label end_label = ig.DefineLabel ();
2791 if (left_unwrap != null) {
2792 left_unwrap.EmitCheck (ec);
2793 ig.Emit (OpCodes.Brfalse, is_null_label);
2796 if (right_unwrap != null) {
2797 right_unwrap.EmitCheck (ec);
2798 ig.Emit (OpCodes.Brfalse, is_null_label);
2801 underlying.Emit (ec);
2802 ig.Emit (OpCodes.Br, end_label);
2804 ig.MarkLabel (is_null_label);
2805 null_value.Emit (ec);
2807 ig.MarkLabel (end_label);
2811 public class OperatorTrueOrFalse : Expression
2813 public readonly bool IsTrue;
2818 public OperatorTrueOrFalse (Expression expr, bool is_true, Location loc)
2820 this.IsTrue = is_true;
2825 public override Expression DoResolve (EmitContext ec)
2827 unwrap = new Unwrap (expr, loc);
2828 expr = unwrap.Resolve (ec);
2832 if (unwrap.Type != TypeManager.bool_type)
2835 type = TypeManager.bool_type;
2836 eclass = ExprClass.Value;
2840 public override void Emit (EmitContext ec)
2842 ILGenerator ig = ec.ig;
2844 Label is_null_label = ig.DefineLabel ();
2845 Label end_label = ig.DefineLabel ();
2847 unwrap.EmitCheck (ec);
2848 ig.Emit (OpCodes.Brfalse, is_null_label);
2852 ig.Emit (OpCodes.Ldc_I4_0);
2853 ig.Emit (OpCodes.Ceq);
2855 ig.Emit (OpCodes.Br, end_label);
2857 ig.MarkLabel (is_null_label);
2858 ig.Emit (OpCodes.Ldc_I4_0);
2860 ig.MarkLabel (end_label);
2864 public class NullCoalescingOperator : Expression
2866 Expression left, right;
2870 public NullCoalescingOperator (Expression left, Expression right, Location loc)
2876 eclass = ExprClass.Value;
2879 public override Expression DoResolve (EmitContext ec)
2884 left = left.Resolve (ec);
2888 right = right.Resolve (ec);
2892 Type ltype = left.Type, rtype = right.Type;
2894 if (!TypeManager.IsNullableType (ltype) && ltype.IsValueType) {
2895 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
2899 if (TypeManager.IsNullableType (ltype)) {
2900 NullableInfo info = new NullableInfo (ltype);
2902 unwrap = (Unwrap) new Unwrap (left, loc).Resolve (ec);
2906 expr = Convert.ImplicitConversion (ec, right, info.UnderlyingType, loc);
2914 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
2920 if (unwrap != null) {
2921 expr = Convert.ImplicitConversion (ec, unwrap, rtype, loc);
2930 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
2934 public override void Emit (EmitContext ec)
2936 ILGenerator ig = ec.ig;
2938 Label is_null_label = ig.DefineLabel ();
2939 Label end_label = ig.DefineLabel ();
2941 if (unwrap != null) {
2942 unwrap.EmitCheck (ec);
2943 ig.Emit (OpCodes.Brfalse, is_null_label);
2947 ig.Emit (OpCodes.Br, end_label);
2949 ig.MarkLabel (is_null_label);
2952 ig.MarkLabel (end_label);
2956 public class LiftedUnaryMutator : ExpressionStatement
2958 public readonly UnaryMutator.Mode Mode;
2959 Expression expr, null_value;
2960 UnaryMutator underlying;
2963 public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
2969 eclass = ExprClass.Value;
2972 public override Expression DoResolve (EmitContext ec)
2974 expr = expr.Resolve (ec);
2978 unwrap = (Unwrap) new Unwrap (expr, loc).Resolve (ec);
2982 underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
2983 if (underlying == null)
2986 null_value = new NullableLiteral (expr.Type, loc).Resolve (ec);
2987 if (null_value == null)
2994 void DoEmit (EmitContext ec, bool is_expr)
2996 ILGenerator ig = ec.ig;
2997 Label is_null_label = ig.DefineLabel ();
2998 Label end_label = ig.DefineLabel ();
3000 unwrap.EmitCheck (ec);
3001 ig.Emit (OpCodes.Brfalse, is_null_label);
3004 underlying.Emit (ec);
3006 underlying.EmitStatement (ec);
3007 ig.Emit (OpCodes.Br, end_label);
3009 ig.MarkLabel (is_null_label);
3011 null_value.Emit (ec);
3013 ig.MarkLabel (end_label);
3016 public override void Emit (EmitContext ec)
3021 public override void EmitStatement (EmitContext ec)