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 int errors = Report.Errors;
203 FullNamedExpression fn = ((Expression) obj).ResolveAsTypeStep (ec);
206 if (errors != Report.Errors)
209 Report.Error (246, loc, "Cannot find type '{0}'", obj);
214 ConstructedType cexpr = fn as ConstructedType;
216 if (!cexpr.ResolveConstructedType (ec))
221 expr = fn.ResolveAsTypeTerminal (ec);
226 TypeParameterExpr texpr = expr as TypeParameterExpr;
228 type_param_constraints.Add (expr);
229 else if (expr.IsInterface)
230 iface_constraints.Add (expr);
231 else if (class_constraint != null) {
232 Report.Error (406, loc,
233 "`{0}': the class constraint for `{1}' " +
234 "must come before any other constraints.",
237 } else if (HasReferenceTypeConstraint || HasValueTypeConstraint) {
238 Report.Error (450, loc, "`{0}': cannot specify both " +
239 "a constraint class and the `class' " +
240 "or `struct' constraint.", expr.Name);
243 class_constraint = expr;
251 bool CheckTypeParameterConstraints (TypeParameter tparam, Hashtable seen)
253 seen.Add (tparam, true);
255 Constraints constraints = tparam.Constraints;
256 if (constraints == null)
259 if (constraints.HasValueTypeConstraint) {
260 Report.Error (456, loc, "Type parameter `{0}' has " +
261 "the `struct' constraint, so it cannot " +
262 "be used as a constraint for `{1}'",
267 if (constraints.type_param_constraints == null)
270 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
271 if (seen.Contains (expr.TypeParameter)) {
272 Report.Error (454, loc, "Circular constraint " +
273 "dependency involving `{0}' and `{1}'",
274 tparam.Name, expr.Name);
278 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
285 public bool ResolveTypes (EmitContext ec)
287 if (effective_base_type != null)
290 foreach (object obj in constraints) {
291 ConstructedType cexpr = obj as ConstructedType;
295 if (!cexpr.CheckConstraints (ec))
299 foreach (TypeParameterExpr expr in type_param_constraints) {
300 Hashtable seen = new Hashtable ();
301 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
305 ArrayList list = new ArrayList ();
307 foreach (TypeExpr iface_constraint in iface_constraints) {
308 foreach (Type type in list) {
309 if (!type.Equals (iface_constraint.Type))
312 Report.Error (405, loc,
313 "Duplicate constraint `{0}' for type " +
314 "parameter `{1}'.", iface_constraint.Type,
319 TypeExpr te = iface_constraint.ResolveAsTypeTerminal (ec);
326 foreach (TypeParameterExpr expr in type_param_constraints) {
327 foreach (Type type in list) {
328 if (!type.Equals (expr.Type))
331 Report.Error (405, loc,
332 "Duplicate constraint `{0}' for type " +
333 "parameter `{1}'.", expr.Type, name);
337 list.Add (expr.Type);
340 ArrayList new_list = new ArrayList ();
341 foreach (Type iface in list) {
342 if (new_list.Contains (iface))
345 new_list.Add (iface);
347 Type [] implementing = TypeManager.GetInterfaces (iface);
349 foreach (Type imp in implementing) {
350 if (!new_list.Contains (imp))
355 iface_constraint_types = new Type [new_list.Count];
356 new_list.CopyTo (iface_constraint_types, 0);
358 if (class_constraint != null) {
359 TypeExpr te = class_constraint.ResolveAsTypeTerminal (ec);
363 class_constraint_type = te.Type;
364 if (class_constraint_type == null)
367 if (class_constraint_type.IsSealed) {
368 Report.Error (701, loc,
369 "`{0}' is not a valid bound. Bounds " +
370 "must be interfaces or non sealed " +
371 "classes", class_constraint_type);
375 if ((class_constraint_type == TypeManager.array_type) ||
376 (class_constraint_type == TypeManager.delegate_type) ||
377 (class_constraint_type == TypeManager.enum_type) ||
378 (class_constraint_type == TypeManager.value_type) ||
379 (class_constraint_type == TypeManager.object_type)) {
380 Report.Error (702, loc,
381 "Bound cannot be special class `{0}'",
382 class_constraint_type);
387 if (class_constraint_type != null)
388 effective_base_type = class_constraint_type;
389 else if (HasValueTypeConstraint)
390 effective_base_type = TypeManager.value_type;
392 effective_base_type = TypeManager.object_type;
397 public bool CheckDependencies (EmitContext ec)
399 foreach (TypeParameterExpr expr in type_param_constraints) {
400 if (!CheckDependencies (expr.TypeParameter, ec))
407 bool CheckDependencies (TypeParameter tparam, EmitContext ec)
409 Constraints constraints = tparam.Constraints;
410 if (constraints == null)
413 if (HasValueTypeConstraint && constraints.HasClassConstraint) {
414 Report.Error (455, loc, "Type parameter `{0}' inherits " +
415 "conflicting constraints `{1}' and `{2}'",
416 name, constraints.ClassConstraint,
421 if (HasClassConstraint && constraints.HasClassConstraint) {
422 Type t1 = ClassConstraint;
423 TypeExpr e1 = class_constraint;
424 Type t2 = constraints.ClassConstraint;
425 TypeExpr e2 = constraints.class_constraint;
427 if (!Convert.ImplicitReferenceConversionExists (ec, e1, t2) &&
428 !Convert.ImplicitReferenceConversionExists (ec, e2, t1)) {
429 Report.Error (455, loc,
430 "Type parameter `{0}' inherits " +
431 "conflicting constraints `{1}' and `{2}'",
437 if (constraints.type_param_constraints == null)
440 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
441 if (!CheckDependencies (expr.TypeParameter, ec))
448 public void Define (GenericTypeParameterBuilder type)
450 type.SetGenericParameterAttributes (attrs);
453 public override GenericParameterAttributes Attributes {
454 get { return attrs; }
457 public override bool HasClassConstraint {
458 get { return class_constraint != null; }
461 public override Type ClassConstraint {
462 get { return class_constraint_type; }
465 public override Type[] InterfaceConstraints {
466 get { return iface_constraint_types; }
469 public override Type EffectiveBaseClass {
470 get { return effective_base_type; }
473 internal bool IsSubclassOf (Type t)
475 if ((class_constraint_type != null) &&
476 class_constraint_type.IsSubclassOf (t))
479 if (iface_constraint_types == null)
482 foreach (Type iface in iface_constraint_types) {
483 if (TypeManager.IsSubclassOf (iface, t))
490 public bool CheckInterfaceMethod (EmitContext ec, GenericConstraints gc)
492 if (gc.Attributes != attrs)
495 if (HasClassConstraint != gc.HasClassConstraint)
497 if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
500 int gc_icount = gc.InterfaceConstraints != null ?
501 gc.InterfaceConstraints.Length : 0;
502 int icount = InterfaceConstraints != null ?
503 InterfaceConstraints.Length : 0;
505 if (gc_icount != icount)
508 foreach (Type iface in gc.InterfaceConstraints) {
510 foreach (Type check in InterfaceConstraints) {
511 if (TypeManager.IsEqual (iface, check)) {
526 // This type represents a generic type parameter
528 public class TypeParameter : MemberCore, IMemberContainer {
530 GenericConstraints gc;
531 Constraints constraints;
533 GenericTypeParameterBuilder type;
535 public TypeParameter (TypeContainer parent, string name,
536 Constraints constraints, Location loc)
537 : base (parent, new MemberName (name), null, loc)
540 this.constraints = constraints;
544 public GenericConstraints GenericConstraints {
546 return gc != null ? gc : constraints;
550 public Constraints Constraints {
556 public bool HasConstructorConstraint {
558 if (constraints != null)
559 return constraints.HasConstructorConstraint;
571 public bool Resolve (DeclSpace ds)
573 if (constraints != null) {
574 if (!constraints.Resolve (ds.EmitContext)) {
583 public void Define (GenericTypeParameterBuilder type)
585 if (this.type != null)
586 throw new InvalidOperationException ();
589 TypeManager.AddTypeParameter (type, this);
592 public void DefineConstraints ()
594 if (constraints != null)
595 constraints.Define (type);
598 public bool ResolveType (EmitContext ec)
600 if (constraints != null) {
601 if (!constraints.ResolveTypes (ec)) {
610 public bool DefineType (EmitContext ec)
612 return DefineType (ec, null, null, false);
615 public bool DefineType (EmitContext ec, MethodBuilder builder,
616 MethodInfo implementing, bool is_override)
618 if (!ResolveType (ec))
621 if (implementing != null) {
622 if (is_override && (constraints != null)) {
624 460, loc, "Constraints for override and " +
625 "explicit interface implementation methods " +
626 "are inherited from the base method so they " +
627 "cannot be specified directly");
631 MethodBase mb = implementing;
632 if (mb.Mono_IsInflatedMethod)
633 mb = mb.GetGenericMethodDefinition ();
635 int pos = type.GenericParameterPosition;
636 ParameterData pd = TypeManager.GetParameterData (mb);
637 GenericConstraints temp_gc = pd.GenericConstraints (pos);
638 Type mparam = mb.GetGenericArguments () [pos];
641 gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
642 else if (constraints != null)
643 gc = new InflatedConstraints (constraints, implementing.DeclaringType);
646 if (constraints != null) {
649 else if (!constraints.CheckInterfaceMethod (ec, gc))
652 if (!is_override && (temp_gc != null))
657 Report.SymbolRelatedToPreviousError (implementing);
660 425, loc, "The constraints for type " +
661 "parameter `{0}' of method `{1}' must match " +
662 "the constraints for type parameter `{2}' " +
663 "of interface method `{3}'. Consider using " +
664 "an explicit interface implementation instead",
665 Name, TypeManager.CSharpSignature (builder),
666 mparam, TypeManager.CSharpSignature (mb));
670 gc = (GenericConstraints) constraints;
676 if (gc.HasClassConstraint)
677 type.SetBaseTypeConstraint (gc.ClassConstraint);
679 type.SetInterfaceConstraints (gc.InterfaceConstraints);
680 TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
685 public bool CheckDependencies (EmitContext ec)
687 if (constraints != null)
688 return constraints.CheckDependencies (ec);
693 public bool UpdateConstraints (EmitContext ec, Constraints new_constraints)
696 // We're used in partial generic type definitions.
697 // If `check' is false, we just encountered the first ClassPart which has
698 // constraints - they become our "real" constraints.
699 // Otherwise we're called after the type parameters have already been defined
700 // and check whether the constraints are the same in all parts.
703 throw new InvalidOperationException ();
705 if (constraints == null) {
706 new_constraints = constraints;
708 } else if (new_constraints == null)
711 if (!new_constraints.Resolve (ec))
713 if (!new_constraints.ResolveTypes (ec))
716 return constraints.CheckInterfaceMethod (ec, new_constraints);
719 public override string DocCommentHeader {
721 throw new InvalidOperationException (
722 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
730 public override bool Define ()
735 protected override void VerifyObsoleteAttribute ()
738 public override void ApplyAttributeBuilder (Attribute a,
739 CustomAttributeBuilder cb)
742 public override AttributeTargets AttributeTargets {
744 return (AttributeTargets) 0;
748 public override string[] ValidAttributeTargets {
750 return new string [0];
758 string IMemberContainer.Name {
762 MemberCache IMemberContainer.BaseCache {
766 bool IMemberContainer.IsInterface {
770 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
772 return FindMembers (mt, bf, null, null);
775 MemberCache IMemberContainer.MemberCache {
779 public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
780 MemberFilter filter, object criteria)
782 if (constraints == null)
783 return MemberList.Empty;
785 ArrayList members = new ArrayList ();
787 GenericConstraints gc = (GenericConstraints) constraints;
789 if (gc.HasClassConstraint) {
790 MemberList list = TypeManager.FindMembers (
791 gc.ClassConstraint, mt, bf, filter, criteria);
793 members.AddRange (list);
796 foreach (Type t in gc.InterfaceConstraints) {
797 MemberList list = TypeManager.FindMembers (
798 t, mt, bf, filter, criteria);
800 members.AddRange (list);
803 return new MemberList (members);
806 public bool IsSubclassOf (Type t)
811 if (constraints != null)
812 return constraints.IsSubclassOf (t);
817 public override string ToString ()
819 return "TypeParameter[" + name + "]";
822 protected class InflatedConstraints : GenericConstraints
824 GenericConstraints gc;
826 Type class_constraint;
827 Type[] iface_constraints;
830 public InflatedConstraints (GenericConstraints gc, Type declaring)
834 dargs = TypeManager.GetTypeArguments (declaring);
836 ArrayList list = new ArrayList ();
837 if (gc.HasClassConstraint)
838 list.Add (inflate (gc.ClassConstraint));
839 foreach (Type iface in gc.InterfaceConstraints)
840 list.Add (inflate (iface));
842 bool has_class_constr = false;
843 if (list.Count > 0) {
844 Type first = (Type) list [0];
845 has_class_constr = !first.IsInterface && !first.IsGenericParameter;
848 if ((list.Count > 0) && has_class_constr) {
849 class_constraint = (Type) list [0];
850 iface_constraints = new Type [list.Count - 1];
851 list.CopyTo (1, iface_constraints, 0, list.Count - 1);
853 iface_constraints = new Type [list.Count];
854 list.CopyTo (iface_constraints, 0);
857 if (HasValueTypeConstraint)
858 base_type = TypeManager.value_type;
859 else if (class_constraint != null)
860 base_type = class_constraint;
862 base_type = TypeManager.object_type;
865 Type inflate (Type t)
869 if (t.IsGenericParameter)
870 return dargs [t.GenericParameterPosition];
871 if (t.IsGenericInstance) {
872 t = t.GetGenericTypeDefinition ();
873 t = t.BindGenericParameters (dargs);
879 public override GenericParameterAttributes Attributes {
880 get { return gc.Attributes; }
883 public override Type ClassConstraint {
884 get { return class_constraint; }
887 public override Type EffectiveBaseClass {
888 get { return base_type; }
891 public override Type[] InterfaceConstraints {
892 get { return iface_constraints; }
898 // This type represents a generic type parameter reference.
900 // These expressions are born in a fully resolved state.
902 public class TypeParameterExpr : TypeExpr {
903 TypeParameter type_parameter;
905 public override string Name {
907 return type_parameter.Name;
911 public override string FullName {
913 return type_parameter.Name;
917 public TypeParameter TypeParameter {
919 return type_parameter;
923 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
925 this.type_parameter = type_parameter;
929 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
931 type = type_parameter.Type;
936 public override bool IsInterface {
937 get { return false; }
940 public override bool CheckAccessLevel (DeclSpace ds)
945 public void Error_CannotUseAsUnmanagedType (Location loc)
947 Report.Error (-203, loc, "Can not use type parameter as unamanged type");
951 public class TypeArguments {
952 public readonly Location Location;
959 public TypeArguments (Location loc)
961 args = new ArrayList ();
965 public TypeArguments (int dimension, Location loc)
967 this.dimension = dimension;
971 public void Add (Expression type)
974 throw new InvalidOperationException ();
979 public void Add (TypeArguments new_args)
982 throw new InvalidOperationException ();
984 args.AddRange (new_args.args);
987 public string[] GetDeclarations ()
989 string[] ret = new string [args.Count];
990 for (int i = 0; i < args.Count; i++) {
991 SimpleName sn = args [i] as SimpleName;
997 Report.Error (81, Location, "Type parameter declaration " +
998 "must be an identifier not a type");
1004 public Type[] Arguments {
1010 public bool HasTypeArguments {
1012 return has_type_args;
1025 public bool IsUnbound {
1027 return dimension > 0;
1031 public override string ToString ()
1033 StringBuilder s = new StringBuilder ();
1036 for (int i = 0; i < count; i++){
1038 // FIXME: Use TypeManager.CSharpname once we have the type
1041 s.Append (args [i].ToString ());
1045 return s.ToString ();
1048 public bool Resolve (EmitContext ec)
1050 int count = args.Count;
1053 atypes = new Type [count];
1055 for (int i = 0; i < count; i++){
1056 TypeExpr te = ((Expression) args [i]).ResolveAsTypeTerminal (ec);
1061 if (te is TypeParameterExpr)
1062 has_type_args = true;
1064 if (te.Type.IsPointer) {
1065 Report.Error (306, Location, "The type `{0}' may not be used " +
1066 "as a type argument.", TypeManager.CSharpName (te.Type));
1070 atypes [i] = te.Type;
1076 public class ConstructedType : TypeExpr {
1078 FullNamedExpression name;
1080 Type[] gen_params, atypes;
1083 public ConstructedType (FullNamedExpression fname, TypeArguments args, Location l)
1089 eclass = ExprClass.Type;
1090 full_name = name + "<" + args.ToString () + ">";
1093 protected ConstructedType (TypeArguments args, Location l)
1098 eclass = ExprClass.Type;
1101 protected ConstructedType (TypeParameter[] type_params, Location l)
1105 args = new TypeArguments (l);
1106 foreach (TypeParameter type_param in type_params)
1107 args.Add (new TypeParameterExpr (type_param, l));
1109 eclass = ExprClass.Type;
1112 public ConstructedType (Type t, TypeParameter[] type_params, Location l)
1113 : this (type_params, l)
1115 gt = t.GetGenericTypeDefinition ();
1117 this.name = new TypeExpression (gt, l);
1118 full_name = gt.FullName + "<" + args.ToString () + ">";
1121 public ConstructedType (Type t, TypeArguments args, Location l)
1124 gt = t.GetGenericTypeDefinition ();
1126 this.name = new TypeExpression (gt, l);
1127 full_name = gt.FullName + "<" + args.ToString () + ">";
1130 public TypeArguments TypeArguments {
1131 get { return args; }
1134 protected string DeclarationName {
1136 StringBuilder sb = new StringBuilder ();
1137 sb.Append (gt.FullName);
1139 for (int i = 0; i < gen_params.Length; i++) {
1142 sb.Append (gen_params [i]);
1145 return sb.ToString ();
1149 protected bool CheckConstraint (EmitContext ec, Type ptype, Expression expr,
1152 if (TypeManager.HasGenericArguments (ctype)) {
1153 Type[] types = TypeManager.GetTypeArguments (ctype);
1155 TypeArguments new_args = new TypeArguments (loc);
1157 for (int i = 0; i < types.Length; i++) {
1160 if (t.IsGenericParameter) {
1161 int pos = t.GenericParameterPosition;
1162 t = args.Arguments [pos];
1164 new_args.Add (new TypeExpression (t, loc));
1167 TypeExpr ct = new ConstructedType (ctype, new_args, loc);
1168 if (ct.ResolveAsTypeStep (ec) == null)
1173 return Convert.ImplicitStandardConversionExists (ec, expr, ctype);
1176 protected bool CheckConstraints (EmitContext ec, int index)
1178 Type atype = atypes [index];
1179 Type ptype = gen_params [index];
1184 Expression aexpr = new EmptyExpression (atype);
1186 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1190 bool is_class, is_struct;
1191 if (atype.IsGenericParameter) {
1192 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1194 is_class = agc.HasReferenceTypeConstraint;
1195 is_struct = agc.HasValueTypeConstraint;
1197 is_class = is_struct = false;
1200 is_class = atype.IsClass;
1201 is_struct = atype.IsValueType;
1205 // First, check the `class' and `struct' constraints.
1207 if (gc.HasReferenceTypeConstraint && !is_class) {
1208 Report.Error (452, loc, "The type `{0}' must be " +
1209 "a reference type in order to use it " +
1210 "as type parameter `{1}' in the " +
1211 "generic type or method `{2}'.",
1212 atype, ptype, DeclarationName);
1214 } else if (gc.HasValueTypeConstraint && !is_struct) {
1215 Report.Error (453, loc, "The type `{0}' must be " +
1216 "a value type in order to use it " +
1217 "as type parameter `{1}' in the " +
1218 "generic type or method `{2}'.",
1219 atype, ptype, DeclarationName);
1224 // The class constraint comes next.
1226 if (gc.HasClassConstraint) {
1227 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint)) {
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, gc.ClassConstraint, ptype, DeclarationName);
1238 // Now, check the interface constraints.
1240 foreach (Type it in gc.InterfaceConstraints) {
1242 if (it.IsGenericParameter)
1243 itype = atypes [it.GenericParameterPosition];
1247 if (!CheckConstraint (ec, ptype, aexpr, itype)) {
1248 Report.Error (309, loc, "The type `{0}' must be " +
1249 "convertible to `{1}' in order to " +
1250 "use it as parameter `{2}' in the " +
1251 "generic type or method `{3}'",
1252 atype, itype, ptype, DeclarationName);
1258 // Finally, check the constructor constraint.
1261 if (!gc.HasConstructorConstraint)
1264 if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
1267 MethodGroupExpr mg = Expression.MemberLookup (
1268 ec, atype, ".ctor", MemberTypes.Constructor,
1269 BindingFlags.Public | BindingFlags.Instance |
1270 BindingFlags.DeclaredOnly, loc)
1273 if (atype.IsAbstract || (mg == null) || !mg.IsInstance) {
1274 Report.Error (310, loc, "The type `{0}' must have a public " +
1275 "parameterless constructor in order to use it " +
1276 "as parameter `{1}' in the generic type or " +
1277 "method `{2}'", atype, ptype, DeclarationName);
1284 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
1286 if (!ResolveConstructedType (ec))
1292 public bool CheckConstraints (EmitContext ec)
1294 for (int i = 0; i < gen_params.Length; i++) {
1295 if (!CheckConstraints (ec, i))
1302 public bool ResolveConstructedType (EmitContext ec)
1307 return DoResolveType (ec);
1313 Report.Error (246, loc, "Cannot find type `{0}'<...>", Name);
1317 num_args = TypeManager.GetNumberOfTypeArguments (t);
1318 if (num_args == 0) {
1319 Report.Error (308, loc,
1320 "The non-generic type `{0}' cannot " +
1321 "be used with type arguments.",
1322 TypeManager.CSharpName (t));
1326 gt = t.GetGenericTypeDefinition ();
1327 return DoResolveType (ec);
1330 bool DoResolveType (EmitContext ec)
1333 // Resolve the arguments.
1335 if (args.Resolve (ec) == false)
1338 gen_params = gt.GetGenericArguments ();
1339 atypes = args.Arguments;
1341 if (atypes.Length != gen_params.Length) {
1342 Report.Error (305, loc,
1343 "Using the generic type `{0}' " +
1344 "requires {1} type arguments",
1345 TypeManager.GetFullName (gt),
1351 // Now bind the parameters.
1353 type = gt.BindGenericParameters (atypes);
1357 public Expression GetSimpleName (EmitContext ec)
1362 public override bool CheckAccessLevel (DeclSpace ds)
1364 return ds.CheckAccessLevel (gt);
1367 public override bool AsAccessible (DeclSpace ds, int flags)
1369 return ds.AsAccessible (gt, flags);
1372 public override bool IsClass {
1373 get { return gt.IsClass; }
1376 public override bool IsValueType {
1377 get { return gt.IsValueType; }
1380 public override bool IsInterface {
1381 get { return gt.IsInterface; }
1384 public override bool IsSealed {
1385 get { return gt.IsSealed; }
1388 public override bool Equals (object obj)
1390 ConstructedType cobj = obj as ConstructedType;
1394 if ((type == null) || (cobj.type == null))
1397 return type == cobj.type;
1400 public override int GetHashCode ()
1402 return base.GetHashCode ();
1405 public override string Name {
1412 public override string FullName {
1419 public class GenericMethod : DeclSpace
1421 public GenericMethod (NamespaceEntry ns, TypeContainer parent,
1422 MemberName name, Location l)
1423 : base (ns, parent, name, null, l)
1426 public override TypeBuilder DefineType ()
1428 throw new Exception ();
1431 public override bool Define ()
1433 ec = new EmitContext (this, this, Location, null, null, ModFlags, false);
1435 for (int i = 0; i < TypeParameters.Length; i++)
1436 if (!TypeParameters [i].Resolve (this))
1442 public bool Define (MethodBuilder mb)
1444 GenericTypeParameterBuilder[] gen_params;
1445 string[] names = MemberName.TypeArguments.GetDeclarations ();
1446 gen_params = mb.DefineGenericParameters (names);
1447 for (int i = 0; i < TypeParameters.Length; i++)
1448 TypeParameters [i].Define (gen_params [i]);
1453 for (int i = 0; i < TypeParameters.Length; i++) {
1454 if (!TypeParameters [i].ResolveType (ec))
1461 public bool DefineType (EmitContext ec, MethodBuilder mb,
1462 MethodInfo implementing, bool is_override)
1464 for (int i = 0; i < TypeParameters.Length; i++)
1465 if (!TypeParameters [i].DefineType (
1466 ec, mb, implementing, is_override))
1472 public override bool DefineMembers (TypeContainer parent)
1477 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1478 MemberFilter filter, object criteria)
1480 throw new Exception ();
1483 public override MemberCache MemberCache {
1489 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1494 protected override void VerifyObsoleteAttribute()
1499 public override AttributeTargets AttributeTargets {
1501 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1505 public override string DocCommentHeader {
1506 get { return "M:"; }
1510 public class DefaultValueExpression : Expression
1514 public DefaultValueExpression (Expression expr, Location loc)
1520 public override Expression DoResolve (EmitContext ec)
1522 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
1528 eclass = ExprClass.Variable;
1532 public override void Emit (EmitContext ec)
1534 if (type.IsGenericParameter || TypeManager.IsValueType (type)) {
1535 LocalTemporary temp_storage = new LocalTemporary (ec, type);
1537 temp_storage.AddressOf (ec, AddressOp.LoadStore);
1538 ec.ig.Emit (OpCodes.Initobj, type);
1539 temp_storage.Emit (ec);
1541 ec.ig.Emit (OpCodes.Ldnull);
1545 public class NullableType : TypeExpr
1547 Expression underlying;
1549 public NullableType (Expression underlying, Location l)
1551 this.underlying = underlying;
1554 eclass = ExprClass.Type;
1557 public NullableType (Type type, Location loc)
1558 : this (new TypeExpression (type, loc), loc)
1561 public override string Name {
1562 get { return underlying.ToString () + "?"; }
1565 public override string FullName {
1566 get { return underlying.ToString () + "?"; }
1569 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
1571 TypeArguments args = new TypeArguments (loc);
1572 args.Add (underlying);
1574 ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
1575 return ctype.ResolveAsTypeTerminal (ec);
1579 public partial class TypeManager
1582 // A list of core types that the compiler requires or uses
1584 static public Type new_constraint_attr_type;
1585 static public Type activator_type;
1586 static public Type generic_ienumerator_type;
1587 static public Type generic_ienumerable_type;
1588 static public Type generic_nullable_type;
1591 // Tracks the generic parameters.
1593 static PtrHashtable builder_to_type_param;
1596 // These methods are called by code generated by the compiler
1598 static public MethodInfo activator_create_instance;
1600 static void InitGenerics ()
1602 builder_to_type_param = new PtrHashtable ();
1605 static void CleanUpGenerics ()
1607 builder_to_type_param = null;
1610 static void InitGenericCoreTypes ()
1612 activator_type = CoreLookupType ("System.Activator");
1613 new_constraint_attr_type = CoreLookupType (
1614 "System.Runtime.CompilerServices.NewConstraintAttribute");
1616 generic_ienumerator_type = CoreLookupType ("System.Collections.Generic.IEnumerator", 1);
1617 generic_ienumerable_type = CoreLookupType ("System.Collections.Generic.IEnumerable", 1);
1618 generic_nullable_type = CoreLookupType ("System.Nullable", 1);
1621 static void InitGenericCodeHelpers ()
1624 Type [] type_arg = { type_type };
1625 activator_create_instance = GetMethod (
1626 activator_type, "CreateInstance", type_arg);
1629 static Type CoreLookupType (string name, int arity)
1631 return CoreLookupType (MemberName.MakeName (name, arity));
1634 public static void AddTypeParameter (Type t, TypeParameter tparam)
1636 if (!builder_to_type_param.Contains (t))
1637 builder_to_type_param.Add (t, tparam);
1640 public static TypeContainer LookupGenericTypeContainer (Type t)
1642 while (t.IsGenericInstance)
1643 t = t.GetGenericTypeDefinition ();
1645 return LookupTypeContainer (t);
1648 public static TypeParameter LookupTypeParameter (Type t)
1650 return (TypeParameter) builder_to_type_param [t];
1653 public static GenericConstraints GetTypeParameterConstraints (Type t)
1655 if (!t.IsGenericParameter)
1656 throw new InvalidOperationException ();
1658 TypeParameter tparam = LookupTypeParameter (t);
1660 return tparam.GenericConstraints;
1662 return new ReflectionConstraints (t);
1665 public static bool IsGeneric (Type t)
1667 DeclSpace ds = (DeclSpace) builder_to_declspace [t];
1669 return ds.IsGeneric;
1672 public static bool HasGenericArguments (Type t)
1674 return GetNumberOfTypeArguments (t) > 0;
1677 public static int GetNumberOfTypeArguments (Type t)
1679 DeclSpace tc = LookupDeclSpace (t);
1681 return tc.IsGeneric ? tc.CountTypeParameters : 0;
1683 return t.HasGenericArguments ? t.GetGenericArguments ().Length : 0;
1686 public static Type[] GetTypeArguments (Type t)
1688 DeclSpace tc = LookupDeclSpace (t);
1691 return Type.EmptyTypes;
1693 TypeParameter[] tparam = tc.TypeParameters;
1694 Type[] ret = new Type [tparam.Length];
1695 for (int i = 0; i < tparam.Length; i++) {
1696 ret [i] = tparam [i].Type;
1697 if (ret [i] == null)
1698 throw new InternalErrorException ();
1703 return t.GetGenericArguments ();
1707 // Whether `array' is an array of T and `enumerator' is `IEnumerable<T>'.
1708 // For instance "string[]" -> "IEnumerable<string>".
1710 public static bool IsIEnumerable (Type array, Type enumerator)
1712 if (!array.IsArray || !enumerator.IsGenericInstance)
1715 if (enumerator.GetGenericTypeDefinition () != generic_ienumerable_type)
1718 Type[] args = GetTypeArguments (enumerator);
1719 return args [0] == GetElementType (array);
1722 public static bool IsEqual (Type a, Type b)
1727 if ((a is TypeBuilder) && a.IsGenericTypeDefinition && b.IsGenericInstance) {
1729 // `a' is a generic type definition's TypeBuilder and `b' is a
1730 // generic instance of the same type.
1736 // void Test (Stack<T> stack) { }
1739 // The first argument of `Test' will be the generic instance
1740 // "Stack<!0>" - which is the same type than the "Stack" TypeBuilder.
1743 // We hit this via Closure.Filter() for gen-82.cs.
1745 if (a != b.GetGenericTypeDefinition ())
1748 Type[] aparams = a.GetGenericArguments ();
1749 Type[] bparams = b.GetGenericArguments ();
1751 if (aparams.Length != bparams.Length)
1754 for (int i = 0; i < aparams.Length; i++)
1755 if (!IsEqual (aparams [i], bparams [i]))
1761 if ((b is TypeBuilder) && b.IsGenericTypeDefinition && a.IsGenericInstance)
1762 return IsEqual (b, a);
1764 if (a.IsGenericParameter && b.IsGenericParameter) {
1765 if ((a.DeclaringMethod == null) || (b.DeclaringMethod == null))
1767 return a.GenericParameterPosition == b.GenericParameterPosition;
1770 if (a.IsArray && b.IsArray) {
1771 if (a.GetArrayRank () != b.GetArrayRank ())
1773 return IsEqual (a.GetElementType (), b.GetElementType ());
1776 if (a.IsGenericInstance && b.IsGenericInstance) {
1777 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
1780 Type[] aargs = a.GetGenericArguments ();
1781 Type[] bargs = b.GetGenericArguments ();
1783 if (aargs.Length != bargs.Length)
1786 for (int i = 0; i < aargs.Length; i++) {
1787 if (!IsEqual (aargs [i], bargs [i]))
1797 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_infered, Type[] method_infered)
1799 if (a.IsGenericParameter) {
1801 // If a is an array of a's type, they may never
1805 b = b.GetElementType ();
1811 // If b is a generic parameter or an actual type,
1812 // they may become equal:
1814 // class X<T,U> : I<T>, I<U>
1815 // class X<T> : I<T>, I<float>
1817 if (b.IsGenericParameter || !b.IsGenericInstance) {
1818 int pos = a.GenericParameterPosition;
1819 Type[] args = a.DeclaringMethod != null ? method_infered : class_infered;
1820 if (args [pos] == null) {
1825 return args [pos] == a;
1829 // We're now comparing a type parameter with a
1830 // generic instance. They may become equal unless
1831 // the type parameter appears anywhere in the
1832 // generic instance:
1834 // class X<T,U> : I<T>, I<X<U>>
1835 // -> error because you could instanciate it as
1838 // class X<T> : I<T>, I<X<T>> -> ok
1841 Type[] bargs = GetTypeArguments (b);
1842 for (int i = 0; i < bargs.Length; i++) {
1843 if (a.Equals (bargs [i]))
1850 if (b.IsGenericParameter)
1851 return MayBecomeEqualGenericTypes (b, a, class_infered, method_infered);
1854 // At this point, neither a nor b are a type parameter.
1856 // If one of them is a generic instance, let
1857 // MayBecomeEqualGenericInstances() compare them (if the
1858 // other one is not a generic instance, they can never
1862 if (a.IsGenericInstance || b.IsGenericInstance)
1863 return MayBecomeEqualGenericInstances (a, b, class_infered, method_infered);
1866 // If both of them are arrays.
1869 if (a.IsArray && b.IsArray) {
1870 if (a.GetArrayRank () != b.GetArrayRank ())
1873 a = a.GetElementType ();
1874 b = b.GetElementType ();
1876 return MayBecomeEqualGenericTypes (a, b, class_infered, method_infered);
1880 // Ok, two ordinary types.
1883 return a.Equals (b);
1887 // Checks whether two generic instances may become equal for some
1888 // particular instantiation (26.3.1).
1890 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
1891 Type[] class_infered, Type[] method_infered)
1893 if (!a.IsGenericInstance || !b.IsGenericInstance)
1895 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
1898 return MayBecomeEqualGenericInstances (
1899 GetTypeArguments (a), GetTypeArguments (b), class_infered, method_infered);
1902 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
1903 Type[] class_infered, Type[] method_infered)
1905 if (aargs.Length != bargs.Length)
1908 for (int i = 0; i < aargs.Length; i++) {
1909 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_infered, method_infered))
1916 public static bool IsEqualGenericInstance (Type type, Type parent)
1918 int tcount = GetNumberOfTypeArguments (type);
1919 int pcount = GetNumberOfTypeArguments (parent);
1921 if (type.IsGenericInstance)
1922 type = type.GetGenericTypeDefinition ();
1923 if (parent.IsGenericInstance)
1924 parent = parent.GetGenericTypeDefinition ();
1926 if (tcount != pcount)
1929 return type.Equals (parent);
1932 static public bool IsGenericMethod (MethodBase mb)
1934 if (mb.DeclaringType is TypeBuilder) {
1935 IMethodData method = (IMethodData) builder_to_method [mb];
1939 return method.GenericMethod != null;
1942 return mb.IsGenericMethodDefinition;
1949 static bool InferType (Type pt, Type at, Type[] infered)
1951 if (pt.IsGenericParameter && (pt.DeclaringMethod != null)) {
1952 int pos = pt.GenericParameterPosition;
1954 if (infered [pos] == null) {
1956 while (check.IsArray)
1957 check = check.GetElementType ();
1966 if (infered [pos] != at)
1972 if (!pt.ContainsGenericParameters) {
1973 if (at.ContainsGenericParameters)
1974 return InferType (at, pt, infered);
1981 (at.GetArrayRank () != pt.GetArrayRank ()))
1984 return InferType (pt.GetElementType (), at.GetElementType (), infered);
1989 (pt.GetArrayRank () != at.GetArrayRank ()))
1992 return InferType (pt.GetElementType (), at.GetElementType (), infered);
1995 if (pt.IsByRef && at.IsByRef)
1996 return InferType (pt.GetElementType (), at.GetElementType (), infered);
1997 ArrayList list = new ArrayList ();
1998 if (at.IsGenericInstance)
2000 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
2003 list.AddRange (TypeManager.GetInterfaces (at));
2005 bool found_one = false;
2007 foreach (Type type in list) {
2008 if (!type.IsGenericInstance)
2011 Type[] infered_types = new Type [infered.Length];
2013 if (!InferGenericInstance (pt, type, infered_types))
2016 for (int i = 0; i < infered_types.Length; i++) {
2017 if (infered [i] == null) {
2018 infered [i] = infered_types [i];
2022 if (infered [i] != infered_types [i])
2032 static bool InferGenericInstance (Type pt, Type at, Type[] infered_types)
2034 Type[] at_args = at.GetGenericArguments ();
2035 Type[] pt_args = pt.GetGenericArguments ();
2037 if (at_args.Length != pt_args.Length)
2040 for (int i = 0; i < at_args.Length; i++) {
2041 if (!InferType (pt_args [i], at_args [i], infered_types))
2045 for (int i = 0; i < infered_types.Length; i++) {
2046 if (infered_types [i] == null)
2053 public static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
2054 ref MethodBase method)
2056 if ((arguments == null) || !TypeManager.IsGenericMethod (method))
2061 if (arguments == null)
2064 arg_count = arguments.Count;
2066 ParameterData pd = TypeManager.GetParameterData (method);
2068 int pd_count = pd.Count;
2073 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2076 if (pd_count - 1 > arg_count)
2079 if (pd_count == 1 && arg_count == 0)
2082 Type[] method_args = method.GetGenericArguments ();
2083 Type[] infered_types = new Type [method_args.Length];
2086 // If we have come this far, the case which
2087 // remains is when the number of parameters is
2088 // less than or equal to the argument count.
2090 for (int i = 0; i < pd_count - 1; ++i) {
2091 Argument a = (Argument) arguments [i];
2093 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2096 Type pt = pd.ParameterType (i);
2099 if (!InferType (pt, at, infered_types))
2103 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
2105 for (int i = pd_count - 1; i < arg_count; i++) {
2106 Argument a = (Argument) arguments [i];
2108 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2111 if (!InferType (element_type, a.Type, infered_types))
2115 for (int i = 0; i < infered_types.Length; i++)
2116 if (infered_types [i] == null)
2119 method = method.BindGenericParameters (infered_types);
2123 public static bool InferTypeArguments (Type[] param_types, Type[] arg_types, Type[] infered_types)
2125 if (infered_types == null)
2128 for (int i = 0; i < arg_types.Length; i++) {
2129 if (arg_types [i] == null)
2132 if (!InferType (param_types [i], arg_types [i], infered_types))
2136 for (int i = 0; i < infered_types.Length; i++)
2137 if (infered_types [i] == null)
2143 public static bool InferTypeArguments (EmitContext ec, ArrayList arguments,
2144 ref MethodBase method)
2146 if (!TypeManager.IsGenericMethod (method))
2150 if (arguments != null)
2151 arg_count = arguments.Count;
2155 ParameterData pd = TypeManager.GetParameterData (method);
2156 if (arg_count != pd.Count)
2159 Type[] method_args = method.GetGenericArguments ();
2161 bool is_open = false;
2162 for (int i = 0; i < method_args.Length; i++) {
2163 if (method_args [i].IsGenericParameter) {
2171 Type[] infered_types = new Type [method_args.Length];
2173 Type[] param_types = new Type [pd.Count];
2174 Type[] arg_types = new Type [pd.Count];
2176 for (int i = 0; i < arg_count; i++) {
2177 param_types [i] = pd.ParameterType (i);
2179 Argument a = (Argument) arguments [i];
2180 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr) ||
2181 (a.Expr is AnonymousMethod))
2184 arg_types [i] = a.Type;
2187 if (!InferTypeArguments (param_types, arg_types, infered_types))
2190 method = method.BindGenericParameters (infered_types);
2194 public static bool InferTypeArguments (EmitContext ec, ParameterData apd,
2195 ref MethodBase method)
2197 if (!TypeManager.IsGenericMethod (method))
2200 ParameterData pd = TypeManager.GetParameterData (method);
2201 if (apd.Count != pd.Count)
2204 Type[] method_args = method.GetGenericArguments ();
2205 Type[] infered_types = new Type [method_args.Length];
2207 Type[] param_types = new Type [pd.Count];
2208 Type[] arg_types = new Type [pd.Count];
2210 for (int i = 0; i < apd.Count; i++) {
2211 param_types [i] = pd.ParameterType (i);
2212 arg_types [i] = apd.ParameterType (i);
2215 if (!InferTypeArguments (param_types, arg_types, infered_types))
2218 method = method.BindGenericParameters (infered_types);
2222 public static bool IsNullableType (Type t)
2224 if (!t.IsGenericInstance)
2227 Type gt = t.GetGenericTypeDefinition ();
2228 return gt == generic_nullable_type;
2232 public abstract class Nullable
2234 protected sealed class NullableInfo
2236 public readonly Type Type;
2237 public readonly Type UnderlyingType;
2238 public readonly MethodInfo HasValue;
2239 public readonly MethodInfo Value;
2240 public readonly ConstructorInfo Constructor;
2242 public NullableInfo (Type type)
2245 UnderlyingType = TypeManager.GetTypeArguments (type) [0];
2247 PropertyInfo has_value_pi = type.GetProperty ("HasValue");
2248 PropertyInfo value_pi = type.GetProperty ("Value");
2250 HasValue = has_value_pi.GetGetMethod (false);
2251 Value = value_pi.GetGetMethod (false);
2252 Constructor = type.GetConstructor (new Type[] { UnderlyingType });
2256 protected class Unwrap : Expression, IMemoryLocation, IAssignMethod
2261 LocalTemporary temp;
2264 public Unwrap (Expression expr, Location loc)
2270 public override Expression DoResolve (EmitContext ec)
2272 expr = expr.Resolve (ec);
2276 if (!(expr is IMemoryLocation))
2277 temp = new LocalTemporary (ec, expr.Type);
2279 info = new NullableInfo (expr.Type);
2280 type = info.UnderlyingType;
2281 eclass = expr.eclass;
2285 public override void Emit (EmitContext ec)
2287 AddressOf (ec, AddressOp.LoadStore);
2288 ec.ig.EmitCall (OpCodes.Call, info.Value, null);
2291 public void EmitCheck (EmitContext ec)
2293 AddressOf (ec, AddressOp.LoadStore);
2294 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
2297 void create_temp (EmitContext ec)
2299 if ((temp != null) && !has_temp) {
2306 public void AddressOf (EmitContext ec, AddressOp mode)
2310 temp.AddressOf (ec, AddressOp.LoadStore);
2312 ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
2315 public void Emit (EmitContext ec, bool leave_copy)
2328 public void EmitAssign (EmitContext ec, Expression source,
2329 bool leave_copy, bool prepare_for_load)
2332 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2335 ec.ig.Emit (OpCodes.Dup);
2337 Expression empty = new EmptyExpression (expr.Type);
2338 ((IAssignMethod) expr).EmitAssign (ec, empty, false, prepare_for_load);
2342 protected class Wrap : Expression
2347 public Wrap (Expression expr, Location loc)
2353 public override Expression DoResolve (EmitContext ec)
2355 expr = expr.Resolve (ec);
2359 TypeExpr target_type = new NullableType (expr.Type, loc);
2360 target_type = target_type.ResolveAsTypeTerminal (ec);
2361 if (target_type == null)
2364 type = target_type.Type;
2365 info = new NullableInfo (type);
2366 eclass = ExprClass.Value;
2370 public override void Emit (EmitContext ec)
2373 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2377 public class NullableLiteral : Expression, IMemoryLocation {
2378 public NullableLiteral (Type target_type, Location loc)
2380 this.type = target_type;
2383 eclass = ExprClass.Value;
2386 public override Expression DoResolve (EmitContext ec)
2391 public override void Emit (EmitContext ec)
2393 LocalTemporary value_target = new LocalTemporary (ec, type);
2395 value_target.AddressOf (ec, AddressOp.Store);
2396 ec.ig.Emit (OpCodes.Initobj, type);
2397 value_target.Emit (ec);
2400 public void AddressOf (EmitContext ec, AddressOp Mode)
2402 LocalTemporary value_target = new LocalTemporary (ec, type);
2404 value_target.AddressOf (ec, AddressOp.Store);
2405 ec.ig.Emit (OpCodes.Initobj, type);
2406 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
2410 public abstract class Lifted : Expression, IMemoryLocation
2412 Expression expr, underlying, wrap, null_value;
2415 protected Lifted (Expression expr, Location loc)
2421 public override Expression DoResolve (EmitContext ec)
2423 expr = expr.Resolve (ec);
2427 unwrap = (Unwrap) new Unwrap (expr, loc).Resolve (ec);
2431 underlying = ResolveUnderlying (unwrap, ec);
2432 if (underlying == null)
2435 wrap = new Wrap (underlying, loc).Resolve (ec);
2439 null_value = new NullableLiteral (wrap.Type, loc).Resolve (ec);
2440 if (null_value == null)
2444 eclass = ExprClass.Value;
2448 protected abstract Expression ResolveUnderlying (Expression unwrap, EmitContext ec);
2450 public override void Emit (EmitContext ec)
2452 ILGenerator ig = ec.ig;
2453 Label is_null_label = ig.DefineLabel ();
2454 Label end_label = ig.DefineLabel ();
2456 unwrap.EmitCheck (ec);
2457 ig.Emit (OpCodes.Brfalse, is_null_label);
2460 ig.Emit (OpCodes.Br, end_label);
2462 ig.MarkLabel (is_null_label);
2463 null_value.Emit (ec);
2465 ig.MarkLabel (end_label);
2468 public void AddressOf (EmitContext ec, AddressOp mode)
2470 unwrap.AddressOf (ec, mode);
2474 public class LiftedConversion : Lifted
2476 public readonly bool IsUser;
2477 public readonly bool IsExplicit;
2478 public readonly Type TargetType;
2480 public LiftedConversion (Expression expr, Type target_type, bool is_user,
2481 bool is_explicit, Location loc)
2484 this.IsUser = is_user;
2485 this.IsExplicit = is_explicit;
2486 this.TargetType = target_type;
2489 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2491 Type type = TypeManager.GetTypeArguments (TargetType) [0];
2494 return Convert.UserDefinedConversion (ec, unwrap, type, loc, IsExplicit);
2497 return Convert.ExplicitConversion (ec, unwrap, type, loc);
2499 return Convert.ImplicitConversion (ec, unwrap, type, loc);
2504 public class LiftedUnaryOperator : Lifted
2506 public readonly Unary.Operator Oper;
2508 public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
2514 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2516 return new Unary (Oper, unwrap, loc);
2520 public class LiftedConditional : Lifted
2522 Expression true_expr, false_expr;
2524 public LiftedConditional (Expression expr, Expression true_expr, Expression false_expr,
2528 this.true_expr = true_expr;
2529 this.false_expr = false_expr;
2532 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2534 return new Conditional (unwrap, true_expr, false_expr, loc);
2538 public class LiftedBinaryOperator : Expression
2540 public readonly Binary.Operator Oper;
2542 Expression left, right, underlying, null_value, bool_wrap;
2543 Unwrap left_unwrap, right_unwrap;
2544 bool is_equality, is_comparision, is_boolean;
2546 public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
2555 public override Expression DoResolve (EmitContext ec)
2557 if (TypeManager.IsNullableType (left.Type)) {
2558 left_unwrap = new Unwrap (left, loc);
2559 left = left_unwrap.Resolve (ec);
2564 if (TypeManager.IsNullableType (right.Type)) {
2565 right_unwrap = new Unwrap (right, loc);
2566 right = right_unwrap.Resolve (ec);
2571 if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr) ||
2572 (Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr)) &&
2573 ((left.Type == TypeManager.bool_type) && (right.Type == TypeManager.bool_type))) {
2574 Expression empty = new EmptyExpression (TypeManager.bool_type);
2575 bool_wrap = new Wrap (empty, loc).Resolve (ec);
2576 null_value = new NullableLiteral (bool_wrap.Type, loc).Resolve (ec);
2578 type = bool_wrap.Type;
2580 } else if ((Oper == Binary.Operator.Equality) || (Oper == Binary.Operator.Inequality)) {
2581 if (!(left is NullLiteral) && !(right is NullLiteral)) {
2582 underlying = new Binary (Oper, left, right, loc).Resolve (ec);
2583 if (underlying == null)
2587 type = TypeManager.bool_type;
2589 } else if ((Oper == Binary.Operator.LessThan) ||
2590 (Oper == Binary.Operator.GreaterThan) ||
2591 (Oper == Binary.Operator.LessThanOrEqual) ||
2592 (Oper == Binary.Operator.GreaterThanOrEqual)) {
2593 underlying = new Binary (Oper, left, right, loc).Resolve (ec);
2594 if (underlying == null)
2597 type = TypeManager.bool_type;
2598 is_comparision = true;
2600 underlying = new Binary (Oper, left, right, loc).Resolve (ec);
2601 if (underlying == null)
2604 underlying = new Wrap (underlying, loc).Resolve (ec);
2605 if (underlying == null)
2608 type = underlying.Type;
2609 null_value = new NullableLiteral (type, loc).Resolve (ec);
2612 eclass = ExprClass.Value;
2616 void EmitBoolean (EmitContext ec)
2618 ILGenerator ig = ec.ig;
2620 Label left_is_null_label = ig.DefineLabel ();
2621 Label right_is_null_label = ig.DefineLabel ();
2622 Label is_null_label = ig.DefineLabel ();
2623 Label wrap_label = ig.DefineLabel ();
2624 Label end_label = ig.DefineLabel ();
2626 if (left_unwrap != null) {
2627 left_unwrap.EmitCheck (ec);
2628 ig.Emit (OpCodes.Brfalse, left_is_null_label);
2632 ig.Emit (OpCodes.Dup);
2633 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
2634 ig.Emit (OpCodes.Brtrue, wrap_label);
2636 ig.Emit (OpCodes.Brfalse, wrap_label);
2638 if (right_unwrap != null) {
2639 right_unwrap.EmitCheck (ec);
2640 ig.Emit (OpCodes.Brfalse, right_is_null_label);
2643 if ((Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr))
2644 ig.Emit (OpCodes.Pop);
2647 if (Oper == Binary.Operator.BitwiseOr)
2648 ig.Emit (OpCodes.Or);
2649 else if (Oper == Binary.Operator.BitwiseAnd)
2650 ig.Emit (OpCodes.And);
2651 ig.Emit (OpCodes.Br, wrap_label);
2653 ig.MarkLabel (left_is_null_label);
2654 if (right_unwrap != null) {
2655 right_unwrap.EmitCheck (ec);
2656 ig.Emit (OpCodes.Brfalse, is_null_label);
2660 ig.Emit (OpCodes.Dup);
2661 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
2662 ig.Emit (OpCodes.Brtrue, wrap_label);
2664 ig.Emit (OpCodes.Brfalse, wrap_label);
2666 ig.MarkLabel (right_is_null_label);
2667 ig.Emit (OpCodes.Pop);
2668 ig.MarkLabel (is_null_label);
2669 null_value.Emit (ec);
2670 ig.Emit (OpCodes.Br, end_label);
2672 ig.MarkLabel (wrap_label);
2673 ig.Emit (OpCodes.Nop);
2674 bool_wrap.Emit (ec);
2675 ig.Emit (OpCodes.Nop);
2677 ig.MarkLabel (end_label);
2680 void EmitEquality (EmitContext ec)
2682 ILGenerator ig = ec.ig;
2684 Label left_not_null_label = ig.DefineLabel ();
2685 Label false_label = ig.DefineLabel ();
2686 Label true_label = ig.DefineLabel ();
2687 Label end_label = ig.DefineLabel ();
2689 if (left_unwrap != null) {
2690 left_unwrap.EmitCheck (ec);
2691 if (right is NullLiteral) {
2692 if (Oper == Binary.Operator.Equality)
2693 ig.Emit (OpCodes.Brfalse, true_label);
2695 ig.Emit (OpCodes.Brfalse, false_label);
2696 } else if (right_unwrap != null) {
2697 ig.Emit (OpCodes.Dup);
2698 ig.Emit (OpCodes.Brtrue, left_not_null_label);
2699 right_unwrap.EmitCheck (ec);
2700 ig.Emit (OpCodes.Ceq);
2701 if (Oper == Binary.Operator.Inequality) {
2702 ig.Emit (OpCodes.Ldc_I4_0);
2703 ig.Emit (OpCodes.Ceq);
2705 ig.Emit (OpCodes.Br, end_label);
2707 ig.MarkLabel (left_not_null_label);
2708 ig.Emit (OpCodes.Pop);
2710 if (Oper == Binary.Operator.Equality)
2711 ig.Emit (OpCodes.Brfalse, false_label);
2713 ig.Emit (OpCodes.Brfalse, true_label);
2717 if (right_unwrap != null) {
2718 right_unwrap.EmitCheck (ec);
2719 if (left is NullLiteral) {
2720 if (Oper == Binary.Operator.Equality)
2721 ig.Emit (OpCodes.Brfalse, true_label);
2723 ig.Emit (OpCodes.Brfalse, false_label);
2725 if (Oper == Binary.Operator.Equality)
2726 ig.Emit (OpCodes.Brfalse, false_label);
2728 ig.Emit (OpCodes.Brfalse, true_label);
2732 bool left_is_null = left is NullLiteral;
2733 bool right_is_null = right is NullLiteral;
2734 if (left_is_null || right_is_null) {
2735 if (((Oper == Binary.Operator.Equality) && (left_is_null == right_is_null)) ||
2736 ((Oper == Binary.Operator.Inequality) && (left_is_null != right_is_null)))
2737 ig.Emit (OpCodes.Br, true_label);
2739 ig.Emit (OpCodes.Br, false_label);
2741 underlying.Emit (ec);
2742 ig.Emit (OpCodes.Br, end_label);
2745 ig.MarkLabel (false_label);
2746 ig.Emit (OpCodes.Ldc_I4_0);
2747 ig.Emit (OpCodes.Br, end_label);
2749 ig.MarkLabel (true_label);
2750 ig.Emit (OpCodes.Ldc_I4_1);
2752 ig.MarkLabel (end_label);
2755 void EmitComparision (EmitContext ec)
2757 ILGenerator ig = ec.ig;
2759 Label is_null_label = ig.DefineLabel ();
2760 Label end_label = ig.DefineLabel ();
2762 if (left_unwrap != null) {
2763 left_unwrap.EmitCheck (ec);
2764 ig.Emit (OpCodes.Brfalse, is_null_label);
2767 if (right_unwrap != null) {
2768 right_unwrap.EmitCheck (ec);
2769 ig.Emit (OpCodes.Brfalse, is_null_label);
2772 underlying.Emit (ec);
2773 ig.Emit (OpCodes.Br, end_label);
2775 ig.MarkLabel (is_null_label);
2776 ig.Emit (OpCodes.Ldc_I4_0);
2778 ig.MarkLabel (end_label);
2781 public override void Emit (EmitContext ec)
2786 } else if (is_equality) {
2789 } else if (is_comparision) {
2790 EmitComparision (ec);
2794 ILGenerator ig = ec.ig;
2796 Label is_null_label = ig.DefineLabel ();
2797 Label end_label = ig.DefineLabel ();
2799 if (left_unwrap != null) {
2800 left_unwrap.EmitCheck (ec);
2801 ig.Emit (OpCodes.Brfalse, is_null_label);
2804 if (right_unwrap != null) {
2805 right_unwrap.EmitCheck (ec);
2806 ig.Emit (OpCodes.Brfalse, is_null_label);
2809 underlying.Emit (ec);
2810 ig.Emit (OpCodes.Br, end_label);
2812 ig.MarkLabel (is_null_label);
2813 null_value.Emit (ec);
2815 ig.MarkLabel (end_label);
2819 public class OperatorTrueOrFalse : Expression
2821 public readonly bool IsTrue;
2826 public OperatorTrueOrFalse (Expression expr, bool is_true, Location loc)
2828 this.IsTrue = is_true;
2833 public override Expression DoResolve (EmitContext ec)
2835 unwrap = new Unwrap (expr, loc);
2836 expr = unwrap.Resolve (ec);
2840 if (unwrap.Type != TypeManager.bool_type)
2843 type = TypeManager.bool_type;
2844 eclass = ExprClass.Value;
2848 public override void Emit (EmitContext ec)
2850 ILGenerator ig = ec.ig;
2852 Label is_null_label = ig.DefineLabel ();
2853 Label end_label = ig.DefineLabel ();
2855 unwrap.EmitCheck (ec);
2856 ig.Emit (OpCodes.Brfalse, is_null_label);
2860 ig.Emit (OpCodes.Ldc_I4_0);
2861 ig.Emit (OpCodes.Ceq);
2863 ig.Emit (OpCodes.Br, end_label);
2865 ig.MarkLabel (is_null_label);
2866 ig.Emit (OpCodes.Ldc_I4_0);
2868 ig.MarkLabel (end_label);
2872 public class NullCoalescingOperator : Expression
2874 Expression left, right;
2878 public NullCoalescingOperator (Expression left, Expression right, Location loc)
2884 eclass = ExprClass.Value;
2887 public override Expression DoResolve (EmitContext ec)
2892 left = left.Resolve (ec);
2896 right = right.Resolve (ec);
2900 Type ltype = left.Type, rtype = right.Type;
2902 if (!TypeManager.IsNullableType (ltype) && ltype.IsValueType) {
2903 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
2907 if (TypeManager.IsNullableType (ltype)) {
2908 NullableInfo info = new NullableInfo (ltype);
2910 unwrap = (Unwrap) new Unwrap (left, loc).Resolve (ec);
2914 expr = Convert.ImplicitConversion (ec, right, info.UnderlyingType, loc);
2922 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
2928 if (unwrap != null) {
2929 expr = Convert.ImplicitConversion (ec, unwrap, rtype, loc);
2938 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
2942 public override void Emit (EmitContext ec)
2944 ILGenerator ig = ec.ig;
2946 Label is_null_label = ig.DefineLabel ();
2947 Label end_label = ig.DefineLabel ();
2949 if (unwrap != null) {
2950 unwrap.EmitCheck (ec);
2951 ig.Emit (OpCodes.Brfalse, is_null_label);
2954 ig.Emit (OpCodes.Br, end_label);
2956 ig.MarkLabel (is_null_label);
2959 ig.MarkLabel (end_label);
2962 ig.Emit (OpCodes.Dup);
2963 ig.Emit (OpCodes.Brtrue, end_label);
2965 ig.MarkLabel (is_null_label);
2967 ig.Emit (OpCodes.Pop);
2970 ig.MarkLabel (end_label);
2975 public class LiftedUnaryMutator : ExpressionStatement
2977 public readonly UnaryMutator.Mode Mode;
2978 Expression expr, null_value;
2979 UnaryMutator underlying;
2982 public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
2988 eclass = ExprClass.Value;
2991 public override Expression DoResolve (EmitContext ec)
2993 expr = expr.Resolve (ec);
2997 unwrap = (Unwrap) new Unwrap (expr, loc).Resolve (ec);
3001 underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
3002 if (underlying == null)
3005 null_value = new NullableLiteral (expr.Type, loc).Resolve (ec);
3006 if (null_value == null)
3013 void DoEmit (EmitContext ec, bool is_expr)
3015 ILGenerator ig = ec.ig;
3016 Label is_null_label = ig.DefineLabel ();
3017 Label end_label = ig.DefineLabel ();
3019 unwrap.EmitCheck (ec);
3020 ig.Emit (OpCodes.Brfalse, is_null_label);
3023 underlying.Emit (ec);
3025 underlying.EmitStatement (ec);
3026 ig.Emit (OpCodes.Br, end_label);
3028 ig.MarkLabel (is_null_label);
3030 null_value.Emit (ec);
3032 ig.MarkLabel (end_label);
3035 public override void Emit (EmitContext ec)
3040 public override void EmitStatement (EmitContext ec)