2 // generic.cs: Generics support
4 // Authors: Martin Baulig (martin@ximian.com)
5 // Miguel de Icaza (miguel@ximian.com)
7 // Licensed under the terms of the GNU GPL
9 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
10 // (C) 2004 Novell, Inc
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.Globalization;
16 using System.Collections;
18 using System.Text.RegularExpressions;
20 namespace Mono.CSharp {
22 public abstract class GenericConstraints {
23 public abstract GenericParameterAttributes Attributes {
27 public bool HasConstructorConstraint {
28 get { return (Attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0; }
31 public bool HasReferenceTypeConstraint {
32 get { return (Attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0; }
35 public bool HasValueTypeConstraint {
36 get { return (Attributes & GenericParameterAttributes.ValueTypeConstraint) != 0; }
39 public virtual bool HasClassConstraint {
40 get { return ClassConstraint != null; }
43 public abstract Type ClassConstraint {
47 public abstract Type[] InterfaceConstraints {
51 public abstract Type EffectiveBaseClass {
56 // Returns whether the type parameter is "known to be a reference type".
58 public virtual bool IsReferenceType {
60 if (HasReferenceTypeConstraint)
62 if (HasValueTypeConstraint)
65 if (ClassConstraint != null) {
66 if (ClassConstraint.IsValueType)
69 if (ClassConstraint != TypeManager.object_type)
73 foreach (Type t in InterfaceConstraints) {
74 if (!t.IsGenericParameter)
77 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
78 if ((gc != null) && gc.IsReferenceType)
87 // Returns whether the type parameter is "known to be a value type".
89 public virtual bool IsValueType {
91 if (HasValueTypeConstraint)
93 if (HasReferenceTypeConstraint)
96 if (ClassConstraint != null) {
97 if (!ClassConstraint.IsValueType)
100 if (ClassConstraint != TypeManager.value_type)
104 foreach (Type t in InterfaceConstraints) {
105 if (!t.IsGenericParameter)
108 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
109 if ((gc != null) && gc.IsValueType)
118 public enum SpecialConstraint
126 // Tracks the constraints for a type parameter
128 public class Constraints : GenericConstraints {
130 ArrayList constraints;
134 // name is the identifier, constraints is an arraylist of
135 // Expressions (with types) or `true' for the constructor constraint.
137 public Constraints (string name, ArrayList constraints,
141 this.constraints = constraints;
145 public string TypeParameter {
151 GenericParameterAttributes attrs;
152 TypeExpr class_constraint;
153 ArrayList iface_constraints;
154 ArrayList type_param_constraints;
155 int num_constraints, first_constraint;
156 Type class_constraint_type;
157 Type[] iface_constraint_types;
158 Type effective_base_type;
160 public bool Resolve (EmitContext ec)
162 iface_constraints = new ArrayList ();
163 type_param_constraints = new ArrayList ();
165 foreach (object obj in constraints) {
166 if (HasConstructorConstraint) {
167 Report.Error (401, loc,
168 "The new() constraint must be last.");
172 if (obj is SpecialConstraint) {
173 SpecialConstraint sc = (SpecialConstraint) obj;
175 if (sc == SpecialConstraint.Constructor) {
176 if (!HasValueTypeConstraint) {
177 attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
182 451, loc, "The new () constraint " +
183 "cannot be used with the `struct' " +
188 if ((num_constraints > 0) || HasReferenceTypeConstraint || HasValueTypeConstraint) {
189 Report.Error (449, loc,
190 "The `class' or `struct' " +
191 "constraint must be first");
195 if (sc == SpecialConstraint.ReferenceType)
196 attrs |= GenericParameterAttributes.ReferenceTypeConstraint;
198 attrs |= GenericParameterAttributes.ValueTypeConstraint;
203 if (obj is ConstructedType) {
204 ConstructedType cexpr = (ConstructedType) obj;
205 if (!cexpr.ResolveConstructedType (ec))
209 expr = ((Expression) obj).ResolveAsTypeTerminal (ec);
214 TypeParameterExpr texpr = expr as TypeParameterExpr;
216 type_param_constraints.Add (expr);
217 else if (expr.IsInterface)
218 iface_constraints.Add (expr);
219 else if (class_constraint != null) {
220 Report.Error (406, loc,
221 "`{0}': the class constraint for `{1}' " +
222 "must come before any other constraints.",
225 } else if (HasReferenceTypeConstraint || HasValueTypeConstraint) {
226 Report.Error (450, loc, "`{0}': cannot specify both " +
227 "a constraint class and the `class' " +
228 "or `struct' constraint.", expr.Name);
231 class_constraint = expr;
239 bool CheckTypeParameterConstraints (TypeParameter tparam, Hashtable seen)
241 seen.Add (tparam, true);
243 Constraints constraints = tparam.Constraints;
244 if (constraints == null)
247 if (constraints.HasValueTypeConstraint) {
248 Report.Error (456, loc, "Type parameter `{0}' has " +
249 "the `struct' constraint, so it cannot " +
250 "be used as a constraint for `{1}'",
255 if (constraints.type_param_constraints == null)
258 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
259 if (seen.Contains (expr.TypeParameter)) {
260 Report.Error (454, loc, "Circular constraint " +
261 "dependency involving `{0}' and `{1}'",
262 tparam.Name, expr.Name);
266 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
273 public bool ResolveTypes (EmitContext ec)
275 if (effective_base_type != null)
278 foreach (object obj in constraints) {
279 ConstructedType cexpr = obj as ConstructedType;
283 if (!cexpr.CheckConstraints (ec))
287 foreach (TypeParameterExpr expr in type_param_constraints) {
288 Hashtable seen = new Hashtable ();
289 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
293 ArrayList list = new ArrayList ();
295 foreach (TypeExpr iface_constraint in iface_constraints) {
296 foreach (Type type in list) {
297 if (!type.Equals (iface_constraint.Type))
300 Report.Error (405, loc,
301 "Duplicate constraint `{0}' for type " +
302 "parameter `{1}'.", iface_constraint.Type,
307 list.Add (iface_constraint.Type);
310 foreach (TypeParameterExpr expr in type_param_constraints) {
311 foreach (Type type in list) {
312 if (!type.Equals (expr.Type))
315 Report.Error (405, loc,
316 "Duplicate constraint `{0}' for type " +
317 "parameter `{1}'.", expr.Type, name);
321 list.Add (expr.Type);
324 iface_constraint_types = new Type [list.Count];
325 list.CopyTo (iface_constraint_types, 0);
327 if (class_constraint != null) {
328 class_constraint_type = class_constraint.Type;
329 if (class_constraint_type == null)
332 if (class_constraint_type.IsSealed) {
333 Report.Error (701, loc,
334 "`{0}' is not a valid bound. Bounds " +
335 "must be interfaces or non sealed " +
336 "classes", class_constraint_type);
340 if ((class_constraint_type == TypeManager.array_type) ||
341 (class_constraint_type == TypeManager.delegate_type) ||
342 (class_constraint_type == TypeManager.enum_type) ||
343 (class_constraint_type == TypeManager.value_type) ||
344 (class_constraint_type == TypeManager.object_type)) {
345 Report.Error (702, loc,
346 "Bound cannot be special class `{0}'",
347 class_constraint_type);
352 if (class_constraint_type != null)
353 effective_base_type = class_constraint_type;
354 else if (HasValueTypeConstraint)
355 effective_base_type = TypeManager.value_type;
357 effective_base_type = TypeManager.object_type;
362 public bool CheckDependencies (EmitContext ec)
364 foreach (TypeParameterExpr expr in type_param_constraints) {
365 if (!CheckDependencies (expr.TypeParameter, ec))
372 bool CheckDependencies (TypeParameter tparam, EmitContext ec)
374 Constraints constraints = tparam.Constraints;
375 if (constraints == null)
378 if (HasValueTypeConstraint && constraints.HasClassConstraint) {
379 Report.Error (455, loc, "Type parameter `{0}' inherits " +
380 "conflicting constraints `{1}' and `{2}'",
381 name, constraints.ClassConstraint,
386 if (HasClassConstraint && constraints.HasClassConstraint) {
387 Type t1 = ClassConstraint;
388 TypeExpr e1 = class_constraint;
389 Type t2 = constraints.ClassConstraint;
390 TypeExpr e2 = constraints.class_constraint;
392 if (!Convert.ImplicitReferenceConversionExists (ec, e1, t2) &&
393 !Convert.ImplicitReferenceConversionExists (ec, e2, t1)) {
394 Report.Error (455, loc,
395 "Type parameter `{0}' inherits " +
396 "conflicting constraints `{1}' and `{2}'",
402 if (constraints.type_param_constraints == null)
405 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
406 if (!CheckDependencies (expr.TypeParameter, ec))
413 public void Define (GenericTypeParameterBuilder type)
415 type.SetGenericParameterAttributes (attrs);
418 public override GenericParameterAttributes Attributes {
419 get { return attrs; }
422 public override bool HasClassConstraint {
423 get { return class_constraint != null; }
426 public override Type ClassConstraint {
427 get { return class_constraint_type; }
430 public override Type[] InterfaceConstraints {
431 get { return iface_constraint_types; }
434 public override Type EffectiveBaseClass {
435 get { return effective_base_type; }
438 internal bool IsSubclassOf (Type t)
440 if ((class_constraint_type != null) &&
441 class_constraint_type.IsSubclassOf (t))
444 if (iface_constraint_types == null)
447 foreach (Type iface in iface_constraint_types) {
448 if (TypeManager.IsSubclassOf (iface, t))
455 public bool CheckInterfaceMethod (EmitContext ec, GenericConstraints gc)
457 if (gc.Attributes != attrs)
460 if (HasClassConstraint != gc.HasClassConstraint)
462 if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
465 int gc_icount = gc.InterfaceConstraints != null ?
466 gc.InterfaceConstraints.Length : 0;
467 int icount = InterfaceConstraints != null ?
468 InterfaceConstraints.Length : 0;
470 if (gc_icount != icount)
473 foreach (Type iface in gc.InterfaceConstraints) {
475 foreach (Type check in InterfaceConstraints) {
476 if (TypeManager.IsEqual (iface, check)) {
491 // This type represents a generic type parameter
493 public class TypeParameter : MemberCore, IMemberContainer {
495 GenericConstraints gc;
496 Constraints constraints;
498 GenericTypeParameterBuilder type;
500 public TypeParameter (TypeContainer parent, string name,
501 Constraints constraints, Location loc)
502 : base (parent, new MemberName (name), null, loc)
505 this.constraints = constraints;
509 public GenericConstraints GenericConstraints {
511 return gc != null ? gc : constraints;
515 public Constraints Constraints {
521 public bool HasConstructorConstraint {
523 if (constraints != null)
524 return constraints.HasConstructorConstraint;
536 public bool Resolve (DeclSpace ds)
538 if (constraints != null) {
539 if (!constraints.Resolve (ds.EmitContext)) {
548 public void Define (GenericTypeParameterBuilder type)
550 if (this.type != null)
551 throw new InvalidOperationException ();
554 TypeManager.AddTypeParameter (type, this);
557 public void DefineConstraints ()
559 if (constraints != null)
560 constraints.Define (type);
563 public bool ResolveType (EmitContext ec)
565 if (constraints != null) {
566 if (!constraints.ResolveTypes (ec)) {
575 public bool DefineType (EmitContext ec)
577 return DefineType (ec, null, null, false);
580 public bool DefineType (EmitContext ec, MethodBuilder builder,
581 MethodInfo implementing, bool is_override)
583 if (!ResolveType (ec))
586 if (implementing != null) {
587 if (is_override && (constraints != null)) {
589 460, loc, "Constraints for override and " +
590 "explicit interface implementation methods " +
591 "are inherited from the base method so they " +
592 "cannot be specified directly");
596 MethodBase mb = implementing;
597 if (mb.Mono_IsInflatedMethod)
598 mb = mb.GetGenericMethodDefinition ();
600 int pos = type.GenericParameterPosition;
601 ParameterData pd = Invocation.GetParameterData (mb);
602 GenericConstraints temp_gc = pd.GenericConstraints (pos);
603 Type mparam = mb.GetGenericArguments () [pos];
606 gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
607 else if (constraints != null)
608 gc = new InflatedConstraints (constraints, implementing.DeclaringType);
611 if (constraints != null) {
614 else if (!constraints.CheckInterfaceMethod (ec, gc))
617 if (!is_override && (temp_gc != null))
622 Report.SymbolRelatedToPreviousError (implementing);
625 425, loc, "The constraints for type " +
626 "parameter `{0}' of method `{1}' must match " +
627 "the constraints for type parameter `{2}' " +
628 "of interface method `{3}'. Consider using " +
629 "an explicit interface implementation instead",
630 Name, TypeManager.CSharpSignature (builder),
631 mparam, TypeManager.CSharpSignature (mb));
635 gc = (GenericConstraints) constraints;
641 if (gc.HasClassConstraint)
642 type.SetBaseTypeConstraint (gc.ClassConstraint);
644 type.SetInterfaceConstraints (gc.InterfaceConstraints);
645 TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
650 public bool CheckDependencies (EmitContext ec)
652 if (constraints != null)
653 return constraints.CheckDependencies (ec);
658 public override string DocCommentHeader {
660 throw new InvalidOperationException (
661 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
669 public override bool Define ()
674 protected override void VerifyObsoleteAttribute ()
677 public override void ApplyAttributeBuilder (Attribute a,
678 CustomAttributeBuilder cb)
681 public override AttributeTargets AttributeTargets {
683 return (AttributeTargets) 0;
687 public override string[] ValidAttributeTargets {
689 return new string [0];
697 string IMemberContainer.Name {
701 MemberCache IMemberContainer.BaseCache {
705 bool IMemberContainer.IsInterface {
709 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
711 return FindMembers (mt, bf, null, null);
714 MemberCache IMemberContainer.MemberCache {
718 public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
719 MemberFilter filter, object criteria)
721 if (constraints == null)
722 return MemberList.Empty;
724 ArrayList members = new ArrayList ();
726 GenericConstraints gc = (GenericConstraints) constraints;
728 if (gc.HasClassConstraint) {
729 MemberList list = TypeManager.FindMembers (
730 gc.ClassConstraint, mt, bf, filter, criteria);
732 members.AddRange (list);
735 foreach (Type t in gc.InterfaceConstraints) {
736 MemberList list = TypeManager.FindMembers (
737 t, mt, bf, filter, criteria);
739 members.AddRange (list);
742 return new MemberList (members);
745 public bool IsSubclassOf (Type t)
750 if (constraints != null)
751 return constraints.IsSubclassOf (t);
756 public override string ToString ()
758 return "TypeParameter[" + name + "]";
761 protected class InflatedConstraints : GenericConstraints
763 GenericConstraints gc;
765 Type class_constraint;
766 Type[] iface_constraints;
770 public InflatedConstraints (GenericConstraints gc, Type declaring)
773 this.declaring = declaring;
775 dargs = TypeManager.GetTypeArguments (declaring);
777 ArrayList list = new ArrayList ();
778 if (gc.HasClassConstraint)
779 list.Add (inflate (gc.ClassConstraint));
780 foreach (Type iface in gc.InterfaceConstraints)
781 list.Add (inflate (iface));
783 bool has_class_constr = false;
784 if (list.Count > 0) {
785 Type first = (Type) list [0];
786 has_class_constr = !first.IsInterface && !first.IsGenericParameter;
789 if ((list.Count > 0) && has_class_constr) {
790 class_constraint = (Type) list [0];
791 iface_constraints = new Type [list.Count - 1];
792 list.CopyTo (1, iface_constraints, 0, list.Count - 1);
794 iface_constraints = new Type [list.Count];
795 list.CopyTo (iface_constraints, 0);
798 if (HasValueTypeConstraint)
799 base_type = TypeManager.value_type;
800 else if (class_constraint != null)
801 base_type = class_constraint;
803 base_type = TypeManager.object_type;
806 Type inflate (Type t)
810 if (t.IsGenericParameter)
811 return dargs [t.GenericParameterPosition];
812 if (t.IsGenericInstance) {
813 t = t.GetGenericTypeDefinition ();
814 t = t.BindGenericParameters (dargs);
820 public override GenericParameterAttributes Attributes {
821 get { return gc.Attributes; }
824 public override Type ClassConstraint {
825 get { return class_constraint; }
828 public override Type EffectiveBaseClass {
829 get { return base_type; }
832 public override Type[] InterfaceConstraints {
833 get { return iface_constraints; }
839 // This type represents a generic type parameter reference.
841 // These expressions are born in a fully resolved state.
843 public class TypeParameterExpr : TypeExpr {
844 TypeParameter type_parameter;
846 public override string Name {
848 return type_parameter.Name;
852 public override string FullName {
854 return type_parameter.Name;
858 public TypeParameter TypeParameter {
860 return type_parameter;
864 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
866 this.type_parameter = type_parameter;
870 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
872 type = type_parameter.Type;
877 public override bool IsInterface {
878 get { return false; }
881 public override bool CheckAccessLevel (DeclSpace ds)
886 public void Error_CannotUseAsUnmanagedType (Location loc)
888 Report.Error (-203, loc, "Can not use type parameter as unamanged type");
892 public class TypeArguments {
893 public readonly Location Location;
900 public TypeArguments (Location loc)
902 args = new ArrayList ();
906 public TypeArguments (int dimension, Location loc)
908 this.dimension = dimension;
912 public void Add (Expression type)
915 throw new InvalidOperationException ();
920 public void Add (TypeArguments new_args)
923 throw new InvalidOperationException ();
925 args.AddRange (new_args.args);
928 public string[] GetDeclarations ()
930 string[] ret = new string [args.Count];
931 for (int i = 0; i < args.Count; i++) {
932 SimpleName sn = args [i] as SimpleName;
938 Report.Error (81, Location, "Type parameter declaration " +
939 "must be an identifier not a type");
945 public Type[] Arguments {
951 public bool HasTypeArguments {
953 return has_type_args;
966 public bool IsUnbound {
968 return dimension > 0;
972 public override string ToString ()
974 StringBuilder s = new StringBuilder ();
977 for (int i = 0; i < count; i++){
979 // FIXME: Use TypeManager.CSharpname once we have the type
982 s.Append (args [i].ToString ());
986 return s.ToString ();
989 public bool Resolve (EmitContext ec)
991 int count = args.Count;
994 atypes = new Type [count];
996 for (int i = 0; i < count; i++){
997 TypeExpr te = ((Expression) args [i]).ResolveAsTypeTerminal (ec);
1002 if (te is TypeParameterExpr)
1003 has_type_args = true;
1005 if (te.Type.IsPointer) {
1006 Report.Error (306, Location, "The type `{0}' may not be used " +
1007 "as a type argument.", TypeManager.CSharpName (te.Type));
1011 atypes [i] = te.Type;
1017 public class ConstructedType : TypeExpr {
1018 string name, full_name;
1020 Type[] gen_params, atypes;
1023 public ConstructedType (string name, TypeArguments args, Location l)
1026 this.name = MemberName.MakeName (name, args.Count);
1029 eclass = ExprClass.Type;
1030 full_name = name + "<" + args.ToString () + ">";
1033 public ConstructedType (string name, TypeParameter[] type_params, Location l)
1034 : this (type_params, l)
1039 full_name = name + "<" + args.ToString () + ">";
1042 public ConstructedType (FullNamedExpression fname, TypeArguments args, Location l)
1045 this.name = fname.FullName;
1048 eclass = ExprClass.Type;
1049 full_name = name + "<" + args.ToString () + ">";
1052 protected ConstructedType (TypeArguments args, Location l)
1057 eclass = ExprClass.Type;
1060 protected ConstructedType (TypeParameter[] type_params, Location l)
1064 args = new TypeArguments (l);
1065 foreach (TypeParameter type_param in type_params)
1066 args.Add (new TypeParameterExpr (type_param, l));
1068 eclass = ExprClass.Type;
1071 public ConstructedType (Type t, TypeParameter[] type_params, Location l)
1072 : this (type_params, l)
1074 gt = t.GetGenericTypeDefinition ();
1076 this.name = gt.FullName;
1077 full_name = gt.FullName + "<" + args.ToString () + ">";
1080 public ConstructedType (Type t, TypeArguments args, Location l)
1083 gt = t.GetGenericTypeDefinition ();
1085 this.name = gt.FullName;
1086 full_name = gt.FullName + "<" + args.ToString () + ">";
1089 public TypeArguments TypeArguments {
1090 get { return args; }
1093 protected string DeclarationName {
1095 StringBuilder sb = new StringBuilder ();
1096 sb.Append (gt.FullName);
1098 for (int i = 0; i < gen_params.Length; i++) {
1101 sb.Append (gen_params [i]);
1104 return sb.ToString ();
1108 protected bool CheckConstraint (EmitContext ec, Type ptype, Expression expr,
1111 if (TypeManager.HasGenericArguments (ctype)) {
1112 Type[] types = TypeManager.GetTypeArguments (ctype);
1114 TypeArguments new_args = new TypeArguments (loc);
1116 for (int i = 0; i < types.Length; i++) {
1119 if (t.IsGenericParameter) {
1120 int pos = t.GenericParameterPosition;
1121 t = args.Arguments [pos];
1123 new_args.Add (new TypeExpression (t, loc));
1126 TypeExpr ct = new ConstructedType (ctype, new_args, loc);
1127 if (ct.ResolveAsTypeTerminal (ec) == null)
1132 return Convert.ImplicitStandardConversionExists (ec, expr, ctype);
1135 protected bool CheckConstraints (EmitContext ec, int index)
1137 Type atype = atypes [index];
1138 Type ptype = gen_params [index];
1143 Expression aexpr = new EmptyExpression (atype);
1145 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1149 bool is_class, is_struct;
1150 if (atype.IsGenericParameter) {
1151 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1153 is_class = agc.HasReferenceTypeConstraint;
1154 is_struct = agc.HasValueTypeConstraint;
1156 is_class = is_struct = false;
1159 is_class = atype.IsClass;
1160 is_struct = atype.IsValueType;
1164 // First, check the `class' and `struct' constraints.
1166 if (gc.HasReferenceTypeConstraint && !is_class) {
1167 Report.Error (452, loc, "The type `{0}' must be " +
1168 "a reference type in order to use it " +
1169 "as type parameter `{1}' in the " +
1170 "generic type or method `{2}'.",
1171 atype, ptype, DeclarationName);
1173 } else if (gc.HasValueTypeConstraint && !is_struct) {
1174 Report.Error (453, loc, "The type `{0}' must be " +
1175 "a value type in order to use it " +
1176 "as type parameter `{1}' in the " +
1177 "generic type or method `{2}'.",
1178 atype, ptype, DeclarationName);
1183 // The class constraint comes next.
1185 if (gc.HasClassConstraint) {
1186 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint)) {
1187 Report.Error (309, loc, "The type `{0}' must be " +
1188 "convertible to `{1}' in order to " +
1189 "use it as parameter `{2}' in the " +
1190 "generic type or method `{3}'",
1191 atype, gc.ClassConstraint, ptype, DeclarationName);
1197 // Now, check the interface constraints.
1199 foreach (Type it in gc.InterfaceConstraints) {
1201 if (it.IsGenericParameter)
1202 itype = atypes [it.GenericParameterPosition];
1206 if (!CheckConstraint (ec, ptype, aexpr, itype)) {
1207 Report.Error (309, loc, "The type `{0}' must be " +
1208 "convertible to `{1}' in order to " +
1209 "use it as parameter `{2}' in the " +
1210 "generic type or method `{3}'",
1211 atype, itype, ptype, DeclarationName);
1217 // Finally, check the constructor constraint.
1220 if (!gc.HasConstructorConstraint)
1223 if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
1226 MethodGroupExpr mg = Expression.MemberLookup (
1227 ec, atype, ".ctor", MemberTypes.Constructor,
1228 BindingFlags.Public | BindingFlags.Instance |
1229 BindingFlags.DeclaredOnly, loc)
1232 if (atype.IsAbstract || (mg == null) || !mg.IsInstance) {
1233 Report.Error (310, loc, "The type `{0}' must have a public " +
1234 "parameterless constructor in order to use it " +
1235 "as parameter `{1}' in the generic type or " +
1236 "method `{2}'", atype, ptype, DeclarationName);
1243 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
1245 if (!ResolveConstructedType (ec))
1251 public bool CheckConstraints (EmitContext ec)
1253 for (int i = 0; i < gen_params.Length; i++) {
1254 if (!CheckConstraints (ec, i))
1261 public override TypeExpr ResolveAsTypeTerminal (EmitContext ec)
1263 if (base.ResolveAsTypeTerminal (ec) == null)
1266 if (!CheckConstraints (ec))
1272 public bool ResolveConstructedType (EmitContext ec)
1277 return DoResolveType (ec);
1280 // First, resolve the generic type.
1283 Type nested = ec.DeclSpace.FindNestedType (loc, name, out ds);
1284 if (nested != null) {
1285 gt = nested.GetGenericTypeDefinition ();
1287 TypeArguments new_args = new TypeArguments (loc);
1289 foreach (TypeParameter param in ds.TypeParameters)
1290 new_args.Add (new TypeParameterExpr (param, loc));
1292 new_args.Add (args);
1295 return DoResolveType (ec);
1301 SimpleName sn = new SimpleName (name, loc);
1302 TypeExpr resolved = sn.ResolveAsTypeTerminal (ec);
1303 if (resolved == null)
1308 Report.Error (246, loc, "Cannot find type `{0}'<...>",
1313 num_args = TypeManager.GetNumberOfTypeArguments (t);
1314 if (num_args == 0) {
1315 Report.Error (308, loc,
1316 "The non-generic type `{0}' cannot " +
1317 "be used with type arguments.",
1318 TypeManager.CSharpName (t));
1322 gt = t.GetGenericTypeDefinition ();
1323 return DoResolveType (ec);
1326 bool DoResolveType (EmitContext ec)
1329 // Resolve the arguments.
1331 if (args.Resolve (ec) == false)
1334 gen_params = gt.GetGenericArguments ();
1335 atypes = args.Arguments;
1337 if (atypes.Length != gen_params.Length) {
1338 Report.Error (305, loc,
1339 "Using the generic type `{0}' " +
1340 "requires {1} type arguments",
1341 TypeManager.GetFullName (gt),
1347 // Now bind the parameters.
1349 type = gt.BindGenericParameters (atypes);
1353 public Expression GetSimpleName (EmitContext ec)
1355 return new SimpleName (Basename, args, loc);
1358 public override bool CheckAccessLevel (DeclSpace ds)
1360 return ds.CheckAccessLevel (gt);
1363 public override bool AsAccessible (DeclSpace ds, int flags)
1365 return ds.AsAccessible (gt, flags);
1368 public override bool IsClass {
1369 get { return gt.IsClass; }
1372 public override bool IsValueType {
1373 get { return gt.IsValueType; }
1376 public override bool IsInterface {
1377 get { return gt.IsInterface; }
1380 public override bool IsSealed {
1381 get { return gt.IsSealed; }
1384 public override bool IsAttribute {
1385 get { return false; }
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 string Basename {
1407 int pos = name.LastIndexOf ('`');
1409 return name.Substring (0, pos);
1415 public override string Name {
1422 public override string FullName {
1429 public class GenericMethod : DeclSpace
1431 public GenericMethod (NamespaceEntry ns, TypeContainer parent,
1432 MemberName name, Location l)
1433 : base (ns, parent, name, null, l)
1436 public override TypeBuilder DefineType ()
1438 throw new Exception ();
1441 public override bool Define ()
1443 for (int i = 0; i < TypeParameters.Length; i++)
1444 if (!TypeParameters [i].Resolve (Parent))
1450 public bool Define (MethodBuilder mb, Type return_type)
1455 GenericTypeParameterBuilder[] gen_params;
1456 string[] names = MemberName.TypeArguments.GetDeclarations ();
1457 gen_params = mb.DefineGenericParameters (names);
1458 for (int i = 0; i < TypeParameters.Length; i++)
1459 TypeParameters [i].Define (gen_params [i]);
1461 ec = new EmitContext (
1462 this, this, Location, null, return_type, ModFlags, false);
1464 for (int i = 0; i < TypeParameters.Length; i++) {
1465 if (!TypeParameters [i].ResolveType (ec))
1472 public bool DefineType (EmitContext ec, MethodBuilder mb,
1473 MethodInfo implementing, bool is_override)
1475 for (int i = 0; i < TypeParameters.Length; i++)
1476 if (!TypeParameters [i].DefineType (
1477 ec, mb, implementing, is_override))
1483 public override bool DefineMembers (TypeContainer parent)
1488 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1489 MemberFilter filter, object criteria)
1491 throw new Exception ();
1494 public override MemberCache MemberCache {
1500 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1505 protected override void VerifyObsoleteAttribute()
1510 public override AttributeTargets AttributeTargets {
1512 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1516 public override string DocCommentHeader {
1517 get { return "M:"; }
1521 public class DefaultValueExpression : Expression
1524 LocalTemporary temp_storage;
1526 public DefaultValueExpression (Expression expr, Location loc)
1532 public override Expression DoResolve (EmitContext ec)
1534 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
1539 if (type.IsGenericParameter || TypeManager.IsValueType (type))
1540 temp_storage = new LocalTemporary (ec, type);
1542 eclass = ExprClass.Variable;
1546 public override void Emit (EmitContext ec)
1548 if (temp_storage != null) {
1549 temp_storage.AddressOf (ec, AddressOp.LoadStore);
1550 ec.ig.Emit (OpCodes.Initobj, type);
1551 temp_storage.Emit (ec);
1553 ec.ig.Emit (OpCodes.Ldnull);
1557 public class NullableType : TypeExpr
1559 Expression underlying;
1561 public NullableType (Expression underlying, Location l)
1563 this.underlying = underlying;
1566 eclass = ExprClass.Type;
1569 public override string Name {
1570 get { return underlying.ToString () + "?"; }
1573 public override string FullName {
1574 get { return underlying.ToString () + "?"; }
1577 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
1579 TypeArguments args = new TypeArguments (loc);
1580 args.Add (underlying);
1582 ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
1583 return ctype.ResolveAsTypeTerminal (ec);
1587 public partial class TypeManager
1590 // A list of core types that the compiler requires or uses
1592 static public Type new_constraint_attr_type;
1593 static public Type activator_type;
1594 static public Type generic_ienumerator_type;
1595 static public Type generic_ienumerable_type;
1596 static public Type generic_nullable_type;
1599 // Tracks the generic parameters.
1601 static PtrHashtable builder_to_type_param;
1604 // These methods are called by code generated by the compiler
1606 static public MethodInfo activator_create_instance;
1608 static void InitGenerics ()
1610 builder_to_type_param = new PtrHashtable ();
1613 static void CleanUpGenerics ()
1615 builder_to_type_param = null;
1618 static void InitGenericCoreTypes ()
1620 activator_type = CoreLookupType ("System.Activator");
1621 new_constraint_attr_type = CoreLookupType (
1622 "System.Runtime.CompilerServices.NewConstraintAttribute");
1624 generic_ienumerator_type = CoreLookupType ("System.Collections.Generic.IEnumerator", 1);
1625 generic_ienumerable_type = CoreLookupType ("System.Collections.Generic.IEnumerable", 1);
1626 generic_nullable_type = CoreLookupType ("System.Nullable", 1);
1629 static void InitGenericCodeHelpers ()
1632 Type [] type_arg = { type_type };
1633 activator_create_instance = GetMethod (
1634 activator_type, "CreateInstance", type_arg);
1637 static Type CoreLookupType (string name, int arity)
1639 return CoreLookupType (MemberName.MakeName (name, arity));
1642 public static void AddTypeParameter (Type t, TypeParameter tparam)
1644 if (!builder_to_type_param.Contains (t))
1645 builder_to_type_param.Add (t, tparam);
1648 public static TypeContainer LookupGenericTypeContainer (Type t)
1650 while (t.IsGenericInstance)
1651 t = t.GetGenericTypeDefinition ();
1653 return LookupTypeContainer (t);
1656 public static TypeParameter LookupTypeParameter (Type t)
1658 return (TypeParameter) builder_to_type_param [t];
1661 public static bool HasConstructorConstraint (Type t)
1663 GenericConstraints gc = GetTypeParameterConstraints (t);
1667 return (gc.Attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0;
1670 public static GenericConstraints GetTypeParameterConstraints (Type t)
1672 if (!t.IsGenericParameter)
1673 throw new InvalidOperationException ();
1675 TypeParameter tparam = LookupTypeParameter (t);
1677 return tparam.GenericConstraints;
1679 return new ReflectionConstraints (t);
1682 public static bool IsGeneric (Type t)
1684 DeclSpace ds = (DeclSpace) builder_to_declspace [t];
1686 return ds.IsGeneric;
1689 public static bool HasGenericArguments (Type t)
1691 return GetNumberOfTypeArguments (t) > 0;
1694 public static int GetNumberOfTypeArguments (Type t)
1696 DeclSpace tc = LookupDeclSpace (t);
1698 return tc.IsGeneric ? tc.CountTypeParameters : 0;
1700 return t.HasGenericArguments ? t.GetGenericArguments ().Length : 0;
1703 public static Type[] GetTypeArguments (Type t)
1705 DeclSpace tc = LookupDeclSpace (t);
1708 return Type.EmptyTypes;
1710 TypeParameter[] tparam = tc.TypeParameters;
1711 Type[] ret = new Type [tparam.Length];
1712 for (int i = 0; i < tparam.Length; i++) {
1713 ret [i] = tparam [i].Type;
1714 if (ret [i] == null)
1715 throw new InternalErrorException ();
1720 return t.GetGenericArguments ();
1723 public static bool IsEqual (Type a, Type b)
1728 if ((a is TypeBuilder) && a.IsGenericTypeDefinition && b.IsGenericInstance) {
1730 // `a' is a generic type definition's TypeBuilder and `b' is a
1731 // generic instance of the same type.
1737 // void Test (Stack<T> stack) { }
1740 // The first argument of `Test' will be the generic instance
1741 // "Stack<!0>" - which is the same type than the "Stack" TypeBuilder.
1744 // We hit this via Closure.Filter() for gen-82.cs.
1746 if (a != b.GetGenericTypeDefinition ())
1749 Type[] aparams = a.GetGenericArguments ();
1750 Type[] bparams = b.GetGenericArguments ();
1752 if (aparams.Length != bparams.Length)
1755 for (int i = 0; i < aparams.Length; i++)
1756 if (!IsEqual (aparams [i], bparams [i]))
1762 if ((b is TypeBuilder) && b.IsGenericTypeDefinition && a.IsGenericInstance)
1763 return IsEqual (b, a);
1765 if (a.IsGenericParameter && b.IsGenericParameter) {
1766 if ((a.DeclaringMethod == null) || (b.DeclaringMethod == null))
1768 return a.GenericParameterPosition == b.GenericParameterPosition;
1771 if (a.IsArray && b.IsArray) {
1772 if (a.GetArrayRank () != b.GetArrayRank ())
1774 return IsEqual (a.GetElementType (), b.GetElementType ());
1777 if (a.IsGenericInstance && b.IsGenericInstance) {
1778 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
1781 Type[] aargs = a.GetGenericArguments ();
1782 Type[] bargs = b.GetGenericArguments ();
1784 if (aargs.Length != bargs.Length)
1787 for (int i = 0; i < aargs.Length; i++) {
1788 if (!IsEqual (aargs [i], bargs [i]))
1798 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_infered, Type[] method_infered)
1800 if (a.IsGenericParameter) {
1802 // If a is an array of a's type, they may never
1806 b = b.GetElementType ();
1812 // If b is a generic parameter or an actual type,
1813 // they may become equal:
1815 // class X<T,U> : I<T>, I<U>
1816 // class X<T> : I<T>, I<float>
1818 if (b.IsGenericParameter || !b.IsGenericInstance) {
1819 int pos = a.GenericParameterPosition;
1820 Type[] args = a.DeclaringMethod != null ? method_infered : class_infered;
1821 if (args [pos] == null) {
1826 return args [pos] == a;
1830 // We're now comparing a type parameter with a
1831 // generic instance. They may become equal unless
1832 // the type parameter appears anywhere in the
1833 // generic instance:
1835 // class X<T,U> : I<T>, I<X<U>>
1836 // -> error because you could instanciate it as
1839 // class X<T> : I<T>, I<X<T>> -> ok
1842 Type[] bargs = GetTypeArguments (b);
1843 for (int i = 0; i < bargs.Length; i++) {
1844 if (a.Equals (bargs [i]))
1851 if (b.IsGenericParameter)
1852 return MayBecomeEqualGenericTypes (b, a, class_infered, method_infered);
1855 // At this point, neither a nor b are a type parameter.
1857 // If one of them is a generic instance, let
1858 // MayBecomeEqualGenericInstances() compare them (if the
1859 // other one is not a generic instance, they can never
1863 if (a.IsGenericInstance || b.IsGenericInstance)
1864 return MayBecomeEqualGenericInstances (a, b, class_infered, method_infered);
1867 // If both of them are arrays.
1870 if (a.IsArray && b.IsArray) {
1871 if (a.GetArrayRank () != b.GetArrayRank ())
1874 a = a.GetElementType ();
1875 b = b.GetElementType ();
1877 return MayBecomeEqualGenericTypes (a, b, class_infered, method_infered);
1881 // Ok, two ordinary types.
1884 return a.Equals (b);
1888 // Checks whether two generic instances may become equal for some
1889 // particular instantiation (26.3.1).
1891 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
1892 Type[] class_infered, Type[] method_infered)
1894 if (!a.IsGenericInstance || !b.IsGenericInstance)
1896 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
1899 return MayBecomeEqualGenericInstances (
1900 GetTypeArguments (a), GetTypeArguments (b), class_infered, method_infered);
1903 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
1904 Type[] class_infered, Type[] method_infered)
1906 if (aargs.Length != bargs.Length)
1909 for (int i = 0; i < aargs.Length; i++) {
1910 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_infered, method_infered))
1917 public static bool IsEqualGenericInstance (Type type, Type parent)
1919 int tcount = GetNumberOfTypeArguments (type);
1920 int pcount = GetNumberOfTypeArguments (parent);
1922 if (type.IsGenericInstance)
1923 type = type.GetGenericTypeDefinition ();
1924 if (parent.IsGenericInstance)
1925 parent = parent.GetGenericTypeDefinition ();
1927 if (tcount != pcount)
1930 return type.Equals (parent);
1933 static public bool IsGenericMethod (MethodBase mb)
1935 if (mb.DeclaringType is TypeBuilder) {
1936 IMethodData method = (IMethodData) builder_to_method [mb];
1940 return method.GenericMethod != null;
1943 return mb.IsGenericMethodDefinition;
1950 static bool InferType (Type pt, Type at, Type[] infered)
1952 if (pt.IsGenericParameter && (pt.DeclaringMethod != null)) {
1953 int pos = pt.GenericParameterPosition;
1955 if (infered [pos] == null) {
1957 while (check.IsArray)
1958 check = check.GetElementType ();
1967 if (infered [pos] != at)
1973 if (!pt.ContainsGenericParameters) {
1974 if (at.ContainsGenericParameters)
1975 return InferType (at, pt, infered);
1982 (at.GetArrayRank () != pt.GetArrayRank ()))
1985 return InferType (pt.GetElementType (), at.GetElementType (), infered);
1990 (pt.GetArrayRank () != at.GetArrayRank ()))
1993 return InferType (pt.GetElementType (), at.GetElementType (), infered);
1996 if (pt.IsByRef && at.IsByRef)
1997 return InferType (pt.GetElementType (), at.GetElementType (), infered);
1998 ArrayList list = new ArrayList ();
1999 if (at.IsGenericInstance)
2002 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
2005 list.AddRange (TypeManager.GetInterfaces (at));
2008 bool found_one = false;
2010 foreach (Type type in list) {
2011 if (!type.IsGenericInstance)
2014 Type[] infered_types = new Type [infered.Length];
2016 if (!InferGenericInstance (pt, type, infered_types))
2019 for (int i = 0; i < infered_types.Length; i++) {
2020 if (infered [i] == null) {
2021 infered [i] = infered_types [i];
2025 if (infered [i] != infered_types [i])
2035 static bool InferGenericInstance (Type pt, Type at, Type[] infered_types)
2037 Type[] at_args = at.GetGenericArguments ();
2038 Type[] pt_args = pt.GetGenericArguments ();
2040 if (at_args.Length != pt_args.Length)
2043 for (int i = 0; i < at_args.Length; i++) {
2044 if (!InferType (pt_args [i], at_args [i], infered_types))
2048 for (int i = 0; i < infered_types.Length; i++) {
2049 if (infered_types [i] == null)
2056 public static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
2057 ref MethodBase method)
2059 if ((arguments == null) || !TypeManager.IsGenericMethod (method))
2064 if (arguments == null)
2067 arg_count = arguments.Count;
2069 ParameterData pd = Invocation.GetParameterData (method);
2071 int pd_count = pd.Count;
2076 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2079 if (pd_count - 1 > arg_count)
2082 if (pd_count == 1 && arg_count == 0)
2085 Type[] method_args = method.GetGenericArguments ();
2086 Type[] infered_types = new Type [method_args.Length];
2089 // If we have come this far, the case which
2090 // remains is when the number of parameters is
2091 // less than or equal to the argument count.
2093 for (int i = 0; i < pd_count - 1; ++i) {
2094 Argument a = (Argument) arguments [i];
2096 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2099 Type pt = pd.ParameterType (i);
2102 if (!InferType (pt, at, infered_types))
2106 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
2108 for (int i = pd_count - 1; i < arg_count; i++) {
2109 Argument a = (Argument) arguments [i];
2111 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2114 if (!InferType (element_type, a.Type, infered_types))
2118 for (int i = 0; i < infered_types.Length; i++)
2119 if (infered_types [i] == null)
2122 method = method.BindGenericParameters (infered_types);
2126 public static bool InferTypeArguments (Type[] param_types, Type[] arg_types, Type[] infered_types)
2128 if (infered_types == null)
2131 for (int i = 0; i < arg_types.Length; i++) {
2132 if (arg_types [i] == null)
2135 if (!InferType (param_types [i], arg_types [i], infered_types))
2139 for (int i = 0; i < infered_types.Length; i++)
2140 if (infered_types [i] == null)
2146 public static bool InferTypeArguments (EmitContext ec, ArrayList arguments,
2147 ref MethodBase method)
2149 if (!TypeManager.IsGenericMethod (method))
2153 if (arguments != null)
2154 arg_count = arguments.Count;
2158 ParameterData pd = Invocation.GetParameterData (method);
2159 if (arg_count != pd.Count)
2162 Type[] method_args = method.GetGenericArguments ();
2164 bool is_open = false;
2165 for (int i = 0; i < method_args.Length; i++) {
2166 if (method_args [i].IsGenericParameter) {
2174 Type[] infered_types = new Type [method_args.Length];
2176 Type[] param_types = new Type [pd.Count];
2177 Type[] arg_types = new Type [pd.Count];
2179 for (int i = 0; i < arg_count; i++) {
2180 param_types [i] = pd.ParameterType (i);
2182 Argument a = (Argument) arguments [i];
2183 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2186 arg_types [i] = a.Type;
2189 if (!InferTypeArguments (param_types, arg_types, infered_types))
2192 method = method.BindGenericParameters (infered_types);
2196 public static bool InferTypeArguments (EmitContext ec, ParameterData apd,
2197 ref MethodBase method)
2199 if (!TypeManager.IsGenericMethod (method))
2202 ParameterData pd = Invocation.GetParameterData (method);
2203 if (apd.Count != pd.Count)
2206 Type[] method_args = method.GetGenericArguments ();
2207 Type[] infered_types = new Type [method_args.Length];
2209 Type[] param_types = new Type [pd.Count];
2210 Type[] arg_types = new Type [pd.Count];
2212 for (int i = 0; i < apd.Count; i++) {
2213 param_types [i] = pd.ParameterType (i);
2214 arg_types [i] = apd.ParameterType (i);
2217 if (!InferTypeArguments (param_types, arg_types, infered_types))
2220 method = method.BindGenericParameters (infered_types);
2224 public static bool IsNullableType (Type t)
2226 if (!t.IsGenericInstance)
2229 Type gt = t.GetGenericTypeDefinition ();
2230 return gt == generic_nullable_type;
2234 public class NullCoalescingOperator : Expression
2239 public NullCoalescingOperator (Expression left, Expression right, Location loc)
2246 public override Expression DoResolve (EmitContext ec)
2248 Error (-1, "The ?? operator is not yet implemented.");
2252 public override void Emit (EmitContext ec)
2257 public abstract class Nullable
2259 protected sealed class NullableInfo
2261 public readonly Type Type;
2262 public readonly Type UnderlyingType;
2263 public readonly MethodInfo HasValue;
2264 public readonly MethodInfo Value;
2265 public readonly ConstructorInfo Constructor;
2267 public NullableInfo (Type type)
2270 UnderlyingType = TypeManager.GetTypeArguments (type) [0];
2272 PropertyInfo has_value_pi = type.GetProperty ("HasValue");
2273 PropertyInfo value_pi = type.GetProperty ("Value");
2275 HasValue = has_value_pi.GetGetMethod (false);
2276 Value = value_pi.GetGetMethod (false);
2277 Constructor = type.GetConstructor (new Type[] { UnderlyingType });
2281 public class NullLiteral : Expression, IMemoryLocation {
2282 public NullLiteral (Type target_type, Location loc)
2284 this.type = target_type;
2287 eclass = ExprClass.Value;
2290 public override Expression DoResolve (EmitContext ec)
2295 public override void Emit (EmitContext ec)
2297 LocalTemporary value_target = new LocalTemporary (ec, type);
2299 value_target.AddressOf (ec, AddressOp.Store);
2300 ec.ig.Emit (OpCodes.Initobj, type);
2301 value_target.Emit (ec);
2304 public void AddressOf (EmitContext ec, AddressOp Mode)
2306 LocalTemporary value_target = new LocalTemporary (ec, type);
2308 value_target.AddressOf (ec, AddressOp.Store);
2309 ec.ig.Emit (OpCodes.Initobj, type);
2310 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
2314 public class LiftedConversion : Expression
2317 NullableInfo source_info, target_info;
2318 Expression conversion;
2320 protected LiftedConversion (Expression source, Type target_type,
2321 NullableInfo source_info, NullableInfo target_info,
2322 Expression conversion, Location loc)
2324 this.source = source;
2325 this.type = target_type;
2326 this.source_info = source_info;
2327 this.target_info = target_info;
2328 this.conversion = conversion;
2331 eclass = source.eclass;
2334 public static Expression Create (EmitContext ec, Expression source, Type target_type,
2335 bool is_user, bool is_explicit, Location loc)
2337 NullableInfo source_info = new NullableInfo (source.Type);
2338 NullableInfo target_info = new NullableInfo (target_type);
2340 source = source.Resolve (ec);
2344 Expression conversion;
2346 conversion = Convert.UserDefinedConversion (
2347 ec, new EmptyExpression (source_info.UnderlyingType),
2348 target_info.UnderlyingType, loc, is_explicit);
2351 conversion = Convert.ExplicitConversion (
2352 ec, new EmptyExpression (source_info.UnderlyingType),
2353 target_info.UnderlyingType, loc);
2355 conversion = Convert.ImplicitConversion (
2356 ec, new EmptyExpression (source_info.UnderlyingType),
2357 target_info.UnderlyingType, loc);
2360 if (conversion == null)
2363 return new LiftedConversion (
2364 source, target_type, source_info, target_info, conversion, loc);
2367 public override Expression DoResolve (EmitContext ec)
2372 public override void Emit (EmitContext ec)
2374 ILGenerator ig = ec.ig;
2375 Label has_value_label = ig.DefineLabel ();
2376 Label end_label = ig.DefineLabel ();
2378 ((IMemoryLocation) source).AddressOf (ec, AddressOp.LoadStore);
2379 ig.EmitCall (OpCodes.Call, source_info.HasValue, null);
2380 ig.Emit (OpCodes.Brtrue, has_value_label);
2382 LocalTemporary value_target = new LocalTemporary (ec, type);
2383 value_target.AddressOf (ec, AddressOp.Store);
2384 ig.Emit (OpCodes.Initobj, type);
2385 value_target.Emit (ec);
2386 value_target.Release (ec);
2387 ig.Emit (OpCodes.Br, end_label);
2389 ig.MarkLabel (has_value_label);
2391 ((IMemoryLocation) source).AddressOf (ec, AddressOp.LoadStore);
2392 ig.EmitCall (OpCodes.Call, source_info.Value, null);
2393 conversion.Emit (ec);
2394 ig.Emit (OpCodes.Newobj, target_info.Constructor);
2396 ig.MarkLabel (end_label);