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;
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 ArrayList new_list = new ArrayList ();
334 foreach (Type iface in list) {
335 if (new_list.Contains (iface))
338 new_list.Add (iface);
340 Type [] implementing = TypeManager.GetInterfaces (iface);
342 foreach (Type imp in implementing) {
343 if (!new_list.Contains (imp))
348 iface_constraint_types = new Type [new_list.Count];
349 new_list.CopyTo (iface_constraint_types, 0);
351 if (class_constraint != null) {
352 TypeExpr te = class_constraint.ResolveAsTypeTerminal (ec);
356 class_constraint_type = te.Type;
357 if (class_constraint_type == null)
360 if (class_constraint_type.IsSealed) {
361 Report.Error (701, loc,
362 "`{0}' is not a valid bound. Bounds " +
363 "must be interfaces or non sealed " +
364 "classes", class_constraint_type);
368 if ((class_constraint_type == TypeManager.array_type) ||
369 (class_constraint_type == TypeManager.delegate_type) ||
370 (class_constraint_type == TypeManager.enum_type) ||
371 (class_constraint_type == TypeManager.value_type) ||
372 (class_constraint_type == TypeManager.object_type)) {
373 Report.Error (702, loc,
374 "Bound cannot be special class `{0}'",
375 class_constraint_type);
380 if (class_constraint_type != null)
381 effective_base_type = class_constraint_type;
382 else if (HasValueTypeConstraint)
383 effective_base_type = TypeManager.value_type;
385 effective_base_type = TypeManager.object_type;
390 public bool CheckDependencies (EmitContext ec)
392 foreach (TypeParameterExpr expr in type_param_constraints) {
393 if (!CheckDependencies (expr.TypeParameter, ec))
400 bool CheckDependencies (TypeParameter tparam, EmitContext ec)
402 Constraints constraints = tparam.Constraints;
403 if (constraints == null)
406 if (HasValueTypeConstraint && constraints.HasClassConstraint) {
407 Report.Error (455, loc, "Type parameter `{0}' inherits " +
408 "conflicting constraints `{1}' and `{2}'",
409 name, constraints.ClassConstraint,
414 if (HasClassConstraint && constraints.HasClassConstraint) {
415 Type t1 = ClassConstraint;
416 TypeExpr e1 = class_constraint;
417 Type t2 = constraints.ClassConstraint;
418 TypeExpr e2 = constraints.class_constraint;
420 if (!Convert.ImplicitReferenceConversionExists (ec, e1, t2) &&
421 !Convert.ImplicitReferenceConversionExists (ec, e2, t1)) {
422 Report.Error (455, loc,
423 "Type parameter `{0}' inherits " +
424 "conflicting constraints `{1}' and `{2}'",
430 if (constraints.type_param_constraints == null)
433 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
434 if (!CheckDependencies (expr.TypeParameter, ec))
441 public void Define (GenericTypeParameterBuilder type)
443 type.SetGenericParameterAttributes (attrs);
446 public override GenericParameterAttributes Attributes {
447 get { return attrs; }
450 public override bool HasClassConstraint {
451 get { return class_constraint != null; }
454 public override Type ClassConstraint {
455 get { return class_constraint_type; }
458 public override Type[] InterfaceConstraints {
459 get { return iface_constraint_types; }
462 public override Type EffectiveBaseClass {
463 get { return effective_base_type; }
466 internal bool IsSubclassOf (Type t)
468 if ((class_constraint_type != null) &&
469 class_constraint_type.IsSubclassOf (t))
472 if (iface_constraint_types == null)
475 foreach (Type iface in iface_constraint_types) {
476 if (TypeManager.IsSubclassOf (iface, t))
483 public bool CheckInterfaceMethod (EmitContext ec, GenericConstraints gc)
485 if (gc.Attributes != attrs)
488 if (HasClassConstraint != gc.HasClassConstraint)
490 if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
493 int gc_icount = gc.InterfaceConstraints != null ?
494 gc.InterfaceConstraints.Length : 0;
495 int icount = InterfaceConstraints != null ?
496 InterfaceConstraints.Length : 0;
498 if (gc_icount != icount)
501 foreach (Type iface in gc.InterfaceConstraints) {
503 foreach (Type check in InterfaceConstraints) {
504 if (TypeManager.IsEqual (iface, check)) {
519 // This type represents a generic type parameter
521 public class TypeParameter : MemberCore, IMemberContainer {
523 GenericConstraints gc;
524 Constraints constraints;
526 GenericTypeParameterBuilder type;
528 public TypeParameter (TypeContainer parent, string name,
529 Constraints constraints, Location loc)
530 : base (parent, new MemberName (name), null, loc)
533 this.constraints = constraints;
537 public GenericConstraints GenericConstraints {
539 return gc != null ? gc : constraints;
543 public Constraints Constraints {
549 public bool HasConstructorConstraint {
551 if (constraints != null)
552 return constraints.HasConstructorConstraint;
564 public bool Resolve (DeclSpace ds)
566 if (constraints != null) {
567 if (!constraints.Resolve (ds.EmitContext)) {
576 public void Define (GenericTypeParameterBuilder type)
578 if (this.type != null)
579 throw new InvalidOperationException ();
582 TypeManager.AddTypeParameter (type, this);
585 public void DefineConstraints ()
587 if (constraints != null)
588 constraints.Define (type);
591 public bool ResolveType (EmitContext ec)
593 if (constraints != null) {
594 if (!constraints.ResolveTypes (ec)) {
603 public bool DefineType (EmitContext ec)
605 return DefineType (ec, null, null, false);
608 public bool DefineType (EmitContext ec, MethodBuilder builder,
609 MethodInfo implementing, bool is_override)
611 if (!ResolveType (ec))
614 if (implementing != null) {
615 if (is_override && (constraints != null)) {
617 460, loc, "Constraints for override and " +
618 "explicit interface implementation methods " +
619 "are inherited from the base method so they " +
620 "cannot be specified directly");
624 MethodBase mb = implementing;
625 if (mb.Mono_IsInflatedMethod)
626 mb = mb.GetGenericMethodDefinition ();
628 int pos = type.GenericParameterPosition;
629 ParameterData pd = TypeManager.GetParameterData (mb);
630 GenericConstraints temp_gc = pd.GenericConstraints (pos);
631 Type mparam = mb.GetGenericArguments () [pos];
634 gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
635 else if (constraints != null)
636 gc = new InflatedConstraints (constraints, implementing.DeclaringType);
639 if (constraints != null) {
642 else if (!constraints.CheckInterfaceMethod (ec, gc))
645 if (!is_override && (temp_gc != null))
650 Report.SymbolRelatedToPreviousError (implementing);
653 425, loc, "The constraints for type " +
654 "parameter `{0}' of method `{1}' must match " +
655 "the constraints for type parameter `{2}' " +
656 "of interface method `{3}'. Consider using " +
657 "an explicit interface implementation instead",
658 Name, TypeManager.CSharpSignature (builder),
659 mparam, TypeManager.CSharpSignature (mb));
663 gc = (GenericConstraints) constraints;
669 if (gc.HasClassConstraint)
670 type.SetBaseTypeConstraint (gc.ClassConstraint);
672 type.SetInterfaceConstraints (gc.InterfaceConstraints);
673 TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
678 public bool CheckDependencies (EmitContext ec)
680 if (constraints != null)
681 return constraints.CheckDependencies (ec);
686 public bool UpdateConstraints (EmitContext ec, Constraints new_constraints)
689 // We're used in partial generic type definitions.
690 // If `check' is false, we just encountered the first ClassPart which has
691 // constraints - they become our "real" constraints.
692 // Otherwise we're called after the type parameters have already been defined
693 // and check whether the constraints are the same in all parts.
696 throw new InvalidOperationException ();
698 if (constraints == null) {
699 new_constraints = constraints;
701 } else if (new_constraints == null)
704 if (!new_constraints.Resolve (ec))
706 if (!new_constraints.ResolveTypes (ec))
709 return constraints.CheckInterfaceMethod (ec, new_constraints);
712 public override string DocCommentHeader {
714 throw new InvalidOperationException (
715 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
723 public override bool Define ()
728 protected override void VerifyObsoleteAttribute ()
731 public override void ApplyAttributeBuilder (Attribute a,
732 CustomAttributeBuilder cb)
735 public override AttributeTargets AttributeTargets {
737 return (AttributeTargets) 0;
741 public override string[] ValidAttributeTargets {
743 return new string [0];
751 string IMemberContainer.Name {
755 MemberCache IMemberContainer.BaseCache {
759 bool IMemberContainer.IsInterface {
763 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
765 return FindMembers (mt, bf, null, null);
768 MemberCache IMemberContainer.MemberCache {
772 public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
773 MemberFilter filter, object criteria)
775 if (constraints == null)
776 return MemberList.Empty;
778 ArrayList members = new ArrayList ();
780 GenericConstraints gc = (GenericConstraints) constraints;
782 if (gc.HasClassConstraint) {
783 MemberList list = TypeManager.FindMembers (
784 gc.ClassConstraint, mt, bf, filter, criteria);
786 members.AddRange (list);
789 foreach (Type t in gc.InterfaceConstraints) {
790 MemberList list = TypeManager.FindMembers (
791 t, mt, bf, filter, criteria);
793 members.AddRange (list);
796 return new MemberList (members);
799 public bool IsSubclassOf (Type t)
804 if (constraints != null)
805 return constraints.IsSubclassOf (t);
810 public override string ToString ()
812 return "TypeParameter[" + name + "]";
815 protected class InflatedConstraints : GenericConstraints
817 GenericConstraints gc;
819 Type class_constraint;
820 Type[] iface_constraints;
823 public InflatedConstraints (GenericConstraints gc, Type declaring)
827 dargs = TypeManager.GetTypeArguments (declaring);
829 ArrayList list = new ArrayList ();
830 if (gc.HasClassConstraint)
831 list.Add (inflate (gc.ClassConstraint));
832 foreach (Type iface in gc.InterfaceConstraints)
833 list.Add (inflate (iface));
835 bool has_class_constr = false;
836 if (list.Count > 0) {
837 Type first = (Type) list [0];
838 has_class_constr = !first.IsInterface && !first.IsGenericParameter;
841 if ((list.Count > 0) && has_class_constr) {
842 class_constraint = (Type) list [0];
843 iface_constraints = new Type [list.Count - 1];
844 list.CopyTo (1, iface_constraints, 0, list.Count - 1);
846 iface_constraints = new Type [list.Count];
847 list.CopyTo (iface_constraints, 0);
850 if (HasValueTypeConstraint)
851 base_type = TypeManager.value_type;
852 else if (class_constraint != null)
853 base_type = class_constraint;
855 base_type = TypeManager.object_type;
858 Type inflate (Type t)
862 if (t.IsGenericParameter)
863 return dargs [t.GenericParameterPosition];
864 if (t.IsGenericInstance) {
865 t = t.GetGenericTypeDefinition ();
866 t = t.BindGenericParameters (dargs);
872 public override GenericParameterAttributes Attributes {
873 get { return gc.Attributes; }
876 public override Type ClassConstraint {
877 get { return class_constraint; }
880 public override Type EffectiveBaseClass {
881 get { return base_type; }
884 public override Type[] InterfaceConstraints {
885 get { return iface_constraints; }
891 // This type represents a generic type parameter reference.
893 // These expressions are born in a fully resolved state.
895 public class TypeParameterExpr : TypeExpr {
896 TypeParameter type_parameter;
898 public override string Name {
900 return type_parameter.Name;
904 public override string FullName {
906 return type_parameter.Name;
910 public TypeParameter TypeParameter {
912 return type_parameter;
916 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
918 this.type_parameter = type_parameter;
922 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
924 type = type_parameter.Type;
929 public override bool IsInterface {
930 get { return false; }
933 public override bool CheckAccessLevel (DeclSpace ds)
938 public void Error_CannotUseAsUnmanagedType (Location loc)
940 Report.Error (-203, loc, "Can not use type parameter as unamanged type");
944 public class TypeArguments {
945 public readonly Location Location;
952 public TypeArguments (Location loc)
954 args = new ArrayList ();
958 public TypeArguments (int dimension, Location loc)
960 this.dimension = dimension;
964 public void Add (Expression type)
967 throw new InvalidOperationException ();
972 public void Add (TypeArguments new_args)
975 throw new InvalidOperationException ();
977 args.AddRange (new_args.args);
980 public string[] GetDeclarations ()
982 string[] ret = new string [args.Count];
983 for (int i = 0; i < args.Count; i++) {
984 SimpleName sn = args [i] as SimpleName;
990 Report.Error (81, Location, "Type parameter declaration " +
991 "must be an identifier not a type");
997 public Type[] Arguments {
1003 public bool HasTypeArguments {
1005 return has_type_args;
1018 public bool IsUnbound {
1020 return dimension > 0;
1024 public override string ToString ()
1026 StringBuilder s = new StringBuilder ();
1029 for (int i = 0; i < count; i++){
1031 // FIXME: Use TypeManager.CSharpname once we have the type
1034 s.Append (args [i].ToString ());
1038 return s.ToString ();
1041 public bool Resolve (EmitContext ec)
1043 int count = args.Count;
1046 atypes = new Type [count];
1048 for (int i = 0; i < count; i++){
1049 TypeExpr te = ((Expression) args [i]).ResolveAsTypeTerminal (ec);
1054 if (te is TypeParameterExpr)
1055 has_type_args = true;
1057 if (te.Type.IsPointer) {
1058 Report.Error (306, Location, "The type `{0}' may not be used " +
1059 "as a type argument.", TypeManager.CSharpName (te.Type));
1063 atypes [i] = te.Type;
1069 public class ConstructedType : TypeExpr {
1071 FullNamedExpression name;
1073 Type[] gen_params, atypes;
1076 public ConstructedType (FullNamedExpression fname, TypeArguments args, Location l)
1082 eclass = ExprClass.Type;
1083 full_name = name + "<" + args.ToString () + ">";
1086 protected ConstructedType (TypeArguments args, Location l)
1091 eclass = ExprClass.Type;
1094 protected ConstructedType (TypeParameter[] type_params, Location l)
1098 args = new TypeArguments (l);
1099 foreach (TypeParameter type_param in type_params)
1100 args.Add (new TypeParameterExpr (type_param, l));
1102 eclass = ExprClass.Type;
1105 public ConstructedType (Type t, TypeParameter[] type_params, Location l)
1106 : this (type_params, l)
1108 gt = t.GetGenericTypeDefinition ();
1110 this.name = new TypeExpression (gt, l);
1111 full_name = gt.FullName + "<" + args.ToString () + ">";
1114 public ConstructedType (Type t, TypeArguments args, Location l)
1117 gt = t.GetGenericTypeDefinition ();
1119 this.name = new TypeExpression (gt, l);
1120 full_name = gt.FullName + "<" + args.ToString () + ">";
1123 public TypeArguments TypeArguments {
1124 get { return args; }
1127 protected string DeclarationName {
1129 StringBuilder sb = new StringBuilder ();
1130 sb.Append (gt.FullName);
1132 for (int i = 0; i < gen_params.Length; i++) {
1135 sb.Append (gen_params [i]);
1138 return sb.ToString ();
1142 protected bool CheckConstraint (EmitContext ec, Type ptype, Expression expr,
1145 if (TypeManager.HasGenericArguments (ctype)) {
1146 Type[] types = TypeManager.GetTypeArguments (ctype);
1148 TypeArguments new_args = new TypeArguments (loc);
1150 for (int i = 0; i < types.Length; i++) {
1153 if (t.IsGenericParameter) {
1154 int pos = t.GenericParameterPosition;
1155 t = args.Arguments [pos];
1157 new_args.Add (new TypeExpression (t, loc));
1160 TypeExpr ct = new ConstructedType (ctype, new_args, loc);
1161 if (ct.ResolveAsTypeTerminal (ec) == null)
1166 return Convert.ImplicitStandardConversionExists (ec, expr, ctype);
1169 protected bool CheckConstraints (EmitContext ec, int index)
1171 Type atype = atypes [index];
1172 Type ptype = gen_params [index];
1177 Expression aexpr = new EmptyExpression (atype);
1179 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1183 bool is_class, is_struct;
1184 if (atype.IsGenericParameter) {
1185 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1187 is_class = agc.HasReferenceTypeConstraint;
1188 is_struct = agc.HasValueTypeConstraint;
1190 is_class = is_struct = false;
1193 is_class = atype.IsClass;
1194 is_struct = atype.IsValueType;
1198 // First, check the `class' and `struct' constraints.
1200 if (gc.HasReferenceTypeConstraint && !is_class) {
1201 Report.Error (452, loc, "The type `{0}' must be " +
1202 "a reference type in order to use it " +
1203 "as type parameter `{1}' in the " +
1204 "generic type or method `{2}'.",
1205 atype, ptype, DeclarationName);
1207 } else if (gc.HasValueTypeConstraint && !is_struct) {
1208 Report.Error (453, loc, "The type `{0}' must be " +
1209 "a value type in order to use it " +
1210 "as type parameter `{1}' in the " +
1211 "generic type or method `{2}'.",
1212 atype, ptype, DeclarationName);
1217 // The class constraint comes next.
1219 if (gc.HasClassConstraint) {
1220 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint)) {
1221 Report.Error (309, loc, "The type `{0}' must be " +
1222 "convertible to `{1}' in order to " +
1223 "use it as parameter `{2}' in the " +
1224 "generic type or method `{3}'",
1225 atype, gc.ClassConstraint, ptype, DeclarationName);
1231 // Now, check the interface constraints.
1233 foreach (Type it in gc.InterfaceConstraints) {
1235 if (it.IsGenericParameter)
1236 itype = atypes [it.GenericParameterPosition];
1240 if (!CheckConstraint (ec, ptype, aexpr, itype)) {
1241 Report.Error (309, loc, "The type `{0}' must be " +
1242 "convertible to `{1}' in order to " +
1243 "use it as parameter `{2}' in the " +
1244 "generic type or method `{3}'",
1245 atype, itype, ptype, DeclarationName);
1251 // Finally, check the constructor constraint.
1254 if (!gc.HasConstructorConstraint)
1257 if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
1260 MethodGroupExpr mg = Expression.MemberLookup (
1261 ec, atype, ".ctor", MemberTypes.Constructor,
1262 BindingFlags.Public | BindingFlags.Instance |
1263 BindingFlags.DeclaredOnly, loc)
1266 if (atype.IsAbstract || (mg == null) || !mg.IsInstance) {
1267 Report.Error (310, loc, "The type `{0}' must have a public " +
1268 "parameterless constructor in order to use it " +
1269 "as parameter `{1}' in the generic type or " +
1270 "method `{2}'", atype, ptype, DeclarationName);
1277 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
1279 if (!ResolveConstructedType (ec))
1285 public bool CheckConstraints (EmitContext ec)
1287 for (int i = 0; i < gen_params.Length; i++) {
1288 if (!CheckConstraints (ec, i))
1295 public bool ResolveConstructedType (EmitContext ec)
1300 return DoResolveType (ec);
1306 Report.Error (246, loc, "Cannot find type `{0}'<...>", Name);
1310 num_args = TypeManager.GetNumberOfTypeArguments (t);
1311 if (num_args == 0) {
1312 Report.Error (308, loc,
1313 "The non-generic type `{0}' cannot " +
1314 "be used with type arguments.",
1315 TypeManager.CSharpName (t));
1319 gt = t.GetGenericTypeDefinition ();
1320 return DoResolveType (ec);
1323 bool DoResolveType (EmitContext ec)
1326 // Resolve the arguments.
1328 if (args.Resolve (ec) == false)
1331 gen_params = gt.GetGenericArguments ();
1332 atypes = args.Arguments;
1334 if (atypes.Length != gen_params.Length) {
1335 Report.Error (305, loc,
1336 "Using the generic type `{0}' " +
1337 "requires {1} type arguments",
1338 TypeManager.GetFullName (gt),
1344 // Now bind the parameters.
1346 type = gt.BindGenericParameters (atypes);
1350 public Expression GetSimpleName (EmitContext ec)
1355 public override bool CheckAccessLevel (DeclSpace ds)
1357 return ds.CheckAccessLevel (gt);
1360 public override bool AsAccessible (DeclSpace ds, int flags)
1362 return ds.AsAccessible (gt, flags);
1365 public override bool IsClass {
1366 get { return gt.IsClass; }
1369 public override bool IsValueType {
1370 get { return gt.IsValueType; }
1373 public override bool IsInterface {
1374 get { return gt.IsInterface; }
1377 public override bool IsSealed {
1378 get { return gt.IsSealed; }
1381 public override bool Equals (object obj)
1383 ConstructedType cobj = obj as ConstructedType;
1387 if ((type == null) || (cobj.type == null))
1390 return type == cobj.type;
1393 public override int GetHashCode ()
1395 return base.GetHashCode ();
1398 public override string Name {
1405 public override string FullName {
1412 public class GenericMethod : DeclSpace
1414 public GenericMethod (NamespaceEntry ns, TypeContainer parent,
1415 MemberName name, Location l)
1416 : base (ns, parent, name, null, l)
1419 public override TypeBuilder DefineType ()
1421 throw new Exception ();
1424 public override bool Define ()
1426 ec = new EmitContext (this, this, Location, null, null, ModFlags, false);
1428 for (int i = 0; i < TypeParameters.Length; i++)
1429 if (!TypeParameters [i].Resolve (this))
1435 public bool Define (MethodBuilder mb)
1437 GenericTypeParameterBuilder[] gen_params;
1438 string[] names = MemberName.TypeArguments.GetDeclarations ();
1439 gen_params = mb.DefineGenericParameters (names);
1440 for (int i = 0; i < TypeParameters.Length; i++)
1441 TypeParameters [i].Define (gen_params [i]);
1446 for (int i = 0; i < TypeParameters.Length; i++) {
1447 if (!TypeParameters [i].ResolveType (ec))
1454 public bool DefineType (EmitContext ec, MethodBuilder mb,
1455 MethodInfo implementing, bool is_override)
1457 for (int i = 0; i < TypeParameters.Length; i++)
1458 if (!TypeParameters [i].DefineType (
1459 ec, mb, implementing, is_override))
1465 public override bool DefineMembers (TypeContainer parent)
1470 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1471 MemberFilter filter, object criteria)
1473 throw new Exception ();
1476 public override MemberCache MemberCache {
1482 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1487 protected override void VerifyObsoleteAttribute()
1492 public override AttributeTargets AttributeTargets {
1494 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1498 public override string DocCommentHeader {
1499 get { return "M:"; }
1503 public class DefaultValueExpression : Expression
1506 LocalTemporary temp_storage;
1508 public DefaultValueExpression (Expression expr, Location loc)
1514 public override Expression DoResolve (EmitContext ec)
1516 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
1521 if (type.IsGenericParameter || TypeManager.IsValueType (type))
1522 temp_storage = new LocalTemporary (ec, type);
1524 eclass = ExprClass.Variable;
1528 public override void Emit (EmitContext ec)
1530 if (temp_storage != null) {
1531 temp_storage.AddressOf (ec, AddressOp.LoadStore);
1532 ec.ig.Emit (OpCodes.Initobj, type);
1533 temp_storage.Emit (ec);
1535 ec.ig.Emit (OpCodes.Ldnull);
1539 public class NullableType : TypeExpr
1541 Expression underlying;
1543 public NullableType (Expression underlying, Location l)
1545 this.underlying = underlying;
1548 eclass = ExprClass.Type;
1551 public NullableType (Type type, Location loc)
1552 : this (new TypeExpression (type, loc), loc)
1555 public override string Name {
1556 get { return underlying.ToString () + "?"; }
1559 public override string FullName {
1560 get { return underlying.ToString () + "?"; }
1563 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
1565 TypeArguments args = new TypeArguments (loc);
1566 args.Add (underlying);
1568 ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
1569 return ctype.ResolveAsTypeTerminal (ec);
1573 public partial class TypeManager
1576 // A list of core types that the compiler requires or uses
1578 static public Type new_constraint_attr_type;
1579 static public Type activator_type;
1580 static public Type generic_ienumerator_type;
1581 static public Type generic_ienumerable_type;
1582 static public Type generic_nullable_type;
1585 // Tracks the generic parameters.
1587 static PtrHashtable builder_to_type_param;
1590 // These methods are called by code generated by the compiler
1592 static public MethodInfo activator_create_instance;
1594 static void InitGenerics ()
1596 builder_to_type_param = new PtrHashtable ();
1599 static void CleanUpGenerics ()
1601 builder_to_type_param = null;
1604 static void InitGenericCoreTypes ()
1606 activator_type = CoreLookupType ("System.Activator");
1607 new_constraint_attr_type = CoreLookupType (
1608 "System.Runtime.CompilerServices.NewConstraintAttribute");
1610 generic_ienumerator_type = CoreLookupType ("System.Collections.Generic.IEnumerator", 1);
1611 generic_ienumerable_type = CoreLookupType ("System.Collections.Generic.IEnumerable", 1);
1612 generic_nullable_type = CoreLookupType ("System.Nullable", 1);
1615 static void InitGenericCodeHelpers ()
1618 Type [] type_arg = { type_type };
1619 activator_create_instance = GetMethod (
1620 activator_type, "CreateInstance", type_arg);
1623 static Type CoreLookupType (string name, int arity)
1625 return CoreLookupType (MemberName.MakeName (name, arity));
1628 public static void AddTypeParameter (Type t, TypeParameter tparam)
1630 if (!builder_to_type_param.Contains (t))
1631 builder_to_type_param.Add (t, tparam);
1634 public static TypeContainer LookupGenericTypeContainer (Type t)
1636 while (t.IsGenericInstance)
1637 t = t.GetGenericTypeDefinition ();
1639 return LookupTypeContainer (t);
1642 public static TypeParameter LookupTypeParameter (Type t)
1644 return (TypeParameter) builder_to_type_param [t];
1647 public static GenericConstraints GetTypeParameterConstraints (Type t)
1649 if (!t.IsGenericParameter)
1650 throw new InvalidOperationException ();
1652 TypeParameter tparam = LookupTypeParameter (t);
1654 return tparam.GenericConstraints;
1656 return new ReflectionConstraints (t);
1659 public static bool IsGeneric (Type t)
1661 DeclSpace ds = (DeclSpace) builder_to_declspace [t];
1663 return ds.IsGeneric;
1666 public static bool HasGenericArguments (Type t)
1668 return GetNumberOfTypeArguments (t) > 0;
1671 public static int GetNumberOfTypeArguments (Type t)
1673 DeclSpace tc = LookupDeclSpace (t);
1675 return tc.IsGeneric ? tc.CountTypeParameters : 0;
1677 return t.HasGenericArguments ? t.GetGenericArguments ().Length : 0;
1680 public static Type[] GetTypeArguments (Type t)
1682 DeclSpace tc = LookupDeclSpace (t);
1685 return Type.EmptyTypes;
1687 TypeParameter[] tparam = tc.TypeParameters;
1688 Type[] ret = new Type [tparam.Length];
1689 for (int i = 0; i < tparam.Length; i++) {
1690 ret [i] = tparam [i].Type;
1691 if (ret [i] == null)
1692 throw new InternalErrorException ();
1697 return t.GetGenericArguments ();
1701 // Whether `array' is an array of T and `enumerator' is `IEnumerable<T>'.
1702 // For instance "string[]" -> "IEnumerable<string>".
1704 public static bool IsIEnumerable (Type array, Type enumerator)
1706 if (!array.IsArray || !enumerator.IsGenericInstance)
1709 if (enumerator.GetGenericTypeDefinition () != generic_ienumerable_type)
1712 Type[] args = GetTypeArguments (enumerator);
1713 return args [0] == GetElementType (array);
1716 public static bool IsEqual (Type a, Type b)
1721 if ((a is TypeBuilder) && a.IsGenericTypeDefinition && b.IsGenericInstance) {
1723 // `a' is a generic type definition's TypeBuilder and `b' is a
1724 // generic instance of the same type.
1730 // void Test (Stack<T> stack) { }
1733 // The first argument of `Test' will be the generic instance
1734 // "Stack<!0>" - which is the same type than the "Stack" TypeBuilder.
1737 // We hit this via Closure.Filter() for gen-82.cs.
1739 if (a != b.GetGenericTypeDefinition ())
1742 Type[] aparams = a.GetGenericArguments ();
1743 Type[] bparams = b.GetGenericArguments ();
1745 if (aparams.Length != bparams.Length)
1748 for (int i = 0; i < aparams.Length; i++)
1749 if (!IsEqual (aparams [i], bparams [i]))
1755 if ((b is TypeBuilder) && b.IsGenericTypeDefinition && a.IsGenericInstance)
1756 return IsEqual (b, a);
1758 if (a.IsGenericParameter && b.IsGenericParameter) {
1759 if ((a.DeclaringMethod == null) || (b.DeclaringMethod == null))
1761 return a.GenericParameterPosition == b.GenericParameterPosition;
1764 if (a.IsArray && b.IsArray) {
1765 if (a.GetArrayRank () != b.GetArrayRank ())
1767 return IsEqual (a.GetElementType (), b.GetElementType ());
1770 if (a.IsGenericInstance && b.IsGenericInstance) {
1771 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
1774 Type[] aargs = a.GetGenericArguments ();
1775 Type[] bargs = b.GetGenericArguments ();
1777 if (aargs.Length != bargs.Length)
1780 for (int i = 0; i < aargs.Length; i++) {
1781 if (!IsEqual (aargs [i], bargs [i]))
1791 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_infered, Type[] method_infered)
1793 if (a.IsGenericParameter) {
1795 // If a is an array of a's type, they may never
1799 b = b.GetElementType ();
1805 // If b is a generic parameter or an actual type,
1806 // they may become equal:
1808 // class X<T,U> : I<T>, I<U>
1809 // class X<T> : I<T>, I<float>
1811 if (b.IsGenericParameter || !b.IsGenericInstance) {
1812 int pos = a.GenericParameterPosition;
1813 Type[] args = a.DeclaringMethod != null ? method_infered : class_infered;
1814 if (args [pos] == null) {
1819 return args [pos] == a;
1823 // We're now comparing a type parameter with a
1824 // generic instance. They may become equal unless
1825 // the type parameter appears anywhere in the
1826 // generic instance:
1828 // class X<T,U> : I<T>, I<X<U>>
1829 // -> error because you could instanciate it as
1832 // class X<T> : I<T>, I<X<T>> -> ok
1835 Type[] bargs = GetTypeArguments (b);
1836 for (int i = 0; i < bargs.Length; i++) {
1837 if (a.Equals (bargs [i]))
1844 if (b.IsGenericParameter)
1845 return MayBecomeEqualGenericTypes (b, a, class_infered, method_infered);
1848 // At this point, neither a nor b are a type parameter.
1850 // If one of them is a generic instance, let
1851 // MayBecomeEqualGenericInstances() compare them (if the
1852 // other one is not a generic instance, they can never
1856 if (a.IsGenericInstance || b.IsGenericInstance)
1857 return MayBecomeEqualGenericInstances (a, b, class_infered, method_infered);
1860 // If both of them are arrays.
1863 if (a.IsArray && b.IsArray) {
1864 if (a.GetArrayRank () != b.GetArrayRank ())
1867 a = a.GetElementType ();
1868 b = b.GetElementType ();
1870 return MayBecomeEqualGenericTypes (a, b, class_infered, method_infered);
1874 // Ok, two ordinary types.
1877 return a.Equals (b);
1881 // Checks whether two generic instances may become equal for some
1882 // particular instantiation (26.3.1).
1884 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
1885 Type[] class_infered, Type[] method_infered)
1887 if (!a.IsGenericInstance || !b.IsGenericInstance)
1889 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
1892 return MayBecomeEqualGenericInstances (
1893 GetTypeArguments (a), GetTypeArguments (b), class_infered, method_infered);
1896 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
1897 Type[] class_infered, Type[] method_infered)
1899 if (aargs.Length != bargs.Length)
1902 for (int i = 0; i < aargs.Length; i++) {
1903 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_infered, method_infered))
1910 public static bool IsEqualGenericInstance (Type type, Type parent)
1912 int tcount = GetNumberOfTypeArguments (type);
1913 int pcount = GetNumberOfTypeArguments (parent);
1915 if (type.IsGenericInstance)
1916 type = type.GetGenericTypeDefinition ();
1917 if (parent.IsGenericInstance)
1918 parent = parent.GetGenericTypeDefinition ();
1920 if (tcount != pcount)
1923 return type.Equals (parent);
1926 static public bool IsGenericMethod (MethodBase mb)
1928 if (mb.DeclaringType is TypeBuilder) {
1929 IMethodData method = (IMethodData) builder_to_method [mb];
1933 return method.GenericMethod != null;
1936 return mb.IsGenericMethodDefinition;
1943 static bool InferType (Type pt, Type at, Type[] infered)
1945 if (pt.IsGenericParameter && (pt.DeclaringMethod != null)) {
1946 int pos = pt.GenericParameterPosition;
1948 if (infered [pos] == null) {
1950 while (check.IsArray)
1951 check = check.GetElementType ();
1960 if (infered [pos] != at)
1966 if (!pt.ContainsGenericParameters) {
1967 if (at.ContainsGenericParameters)
1968 return InferType (at, pt, infered);
1975 (at.GetArrayRank () != pt.GetArrayRank ()))
1978 return InferType (pt.GetElementType (), at.GetElementType (), infered);
1983 (pt.GetArrayRank () != at.GetArrayRank ()))
1986 return InferType (pt.GetElementType (), at.GetElementType (), infered);
1989 if (pt.IsByRef && at.IsByRef)
1990 return InferType (pt.GetElementType (), at.GetElementType (), infered);
1991 ArrayList list = new ArrayList ();
1992 if (at.IsGenericInstance)
1995 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
1998 list.AddRange (TypeManager.GetInterfaces (at));
2001 bool found_one = false;
2003 foreach (Type type in list) {
2004 if (!type.IsGenericInstance)
2007 Type[] infered_types = new Type [infered.Length];
2009 if (!InferGenericInstance (pt, type, infered_types))
2012 for (int i = 0; i < infered_types.Length; i++) {
2013 if (infered [i] == null) {
2014 infered [i] = infered_types [i];
2018 if (infered [i] != infered_types [i])
2028 static bool InferGenericInstance (Type pt, Type at, Type[] infered_types)
2030 Type[] at_args = at.GetGenericArguments ();
2031 Type[] pt_args = pt.GetGenericArguments ();
2033 if (at_args.Length != pt_args.Length)
2036 for (int i = 0; i < at_args.Length; i++) {
2037 if (!InferType (pt_args [i], at_args [i], infered_types))
2041 for (int i = 0; i < infered_types.Length; i++) {
2042 if (infered_types [i] == null)
2049 public static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
2050 ref MethodBase method)
2052 if ((arguments == null) || !TypeManager.IsGenericMethod (method))
2057 if (arguments == null)
2060 arg_count = arguments.Count;
2062 ParameterData pd = TypeManager.GetParameterData (method);
2064 int pd_count = pd.Count;
2069 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2072 if (pd_count - 1 > arg_count)
2075 if (pd_count == 1 && arg_count == 0)
2078 Type[] method_args = method.GetGenericArguments ();
2079 Type[] infered_types = new Type [method_args.Length];
2082 // If we have come this far, the case which
2083 // remains is when the number of parameters is
2084 // less than or equal to the argument count.
2086 for (int i = 0; i < pd_count - 1; ++i) {
2087 Argument a = (Argument) arguments [i];
2089 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2092 Type pt = pd.ParameterType (i);
2095 if (!InferType (pt, at, infered_types))
2099 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
2101 for (int i = pd_count - 1; i < arg_count; i++) {
2102 Argument a = (Argument) arguments [i];
2104 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2107 if (!InferType (element_type, a.Type, infered_types))
2111 for (int i = 0; i < infered_types.Length; i++)
2112 if (infered_types [i] == null)
2115 method = method.BindGenericParameters (infered_types);
2119 public static bool InferTypeArguments (Type[] param_types, Type[] arg_types, Type[] infered_types)
2121 if (infered_types == null)
2124 for (int i = 0; i < arg_types.Length; i++) {
2125 if (arg_types [i] == null)
2128 if (!InferType (param_types [i], arg_types [i], infered_types))
2132 for (int i = 0; i < infered_types.Length; i++)
2133 if (infered_types [i] == null)
2139 public static bool InferTypeArguments (EmitContext ec, ArrayList arguments,
2140 ref MethodBase method)
2142 if (!TypeManager.IsGenericMethod (method))
2146 if (arguments != null)
2147 arg_count = arguments.Count;
2151 ParameterData pd = TypeManager.GetParameterData (method);
2152 if (arg_count != pd.Count)
2155 Type[] method_args = method.GetGenericArguments ();
2157 bool is_open = false;
2158 for (int i = 0; i < method_args.Length; i++) {
2159 if (method_args [i].IsGenericParameter) {
2167 Type[] infered_types = new Type [method_args.Length];
2169 Type[] param_types = new Type [pd.Count];
2170 Type[] arg_types = new Type [pd.Count];
2172 for (int i = 0; i < arg_count; i++) {
2173 param_types [i] = pd.ParameterType (i);
2175 Argument a = (Argument) arguments [i];
2176 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2179 arg_types [i] = a.Type;
2182 if (!InferTypeArguments (param_types, arg_types, infered_types))
2185 method = method.BindGenericParameters (infered_types);
2189 public static bool InferTypeArguments (EmitContext ec, ParameterData apd,
2190 ref MethodBase method)
2192 if (!TypeManager.IsGenericMethod (method))
2195 ParameterData pd = TypeManager.GetParameterData (method);
2196 if (apd.Count != pd.Count)
2199 Type[] method_args = method.GetGenericArguments ();
2200 Type[] infered_types = new Type [method_args.Length];
2202 Type[] param_types = new Type [pd.Count];
2203 Type[] arg_types = new Type [pd.Count];
2205 for (int i = 0; i < apd.Count; i++) {
2206 param_types [i] = pd.ParameterType (i);
2207 arg_types [i] = apd.ParameterType (i);
2210 if (!InferTypeArguments (param_types, arg_types, infered_types))
2213 method = method.BindGenericParameters (infered_types);
2217 public static bool IsNullableType (Type t)
2219 if (!t.IsGenericInstance)
2222 Type gt = t.GetGenericTypeDefinition ();
2223 return gt == generic_nullable_type;
2227 public abstract class Nullable
2229 protected sealed class NullableInfo
2231 public readonly Type Type;
2232 public readonly Type UnderlyingType;
2233 public readonly MethodInfo HasValue;
2234 public readonly MethodInfo Value;
2235 public readonly ConstructorInfo Constructor;
2237 public NullableInfo (Type type)
2240 UnderlyingType = TypeManager.GetTypeArguments (type) [0];
2242 PropertyInfo has_value_pi = type.GetProperty ("HasValue");
2243 PropertyInfo value_pi = type.GetProperty ("Value");
2245 HasValue = has_value_pi.GetGetMethod (false);
2246 Value = value_pi.GetGetMethod (false);
2247 Constructor = type.GetConstructor (new Type[] { UnderlyingType });
2251 protected class Unwrap : Expression, IMemoryLocation, IAssignMethod
2256 LocalTemporary temp;
2259 public Unwrap (Expression expr, Location loc)
2265 public override Expression DoResolve (EmitContext ec)
2267 expr = expr.Resolve (ec);
2271 if (!(expr is IMemoryLocation))
2272 temp = new LocalTemporary (ec, expr.Type);
2274 info = new NullableInfo (expr.Type);
2275 type = info.UnderlyingType;
2276 eclass = expr.eclass;
2280 public override void Emit (EmitContext ec)
2282 AddressOf (ec, AddressOp.LoadStore);
2283 ec.ig.EmitCall (OpCodes.Call, info.Value, null);
2286 public void EmitCheck (EmitContext ec)
2288 AddressOf (ec, AddressOp.LoadStore);
2289 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
2292 void create_temp (EmitContext ec)
2294 if ((temp != null) && !has_temp) {
2301 public void AddressOf (EmitContext ec, AddressOp mode)
2305 temp.AddressOf (ec, AddressOp.LoadStore);
2307 ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
2310 public void Emit (EmitContext ec, bool leave_copy)
2323 public void EmitAssign (EmitContext ec, Expression source,
2324 bool leave_copy, bool prepare_for_load)
2327 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2330 ec.ig.Emit (OpCodes.Dup);
2332 Expression empty = new EmptyExpression (expr.Type);
2333 ((IAssignMethod) expr).EmitAssign (ec, empty, false, prepare_for_load);
2337 protected class Wrap : Expression
2342 public Wrap (Expression expr, Location loc)
2348 public override Expression DoResolve (EmitContext ec)
2350 expr = expr.Resolve (ec);
2354 TypeExpr target_type = new NullableType (expr.Type, loc);
2355 target_type = target_type.ResolveAsTypeTerminal (ec);
2356 if (target_type == null)
2359 type = target_type.Type;
2360 info = new NullableInfo (type);
2361 eclass = ExprClass.Value;
2365 public override void Emit (EmitContext ec)
2368 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2372 public class NullableLiteral : Expression, IMemoryLocation {
2373 public NullableLiteral (Type target_type, Location loc)
2375 this.type = target_type;
2378 eclass = ExprClass.Value;
2381 public override Expression DoResolve (EmitContext ec)
2386 public override void Emit (EmitContext ec)
2388 LocalTemporary value_target = new LocalTemporary (ec, type);
2390 value_target.AddressOf (ec, AddressOp.Store);
2391 ec.ig.Emit (OpCodes.Initobj, type);
2392 value_target.Emit (ec);
2395 public void AddressOf (EmitContext ec, AddressOp Mode)
2397 LocalTemporary value_target = new LocalTemporary (ec, type);
2399 value_target.AddressOf (ec, AddressOp.Store);
2400 ec.ig.Emit (OpCodes.Initobj, type);
2401 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
2405 public abstract class Lifted : Expression, IMemoryLocation
2407 Expression expr, underlying, wrap, null_value;
2410 protected Lifted (Expression expr, Location loc)
2416 public override Expression DoResolve (EmitContext ec)
2418 expr = expr.Resolve (ec);
2422 unwrap = (Unwrap) new Unwrap (expr, loc).Resolve (ec);
2426 underlying = ResolveUnderlying (unwrap, ec);
2427 if (underlying == null)
2430 wrap = new Wrap (underlying, loc).Resolve (ec);
2434 null_value = new NullableLiteral (wrap.Type, loc).Resolve (ec);
2435 if (null_value == null)
2439 eclass = ExprClass.Value;
2443 protected abstract Expression ResolveUnderlying (Expression unwrap, EmitContext ec);
2445 public override void Emit (EmitContext ec)
2447 ILGenerator ig = ec.ig;
2448 Label is_null_label = ig.DefineLabel ();
2449 Label end_label = ig.DefineLabel ();
2451 unwrap.EmitCheck (ec);
2452 ig.Emit (OpCodes.Brfalse, is_null_label);
2455 ig.Emit (OpCodes.Br, end_label);
2457 ig.MarkLabel (is_null_label);
2458 null_value.Emit (ec);
2460 ig.MarkLabel (end_label);
2463 public void AddressOf (EmitContext ec, AddressOp mode)
2465 unwrap.AddressOf (ec, mode);
2469 public class LiftedConversion : Lifted
2471 public readonly bool IsUser;
2472 public readonly bool IsExplicit;
2473 public readonly Type TargetType;
2475 public LiftedConversion (Expression expr, Type target_type, bool is_user,
2476 bool is_explicit, Location loc)
2479 this.IsUser = is_user;
2480 this.IsExplicit = is_explicit;
2481 this.TargetType = target_type;
2484 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2486 Type type = TypeManager.GetTypeArguments (TargetType) [0];
2489 return Convert.UserDefinedConversion (ec, unwrap, type, loc, IsExplicit);
2492 return Convert.ExplicitConversion (ec, unwrap, type, loc);
2494 return Convert.ImplicitConversion (ec, unwrap, type, loc);
2499 public class LiftedUnaryOperator : Lifted
2501 public readonly Unary.Operator Oper;
2503 public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
2509 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2511 return new Unary (Oper, unwrap, loc);
2515 public class LiftedConditional : Lifted
2517 Expression true_expr, false_expr;
2519 public LiftedConditional (Expression expr, Expression true_expr, Expression false_expr,
2523 this.true_expr = true_expr;
2524 this.false_expr = false_expr;
2527 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2529 return new Conditional (unwrap, true_expr, false_expr, loc);
2533 public class LiftedBinaryOperator : Expression
2535 public readonly Binary.Operator Oper;
2537 Expression left, right, underlying, null_value, bool_wrap;
2538 Unwrap left_unwrap, right_unwrap;
2539 bool is_equality, is_comparision, is_boolean;
2541 public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
2550 public override Expression DoResolve (EmitContext ec)
2552 if (TypeManager.IsNullableType (left.Type)) {
2553 left_unwrap = new Unwrap (left, loc);
2554 left = left_unwrap.Resolve (ec);
2559 if (TypeManager.IsNullableType (right.Type)) {
2560 right_unwrap = new Unwrap (right, loc);
2561 right = right_unwrap.Resolve (ec);
2566 if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr) ||
2567 (Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr)) &&
2568 ((left.Type == TypeManager.bool_type) && (right.Type == TypeManager.bool_type))) {
2569 Expression empty = new EmptyExpression (TypeManager.bool_type);
2570 bool_wrap = new Wrap (empty, loc).Resolve (ec);
2571 null_value = new NullableLiteral (bool_wrap.Type, loc).Resolve (ec);
2573 type = bool_wrap.Type;
2575 } else if ((Oper == Binary.Operator.Equality) || (Oper == Binary.Operator.Inequality)) {
2576 if (!(left is NullLiteral) && !(right is NullLiteral)) {
2577 underlying = new Binary (Oper, left, right, loc).Resolve (ec);
2578 if (underlying == null)
2582 type = TypeManager.bool_type;
2584 } else if ((Oper == Binary.Operator.LessThan) ||
2585 (Oper == Binary.Operator.GreaterThan) ||
2586 (Oper == Binary.Operator.LessThanOrEqual) ||
2587 (Oper == Binary.Operator.GreaterThanOrEqual)) {
2588 underlying = new Binary (Oper, left, right, loc).Resolve (ec);
2589 if (underlying == null)
2592 type = TypeManager.bool_type;
2593 is_comparision = true;
2595 underlying = new Binary (Oper, left, right, loc).Resolve (ec);
2596 if (underlying == null)
2599 underlying = new Wrap (underlying, loc).Resolve (ec);
2600 if (underlying == null)
2603 type = underlying.Type;
2604 null_value = new NullableLiteral (type, loc).Resolve (ec);
2607 eclass = ExprClass.Value;
2611 void EmitBoolean (EmitContext ec)
2613 ILGenerator ig = ec.ig;
2615 Label left_is_null_label = ig.DefineLabel ();
2616 Label right_is_null_label = ig.DefineLabel ();
2617 Label is_null_label = ig.DefineLabel ();
2618 Label wrap_label = ig.DefineLabel ();
2619 Label end_label = ig.DefineLabel ();
2621 if (left_unwrap != null) {
2622 left_unwrap.EmitCheck (ec);
2623 ig.Emit (OpCodes.Brfalse, left_is_null_label);
2627 ig.Emit (OpCodes.Dup);
2628 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
2629 ig.Emit (OpCodes.Brtrue, wrap_label);
2631 ig.Emit (OpCodes.Brfalse, wrap_label);
2633 if (right_unwrap != null) {
2634 right_unwrap.EmitCheck (ec);
2635 ig.Emit (OpCodes.Brfalse, right_is_null_label);
2638 if ((Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr))
2639 ig.Emit (OpCodes.Pop);
2642 if (Oper == Binary.Operator.BitwiseOr)
2643 ig.Emit (OpCodes.Or);
2644 else if (Oper == Binary.Operator.BitwiseAnd)
2645 ig.Emit (OpCodes.And);
2646 ig.Emit (OpCodes.Br, wrap_label);
2648 ig.MarkLabel (left_is_null_label);
2649 if (right_unwrap != null) {
2650 right_unwrap.EmitCheck (ec);
2651 ig.Emit (OpCodes.Brfalse, is_null_label);
2655 ig.Emit (OpCodes.Dup);
2656 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
2657 ig.Emit (OpCodes.Brtrue, wrap_label);
2659 ig.Emit (OpCodes.Brfalse, wrap_label);
2661 ig.MarkLabel (right_is_null_label);
2662 ig.Emit (OpCodes.Pop);
2663 ig.MarkLabel (is_null_label);
2664 null_value.Emit (ec);
2665 ig.Emit (OpCodes.Br, end_label);
2667 ig.MarkLabel (wrap_label);
2668 ig.Emit (OpCodes.Nop);
2669 bool_wrap.Emit (ec);
2670 ig.Emit (OpCodes.Nop);
2672 ig.MarkLabel (end_label);
2675 void EmitEquality (EmitContext ec)
2677 ILGenerator ig = ec.ig;
2679 Label left_not_null_label = ig.DefineLabel ();
2680 Label false_label = ig.DefineLabel ();
2681 Label true_label = ig.DefineLabel ();
2682 Label end_label = ig.DefineLabel ();
2684 if (left_unwrap != null) {
2685 left_unwrap.EmitCheck (ec);
2686 if (right is NullLiteral) {
2687 if (Oper == Binary.Operator.Equality)
2688 ig.Emit (OpCodes.Brfalse, true_label);
2690 ig.Emit (OpCodes.Brfalse, false_label);
2691 } else if (right_unwrap != null) {
2692 ig.Emit (OpCodes.Dup);
2693 ig.Emit (OpCodes.Brtrue, left_not_null_label);
2694 right_unwrap.EmitCheck (ec);
2695 ig.Emit (OpCodes.Ceq);
2696 if (Oper == Binary.Operator.Inequality) {
2697 ig.Emit (OpCodes.Ldc_I4_0);
2698 ig.Emit (OpCodes.Ceq);
2700 ig.Emit (OpCodes.Br, end_label);
2702 ig.MarkLabel (left_not_null_label);
2703 ig.Emit (OpCodes.Pop);
2705 if (Oper == Binary.Operator.Equality)
2706 ig.Emit (OpCodes.Brfalse, false_label);
2708 ig.Emit (OpCodes.Brfalse, true_label);
2712 if (right_unwrap != null) {
2713 right_unwrap.EmitCheck (ec);
2714 if (left is NullLiteral) {
2715 if (Oper == Binary.Operator.Equality)
2716 ig.Emit (OpCodes.Brfalse, true_label);
2718 ig.Emit (OpCodes.Brfalse, false_label);
2720 if (Oper == Binary.Operator.Equality)
2721 ig.Emit (OpCodes.Brfalse, false_label);
2723 ig.Emit (OpCodes.Brfalse, true_label);
2727 bool left_is_null = left is NullLiteral;
2728 bool right_is_null = right is NullLiteral;
2729 if (left_is_null || right_is_null) {
2730 if (((Oper == Binary.Operator.Equality) && (left_is_null == right_is_null)) ||
2731 ((Oper == Binary.Operator.Inequality) && (left_is_null != right_is_null)))
2732 ig.Emit (OpCodes.Br, true_label);
2734 ig.Emit (OpCodes.Br, false_label);
2736 underlying.Emit (ec);
2737 ig.Emit (OpCodes.Br, end_label);
2740 ig.MarkLabel (false_label);
2741 ig.Emit (OpCodes.Ldc_I4_0);
2742 ig.Emit (OpCodes.Br, end_label);
2744 ig.MarkLabel (true_label);
2745 ig.Emit (OpCodes.Ldc_I4_1);
2747 ig.MarkLabel (end_label);
2750 void EmitComparision (EmitContext ec)
2752 ILGenerator ig = ec.ig;
2754 Label is_null_label = ig.DefineLabel ();
2755 Label end_label = ig.DefineLabel ();
2757 if (left_unwrap != null) {
2758 left_unwrap.EmitCheck (ec);
2759 ig.Emit (OpCodes.Brfalse, is_null_label);
2762 if (right_unwrap != null) {
2763 right_unwrap.EmitCheck (ec);
2764 ig.Emit (OpCodes.Brfalse, is_null_label);
2767 underlying.Emit (ec);
2768 ig.Emit (OpCodes.Br, end_label);
2770 ig.MarkLabel (is_null_label);
2771 ig.Emit (OpCodes.Ldc_I4_0);
2773 ig.MarkLabel (end_label);
2776 public override void Emit (EmitContext ec)
2781 } else if (is_equality) {
2784 } else if (is_comparision) {
2785 EmitComparision (ec);
2789 ILGenerator ig = ec.ig;
2791 Label is_null_label = ig.DefineLabel ();
2792 Label end_label = ig.DefineLabel ();
2794 if (left_unwrap != null) {
2795 left_unwrap.EmitCheck (ec);
2796 ig.Emit (OpCodes.Brfalse, is_null_label);
2799 if (right_unwrap != null) {
2800 right_unwrap.EmitCheck (ec);
2801 ig.Emit (OpCodes.Brfalse, is_null_label);
2804 underlying.Emit (ec);
2805 ig.Emit (OpCodes.Br, end_label);
2807 ig.MarkLabel (is_null_label);
2808 null_value.Emit (ec);
2810 ig.MarkLabel (end_label);
2814 public class OperatorTrueOrFalse : Expression
2816 public readonly bool IsTrue;
2821 public OperatorTrueOrFalse (Expression expr, bool is_true, Location loc)
2823 this.IsTrue = is_true;
2828 public override Expression DoResolve (EmitContext ec)
2830 unwrap = new Unwrap (expr, loc);
2831 expr = unwrap.Resolve (ec);
2835 if (unwrap.Type != TypeManager.bool_type)
2838 type = TypeManager.bool_type;
2839 eclass = ExprClass.Value;
2843 public override void Emit (EmitContext ec)
2845 ILGenerator ig = ec.ig;
2847 Label is_null_label = ig.DefineLabel ();
2848 Label end_label = ig.DefineLabel ();
2850 unwrap.EmitCheck (ec);
2851 ig.Emit (OpCodes.Brfalse, is_null_label);
2855 ig.Emit (OpCodes.Ldc_I4_0);
2856 ig.Emit (OpCodes.Ceq);
2858 ig.Emit (OpCodes.Br, end_label);
2860 ig.MarkLabel (is_null_label);
2861 ig.Emit (OpCodes.Ldc_I4_0);
2863 ig.MarkLabel (end_label);
2867 public class NullCoalescingOperator : Expression
2869 Expression left, right;
2873 public NullCoalescingOperator (Expression left, Expression right, Location loc)
2879 eclass = ExprClass.Value;
2882 public override Expression DoResolve (EmitContext ec)
2887 left = left.Resolve (ec);
2891 right = right.Resolve (ec);
2895 Type ltype = left.Type, rtype = right.Type;
2897 if (!TypeManager.IsNullableType (ltype) && ltype.IsValueType) {
2898 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
2902 if (TypeManager.IsNullableType (ltype)) {
2903 NullableInfo info = new NullableInfo (ltype);
2905 unwrap = (Unwrap) new Unwrap (left, loc).Resolve (ec);
2909 expr = Convert.ImplicitConversion (ec, right, info.UnderlyingType, loc);
2917 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
2923 if (unwrap != null) {
2924 expr = Convert.ImplicitConversion (ec, unwrap, rtype, loc);
2933 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
2937 public override void Emit (EmitContext ec)
2939 ILGenerator ig = ec.ig;
2941 Label is_null_label = ig.DefineLabel ();
2942 Label end_label = ig.DefineLabel ();
2944 if (unwrap != null) {
2945 unwrap.EmitCheck (ec);
2946 ig.Emit (OpCodes.Brfalse, is_null_label);
2950 ig.Emit (OpCodes.Br, end_label);
2952 ig.MarkLabel (is_null_label);
2955 ig.MarkLabel (end_label);
2959 public class LiftedUnaryMutator : ExpressionStatement
2961 public readonly UnaryMutator.Mode Mode;
2962 Expression expr, null_value;
2963 UnaryMutator underlying;
2966 public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
2972 eclass = ExprClass.Value;
2975 public override Expression DoResolve (EmitContext ec)
2977 expr = expr.Resolve (ec);
2981 unwrap = (Unwrap) new Unwrap (expr, loc).Resolve (ec);
2985 underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
2986 if (underlying == null)
2989 null_value = new NullableLiteral (expr.Type, loc).Resolve (ec);
2990 if (null_value == null)
2997 void DoEmit (EmitContext ec, bool is_expr)
2999 ILGenerator ig = ec.ig;
3000 Label is_null_label = ig.DefineLabel ();
3001 Label end_label = ig.DefineLabel ();
3003 unwrap.EmitCheck (ec);
3004 ig.Emit (OpCodes.Brfalse, is_null_label);
3007 underlying.Emit (ec);
3009 underlying.EmitStatement (ec);
3010 ig.Emit (OpCodes.Br, end_label);
3012 ig.MarkLabel (is_null_label);
3014 null_value.Emit (ec);
3016 ig.MarkLabel (end_label);
3019 public override void Emit (EmitContext ec)
3024 public override void EmitStatement (EmitContext ec)