2 // generic.cs: Generics support
4 // Authors: Martin Baulig (martin@ximian.com)
5 // Miguel de Icaza (miguel@ximian.com)
7 // Licensed under the terms of the GNU GPL
9 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
10 // (C) 2004 Novell, Inc
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.Globalization;
16 using System.Collections;
18 using System.Text.RegularExpressions;
20 namespace Mono.CSharp {
23 /// Abstract base class for type parameter constraints.
24 /// The type parameter can come from a generic type definition or from reflection.
26 public abstract class GenericConstraints {
27 public abstract string TypeParameter {
31 public abstract GenericParameterAttributes Attributes {
35 public bool HasConstructorConstraint {
36 get { return (Attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0; }
39 public bool HasReferenceTypeConstraint {
40 get { return (Attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0; }
43 public bool HasValueTypeConstraint {
44 get { return (Attributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0; }
47 public virtual bool HasClassConstraint {
48 get { return ClassConstraint != null; }
51 public abstract Type ClassConstraint {
55 public abstract Type[] InterfaceConstraints {
59 public abstract Type EffectiveBaseClass {
64 // Returns whether the type parameter is "known to be a reference type".
66 public virtual bool IsReferenceType {
68 if (HasReferenceTypeConstraint)
70 if (HasValueTypeConstraint)
73 if (ClassConstraint != null) {
74 if (ClassConstraint.IsValueType)
77 if (ClassConstraint != TypeManager.object_type)
81 foreach (Type t in InterfaceConstraints) {
82 if (!t.IsGenericParameter)
85 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
86 if ((gc != null) && gc.IsReferenceType)
95 // Returns whether the type parameter is "known to be a value type".
97 public virtual bool IsValueType {
99 if (HasValueTypeConstraint)
101 if (HasReferenceTypeConstraint)
104 if (ClassConstraint != null) {
105 if (!ClassConstraint.IsValueType)
108 if (ClassConstraint != TypeManager.value_type)
112 foreach (Type t in InterfaceConstraints) {
113 if (!t.IsGenericParameter)
116 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
117 if ((gc != null) && gc.IsValueType)
126 public enum SpecialConstraint
134 /// Tracks the constraints for a type parameter from a generic type definition.
136 public class Constraints : GenericConstraints {
138 ArrayList constraints;
142 // name is the identifier, constraints is an arraylist of
143 // Expressions (with types) or `true' for the constructor constraint.
145 public Constraints (string name, ArrayList constraints,
149 this.constraints = constraints;
153 public override string TypeParameter {
159 GenericParameterAttributes attrs;
160 TypeExpr class_constraint;
161 ArrayList iface_constraints;
162 ArrayList type_param_constraints;
164 Type class_constraint_type;
165 Type[] iface_constraint_types;
166 Type effective_base_type;
171 /// Resolve the constraints - but only resolve things into Expression's, not
172 /// into actual types.
174 public bool Resolve (EmitContext ec)
179 iface_constraints = new ArrayList ();
180 type_param_constraints = new ArrayList ();
182 foreach (object obj in constraints) {
183 if (HasConstructorConstraint) {
184 Report.Error (401, loc,
185 "The new() constraint must be last.");
189 if (obj is SpecialConstraint) {
190 SpecialConstraint sc = (SpecialConstraint) obj;
192 if (sc == SpecialConstraint.Constructor) {
193 if (!HasValueTypeConstraint) {
194 attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
199 451, loc, "The new () constraint " +
200 "cannot be used with the `struct' " +
205 if ((num_constraints > 0) || HasReferenceTypeConstraint || HasValueTypeConstraint) {
206 Report.Error (449, loc,
207 "The `class' or `struct' " +
208 "constraint must be first");
212 if (sc == SpecialConstraint.ReferenceType)
213 attrs |= GenericParameterAttributes.ReferenceTypeConstraint;
215 attrs |= GenericParameterAttributes.NotNullableValueTypeConstraint;
219 int errors = Report.Errors;
220 FullNamedExpression fn = ((Expression) obj).ResolveAsTypeStep (ec);
223 if (errors != Report.Errors)
226 Report.Error (246, loc, "Cannot find type '{0}'", ((Expression) obj).GetSignatureForError ());
231 ConstructedType cexpr = fn as ConstructedType;
233 if (!cexpr.ResolveConstructedType (ec))
238 expr = fn.ResolveAsTypeTerminal (ec);
240 if ((expr == null) || (expr.Type == null))
243 TypeParameterExpr texpr = expr as TypeParameterExpr;
245 type_param_constraints.Add (expr);
246 else if (expr.IsInterface)
247 iface_constraints.Add (expr);
248 else if (class_constraint != null) {
249 Report.Error (406, loc,
250 "`{0}': the class constraint for `{1}' " +
251 "must come before any other constraints.",
254 } else if (HasReferenceTypeConstraint || HasValueTypeConstraint) {
255 Report.Error (450, loc, "`{0}': cannot specify both " +
256 "a constraint class and the `class' " +
257 "or `struct' constraint.", expr.Name);
260 class_constraint = expr;
265 ArrayList list = new ArrayList ();
266 foreach (TypeExpr iface_constraint in iface_constraints) {
267 foreach (Type type in list) {
268 if (!type.Equals (iface_constraint.Type))
271 Report.Error (405, loc,
272 "Duplicate constraint `{0}' for type " +
273 "parameter `{1}'.", iface_constraint.GetSignatureForError (),
278 list.Add (iface_constraint.Type);
281 foreach (TypeParameterExpr expr in type_param_constraints) {
282 foreach (Type type in list) {
283 if (!type.Equals (expr.Type))
286 Report.Error (405, loc,
287 "Duplicate constraint `{0}' for type " +
288 "parameter `{1}'.", expr.GetSignatureForError (), name);
292 list.Add (expr.Type);
295 iface_constraint_types = new Type [list.Count];
296 list.CopyTo (iface_constraint_types, 0);
298 if (class_constraint != null) {
299 class_constraint_type = class_constraint.Type;
300 if (class_constraint_type == null)
303 if (class_constraint_type.IsSealed) {
304 Report.Error (701, loc,
305 "`{0}' is not a valid bound. Bounds " +
306 "must be interfaces or non sealed " +
307 "classes", TypeManager.CSharpName (class_constraint_type));
311 if ((class_constraint_type == TypeManager.array_type) ||
312 (class_constraint_type == TypeManager.delegate_type) ||
313 (class_constraint_type == TypeManager.enum_type) ||
314 (class_constraint_type == TypeManager.value_type) ||
315 (class_constraint_type == TypeManager.object_type)) {
316 Report.Error (702, loc,
317 "Bound cannot be special class `{0}'",
318 TypeManager.CSharpName (class_constraint_type));
323 if (class_constraint_type != null)
324 effective_base_type = class_constraint_type;
325 else if (HasValueTypeConstraint)
326 effective_base_type = TypeManager.value_type;
328 effective_base_type = TypeManager.object_type;
334 bool CheckTypeParameterConstraints (TypeParameter tparam, Hashtable seen)
336 seen.Add (tparam, true);
338 Constraints constraints = tparam.Constraints;
339 if (constraints == null)
342 if (constraints.HasValueTypeConstraint) {
343 Report.Error (456, loc, "Type parameter `{0}' has " +
344 "the `struct' constraint, so it cannot " +
345 "be used as a constraint for `{1}'",
350 if (constraints.type_param_constraints == null)
353 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
354 if (seen.Contains (expr.TypeParameter)) {
355 Report.Error (454, loc, "Circular constraint " +
356 "dependency involving `{0}' and `{1}'",
357 tparam.Name, expr.Name);
361 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
369 /// Resolve the constraints into actual types.
371 public bool ResolveTypes (EmitContext ec)
376 resolved_types = true;
378 foreach (object obj in constraints) {
379 ConstructedType cexpr = obj as ConstructedType;
383 if (!cexpr.CheckConstraints (ec))
387 foreach (TypeParameterExpr expr in type_param_constraints) {
388 Hashtable seen = new Hashtable ();
389 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
393 foreach (TypeExpr iface_constraint in iface_constraints) {
394 if (iface_constraint.ResolveType (ec) == null)
398 if (class_constraint != null) {
399 if (class_constraint.ResolveType (ec) == null)
407 /// Check whether there are no conflicts in our type parameter constraints.
409 /// This is an example:
413 /// where U : T, struct
415 public bool CheckDependencies (EmitContext ec)
417 foreach (TypeParameterExpr expr in type_param_constraints) {
418 if (!CheckDependencies (expr.TypeParameter, ec))
425 bool CheckDependencies (TypeParameter tparam, EmitContext ec)
427 Constraints constraints = tparam.Constraints;
428 if (constraints == null)
431 if (HasValueTypeConstraint && constraints.HasClassConstraint) {
432 Report.Error (455, loc, "Type parameter `{0}' inherits " +
433 "conflicting constraints `{1}' and `{2}'",
434 name, TypeManager.CSharpName (constraints.ClassConstraint),
439 if (HasClassConstraint && constraints.HasClassConstraint) {
440 Type t1 = ClassConstraint;
441 TypeExpr e1 = class_constraint;
442 Type t2 = constraints.ClassConstraint;
443 TypeExpr e2 = constraints.class_constraint;
445 if (!Convert.ImplicitReferenceConversionExists (ec, e1, t2) &&
446 !Convert.ImplicitReferenceConversionExists (ec, e2, t1)) {
447 Report.Error (455, loc,
448 "Type parameter `{0}' inherits " +
449 "conflicting constraints `{1}' and `{2}'",
450 name, TypeManager.CSharpName (t1), TypeManager.CSharpName (t2));
455 if (constraints.type_param_constraints == null)
458 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
459 if (!CheckDependencies (expr.TypeParameter, ec))
467 /// Set the attributes on the GenericTypeParameterBuilder.
470 /// This is not done in Resolve() since Resolve() may be called before
471 /// the GenericTypeParameterBuilder is created (partial generic classes).
473 public void Define (GenericTypeParameterBuilder type)
475 type.SetGenericParameterAttributes (attrs);
478 public override GenericParameterAttributes Attributes {
479 get { return attrs; }
482 public override bool HasClassConstraint {
483 get { return class_constraint != null; }
486 public override Type ClassConstraint {
487 get { return class_constraint_type; }
490 public override Type[] InterfaceConstraints {
491 get { return iface_constraint_types; }
494 public override Type EffectiveBaseClass {
495 get { return effective_base_type; }
498 public bool IsSubclassOf (Type t)
500 if ((class_constraint_type != null) &&
501 class_constraint_type.IsSubclassOf (t))
504 if (iface_constraint_types == null)
507 foreach (Type iface in iface_constraint_types) {
508 if (TypeManager.IsSubclassOf (iface, t))
516 /// This is used when we're implementing a generic interface method.
517 /// Each method type parameter in implementing method must have the same
518 /// constraints than the corresponding type parameter in the interface
519 /// method. To do that, we're called on each of the implementing method's
522 public bool CheckInterfaceMethod (EmitContext ec, GenericConstraints gc)
524 if (gc.Attributes != attrs)
527 if (HasClassConstraint != gc.HasClassConstraint)
529 if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
532 int gc_icount = gc.InterfaceConstraints != null ?
533 gc.InterfaceConstraints.Length : 0;
534 int icount = InterfaceConstraints != null ?
535 InterfaceConstraints.Length : 0;
537 if (gc_icount != icount)
540 foreach (Type iface in gc.InterfaceConstraints) {
542 foreach (Type check in InterfaceConstraints) {
543 if (TypeManager.IsEqual (iface, check)) {
558 /// A type parameter from a generic type definition.
560 public class TypeParameter : MemberCore, IMemberContainer {
563 GenericConstraints gc;
564 Constraints constraints;
566 GenericTypeParameterBuilder type;
568 public TypeParameter (TypeContainer parent, DeclSpace decl, string name,
569 Constraints constraints, Location loc)
570 : base (parent, new MemberName (name, loc), null)
574 this.constraints = constraints;
578 public GenericConstraints GenericConstraints {
580 return gc != null ? gc : constraints;
584 public Constraints Constraints {
590 public bool HasConstructorConstraint {
592 if (constraints != null)
593 return constraints.HasConstructorConstraint;
599 public DeclSpace DeclSpace {
612 /// This is the first method which is called during the resolving
613 /// process; we're called immediately after creating the type parameters
614 /// with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
617 /// We're either called from TypeContainer.DefineType() or from
618 /// GenericMethod.Define() (called from Method.Define()).
620 public void Define (GenericTypeParameterBuilder type)
622 if (this.type != null)
623 throw new InvalidOperationException ();
626 TypeManager.AddTypeParameter (type, this);
630 /// This is the second method which is called during the resolving
631 /// process - in case of class type parameters, we're called from
632 /// TypeContainer.ResolveType() - after it resolved the class'es
633 /// base class and interfaces. For method type parameters, we're
634 /// called immediately after Define().
636 /// We're just resolving the constraints into expressions here, we
637 /// don't resolve them into actual types.
639 /// Note that in the special case of partial generic classes, we may be
640 /// called _before_ Define() and we may also be called multiple types.
642 public bool Resolve (DeclSpace ds)
644 if (constraints != null) {
645 if (!constraints.Resolve (ds.EmitContext)) {
655 /// This is the third method which is called during the resolving
656 /// process. We're called immediately after calling Resolve() on
657 /// all of the current class'es type parameters.
659 /// All we do is setting the attributes on the GenericTypeParameterBuilder.
662 /// This is not done in Resolve() since Resolve() may be called before
663 /// Define() for partial generic classes.
665 public void DefineConstraints ()
667 if (constraints != null)
668 constraints.Define (type);
672 /// This is the forth method which is called during the resolving
673 /// process. We're called immediately after calling DefineConstraints()
674 /// on all of the current class'es type parameters.
676 /// Our job is to resolve the constraints to actual types.
678 /// Note that we may have circular dependencies on type parameters - this
679 /// is why Resolve() and ResolveType() are separate.
681 public bool ResolveType (EmitContext ec)
683 if (constraints != null) {
684 if (!constraints.ResolveTypes (ec)) {
694 /// This is the fith and last method which is called during the resolving
695 /// process. We're called after everything is fully resolved and actually
696 /// register the constraints with SRE and the TypeManager.
698 public bool DefineType (EmitContext ec)
700 return DefineType (ec, null, null, false);
704 /// This is the fith and last method which is called during the resolving
705 /// process. We're called after everything is fully resolved and actually
706 /// register the constraints with SRE and the TypeManager.
708 /// The `builder', `implementing' and `is_override' arguments are only
709 /// applicable to method type parameters.
711 public bool DefineType (EmitContext ec, MethodBuilder builder,
712 MethodInfo implementing, bool is_override)
714 if (!ResolveType (ec))
717 if (implementing != null) {
718 if (is_override && (constraints != null)) {
720 460, loc, "Constraints for override and " +
721 "explicit interface implementation methods " +
722 "are inherited from the base method so they " +
723 "cannot be specified directly");
727 MethodBase mb = implementing;
728 if (mb.Mono_IsInflatedMethod)
729 mb = mb.GetGenericMethodDefinition ();
731 int pos = type.GenericParameterPosition;
732 ParameterData pd = TypeManager.GetParameterData (mb);
733 GenericConstraints temp_gc = pd.GenericConstraints (pos);
734 Type mparam = mb.GetGenericArguments () [pos];
737 gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
738 else if (constraints != null)
739 gc = new InflatedConstraints (constraints, implementing.DeclaringType);
742 if (constraints != null) {
745 else if (!constraints.CheckInterfaceMethod (ec, gc))
748 if (!is_override && (temp_gc != null))
753 Report.SymbolRelatedToPreviousError (implementing);
756 425, loc, "The constraints for type " +
757 "parameter `{0}' of method `{1}' must match " +
758 "the constraints for type parameter `{2}' " +
759 "of interface method `{3}'. Consider using " +
760 "an explicit interface implementation instead",
761 Name, TypeManager.CSharpSignature (builder),
762 TypeManager.CSharpName (mparam), TypeManager.CSharpSignature (mb));
765 } else if (DeclSpace is Iterator) {
766 TypeParameter[] tparams = DeclSpace.TypeParameters;
767 Type[] types = new Type [tparams.Length];
768 for (int i = 0; i < tparams.Length; i++)
769 types [i] = tparams [i].Type;
771 if (constraints != null)
772 gc = new InflatedConstraints (constraints, types);
774 gc = (GenericConstraints) constraints;
780 if (gc.HasClassConstraint)
781 type.SetBaseTypeConstraint (gc.ClassConstraint);
783 type.SetInterfaceConstraints (gc.InterfaceConstraints);
784 TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
790 /// Check whether there are no conflicts in our type parameter constraints.
792 /// This is an example:
796 /// where U : T, struct
798 public bool CheckDependencies (EmitContext ec)
800 if (constraints != null)
801 return constraints.CheckDependencies (ec);
807 /// This is called for each part of a partial generic type definition.
809 /// If `new_constraints' is not null and we don't already have constraints,
810 /// they become our constraints. If we already have constraints, we must
811 /// check that they're the same.
814 public bool UpdateConstraints (EmitContext ec, Constraints new_constraints)
817 throw new InvalidOperationException ();
819 if (constraints == null) {
820 new_constraints = constraints;
822 } else if (new_constraints == null)
825 if (!new_constraints.Resolve (ec))
827 if (!new_constraints.ResolveTypes (ec))
830 return constraints.CheckInterfaceMethod (ec, new_constraints);
833 public override string DocCommentHeader {
835 throw new InvalidOperationException (
836 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
844 public override bool Define ()
849 public override void ApplyAttributeBuilder (Attribute a,
850 CustomAttributeBuilder cb)
853 public override AttributeTargets AttributeTargets {
855 return (AttributeTargets) 0;
859 public override string[] ValidAttributeTargets {
861 return new string [0];
869 string IMemberContainer.Name {
873 MemberCache IMemberContainer.BaseCache {
877 bool IMemberContainer.IsInterface {
881 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
883 return FindMembers (mt, bf, null, null);
886 MemberCache IMemberContainer.MemberCache {
890 public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
891 MemberFilter filter, object criteria)
893 if (constraints == null)
894 return MemberList.Empty;
896 ArrayList members = new ArrayList ();
898 GenericConstraints gc = (GenericConstraints) constraints;
900 if (gc.HasClassConstraint) {
901 MemberList list = TypeManager.FindMembers (
902 gc.ClassConstraint, mt, bf, filter, criteria);
904 members.AddRange (list);
907 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
908 foreach (Type t in ifaces) {
909 MemberList list = TypeManager.FindMembers (
910 t, mt, bf, filter, criteria);
912 members.AddRange (list);
915 return new MemberList (members);
918 public bool IsSubclassOf (Type t)
923 if (constraints != null)
924 return constraints.IsSubclassOf (t);
929 public override string ToString ()
931 return "TypeParameter[" + name + "]";
934 public static string GetSignatureForError (TypeParameter[] tp)
936 if (tp == null || tp.Length == 0)
939 StringBuilder sb = new StringBuilder ("<");
940 for (int i = 0; i < tp.Length; ++i) {
943 sb.Append (tp[i].GetSignatureForError ());
946 return sb.ToString ();
949 protected class InflatedConstraints : GenericConstraints
951 GenericConstraints gc;
953 Type class_constraint;
954 Type[] iface_constraints;
957 public InflatedConstraints (GenericConstraints gc, Type declaring)
958 : this (gc, TypeManager.GetTypeArguments (declaring))
961 public InflatedConstraints (GenericConstraints gc, Type[] dargs)
966 ArrayList list = new ArrayList ();
967 if (gc.HasClassConstraint)
968 list.Add (inflate (gc.ClassConstraint));
969 foreach (Type iface in gc.InterfaceConstraints)
970 list.Add (inflate (iface));
972 bool has_class_constr = false;
973 if (list.Count > 0) {
974 Type first = (Type) list [0];
975 has_class_constr = !first.IsInterface && !first.IsGenericParameter;
978 if ((list.Count > 0) && has_class_constr) {
979 class_constraint = (Type) list [0];
980 iface_constraints = new Type [list.Count - 1];
981 list.CopyTo (1, iface_constraints, 0, list.Count - 1);
983 iface_constraints = new Type [list.Count];
984 list.CopyTo (iface_constraints, 0);
987 if (HasValueTypeConstraint)
988 base_type = TypeManager.value_type;
989 else if (class_constraint != null)
990 base_type = class_constraint;
992 base_type = TypeManager.object_type;
995 Type inflate (Type t)
999 if (t.IsGenericParameter)
1000 return dargs [t.GenericParameterPosition];
1001 if (t.IsGenericInstance) {
1002 t = t.GetGenericTypeDefinition ();
1003 t = t.MakeGenericType (dargs);
1009 public override string TypeParameter {
1010 get { return gc.TypeParameter; }
1013 public override GenericParameterAttributes Attributes {
1014 get { return gc.Attributes; }
1017 public override Type ClassConstraint {
1018 get { return class_constraint; }
1021 public override Type EffectiveBaseClass {
1022 get { return base_type; }
1025 public override Type[] InterfaceConstraints {
1026 get { return iface_constraints; }
1032 /// A TypeExpr which already resolved to a type parameter.
1034 public class TypeParameterExpr : TypeExpr {
1035 TypeParameter type_parameter;
1037 public override string Name {
1039 return type_parameter.Name;
1043 public override string FullName {
1045 return type_parameter.Name;
1049 public TypeParameter TypeParameter {
1051 return type_parameter;
1055 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1057 this.type_parameter = type_parameter;
1061 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
1063 type = type_parameter.Type;
1068 public override bool IsInterface {
1069 get { return false; }
1072 public override bool CheckAccessLevel (DeclSpace ds)
1077 public void Error_CannotUseAsUnmanagedType (Location loc)
1079 Report.Error (-203, loc, "Can not use type parameter as unamanged type");
1084 /// Tracks the type arguments when instantiating a generic type. We're used in
1085 /// ConstructedType.
1087 public class TypeArguments {
1088 public readonly Location Location;
1095 public TypeArguments (Location loc)
1097 args = new ArrayList ();
1098 this.Location = loc;
1101 public TypeArguments (int dimension, Location loc)
1103 this.dimension = dimension;
1104 this.Location = loc;
1107 public void Add (Expression type)
1110 throw new InvalidOperationException ();
1115 public void Add (TypeArguments new_args)
1118 throw new InvalidOperationException ();
1120 args.AddRange (new_args.args);
1124 /// We're used during the parsing process: the parser can't distinguish
1125 /// between type parameters and type arguments. Because of that, the
1126 /// parser creates a `MemberName' with `TypeArguments' for both cases and
1127 /// in case of a generic type definition, we call GetDeclarations().
1129 public string[] GetDeclarations ()
1131 string[] ret = new string [args.Count];
1132 for (int i = 0; i < args.Count; i++) {
1133 SimpleName sn = args [i] as SimpleName;
1139 Report.Error (81, Location, "Type parameter declaration " +
1140 "must be an identifier not a type");
1147 /// We may only be used after Resolve() is called and return the fully
1150 public Type[] Arguments {
1156 public bool HasTypeArguments {
1158 return has_type_args;
1171 public bool IsUnbound {
1173 return dimension > 0;
1177 public override string ToString ()
1179 StringBuilder s = new StringBuilder ();
1182 for (int i = 0; i < count; i++){
1184 // FIXME: Use TypeManager.CSharpname once we have the type
1187 s.Append (args [i].ToString ());
1191 return s.ToString ();
1195 /// Resolve the type arguments.
1197 public bool Resolve (EmitContext ec)
1199 int count = args.Count;
1202 atypes = new Type [count];
1204 for (int i = 0; i < count; i++){
1205 TypeExpr te = ((Expression) args [i]).ResolveAsTypeTerminal (ec);
1210 if (te is TypeParameterExpr)
1211 has_type_args = true;
1213 if (te.Type.IsPointer) {
1214 Report.Error (306, Location, "The type `{0}' may not be used " +
1215 "as a type argument.", TypeManager.CSharpName (te.Type));
1219 atypes [i] = te.Type;
1226 /// An instantiation of a generic type.
1228 public class ConstructedType : TypeExpr {
1230 FullNamedExpression name;
1232 Type[] gen_params, atypes;
1236 /// Instantiate the generic type `fname' with the type arguments `args'.
1238 public ConstructedType (FullNamedExpression fname, TypeArguments args, Location l)
1244 eclass = ExprClass.Type;
1245 full_name = name + "<" + args.ToString () + ">";
1248 protected ConstructedType (TypeArguments args, Location l)
1253 eclass = ExprClass.Type;
1256 protected ConstructedType (TypeParameter[] type_params, Location l)
1260 args = new TypeArguments (l);
1261 foreach (TypeParameter type_param in type_params)
1262 args.Add (new TypeParameterExpr (type_param, l));
1264 eclass = ExprClass.Type;
1268 /// This is used to construct the `this' type inside a generic type definition.
1270 public ConstructedType (Type t, TypeParameter[] type_params, Location l)
1271 : this (type_params, l)
1273 gt = t.GetGenericTypeDefinition ();
1275 this.name = new TypeExpression (gt, l);
1276 full_name = gt.FullName + "<" + args.ToString () + ">";
1280 /// Instantiate the generic type `t' with the type arguments `args'.
1281 /// Use this constructor if you already know the fully resolved
1284 public ConstructedType (Type t, TypeArguments args, Location l)
1287 gt = t.GetGenericTypeDefinition ();
1289 this.name = new TypeExpression (gt, l);
1290 full_name = gt.FullName + "<" + args.ToString () + ">";
1293 public TypeArguments TypeArguments {
1294 get { return args; }
1297 public override string GetSignatureForError ()
1299 return TypeManager.CSharpName (gt);
1302 protected bool CheckConstraint (EmitContext ec, Type ptype, Expression expr,
1305 if (TypeManager.HasGenericArguments (ctype)) {
1306 Type[] types = TypeManager.GetTypeArguments (ctype);
1308 TypeArguments new_args = new TypeArguments (loc);
1310 for (int i = 0; i < types.Length; i++) {
1313 if (t.IsGenericParameter) {
1314 int pos = t.GenericParameterPosition;
1315 t = args.Arguments [pos];
1317 new_args.Add (new TypeExpression (t, loc));
1320 TypeExpr ct = new ConstructedType (ctype, new_args, loc);
1321 if (ct.ResolveAsTypeStep (ec) == null)
1326 return Convert.ImplicitStandardConversionExists (ec, expr, ctype);
1329 protected bool CheckConstraints (EmitContext ec, int index)
1331 Type atype = atypes [index];
1332 Type ptype = gen_params [index];
1337 Expression aexpr = new EmptyExpression (atype);
1339 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1343 bool is_class, is_struct;
1344 if (atype.IsGenericParameter) {
1345 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1347 is_class = agc.HasReferenceTypeConstraint;
1348 is_struct = agc.HasValueTypeConstraint;
1350 is_class = is_struct = false;
1353 is_class = atype.IsClass;
1354 is_struct = atype.IsValueType;
1358 // First, check the `class' and `struct' constraints.
1360 if (gc.HasReferenceTypeConstraint && !is_class) {
1361 Report.Error (452, loc, "The type `{0}' must be " +
1362 "a reference type in order to use it " +
1363 "as type parameter `{1}' in the " +
1364 "generic type or method `{2}'.",
1365 TypeManager.CSharpName (atype),
1366 TypeManager.CSharpName (ptype),
1367 GetSignatureForError ());
1369 } else if (gc.HasValueTypeConstraint && !is_struct) {
1370 Report.Error (453, loc, "The type `{0}' must be " +
1371 "a value type in order to use it " +
1372 "as type parameter `{1}' in the " +
1373 "generic type or method `{2}'.",
1374 TypeManager.CSharpName (atype),
1375 TypeManager.CSharpName (ptype),
1376 GetSignatureForError ());
1381 // The class constraint comes next.
1383 if (gc.HasClassConstraint) {
1384 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint)) {
1385 Error_TypeMustBeConvertible (atype, gc.ClassConstraint, ptype);
1391 // Now, check the interface constraints.
1393 foreach (Type it in gc.InterfaceConstraints) {
1395 if (it.IsGenericParameter)
1396 itype = atypes [it.GenericParameterPosition];
1400 if (!CheckConstraint (ec, ptype, aexpr, itype)) {
1401 Error_TypeMustBeConvertible (atype, itype, ptype);
1407 // Finally, check the constructor constraint.
1410 if (!gc.HasConstructorConstraint)
1413 if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
1416 if (HasDefaultConstructor (ec, atype))
1419 Report.SymbolRelatedToPreviousError (gt);
1420 Report.SymbolRelatedToPreviousError (atype);
1421 Report.Error (310, loc, "The type `{0}' must have a public " +
1422 "parameterless constructor in order to use it " +
1423 "as parameter `{1}' in the generic type or " +
1425 TypeManager.CSharpName (atype),
1426 TypeManager.CSharpName (ptype),
1427 GetSignatureForError ());
1431 void Error_TypeMustBeConvertible (Type atype, Type gc, Type ptype)
1433 Report.SymbolRelatedToPreviousError (gt);
1434 Report.SymbolRelatedToPreviousError (atype);
1435 Report.Error (309, loc, "The type `{0}' must be convertible to `{1}' in order to " +
1436 "use it as parameter `{2}' in the generic type or method `{3}'",
1437 TypeManager.CSharpName (atype), TypeManager.CSharpName (gc),
1438 TypeManager.CSharpName (ptype), GetSignatureForError ());
1441 bool HasDefaultConstructor (EmitContext ec, Type atype)
1443 if (atype is TypeBuilder) {
1444 if (atype.IsAbstract)
1447 TypeContainer tc = TypeManager.LookupTypeContainer (atype);
1448 foreach (Constructor c in tc.InstanceConstructors) {
1449 if ((c.ModFlags & Modifiers.PUBLIC) == 0)
1451 if ((c.Parameters.FixedParameters != null) &&
1452 (c.Parameters.FixedParameters.Length != 0))
1454 if (c.Parameters.HasArglist ||
1455 (c.Parameters.ArrayParameter != null))
1462 MethodGroupExpr mg = Expression.MemberLookup (
1463 ec, atype, ".ctor", MemberTypes.Constructor,
1464 BindingFlags.Public | BindingFlags.Instance |
1465 BindingFlags.DeclaredOnly, loc)
1468 if (!atype.IsAbstract && (mg != null) && mg.IsInstance) {
1469 foreach (MethodBase mb in mg.Methods) {
1470 ParameterData pd = TypeManager.GetParameterData (mb);
1479 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
1481 if (!ResolveConstructedType (ec))
1488 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1489 /// after fully resolving the constructed type.
1491 public bool CheckConstraints (EmitContext ec)
1493 for (int i = 0; i < gen_params.Length; i++) {
1494 if (!CheckConstraints (ec, i))
1502 /// Resolve the constructed type, but don't check the constraints.
1504 public bool ResolveConstructedType (EmitContext ec)
1508 // If we already know the fully resolved generic type.
1510 return DoResolveType (ec);
1516 Report.Error (246, loc, "Cannot find type `{0}'<...>", Name);
1520 num_args = TypeManager.GetNumberOfTypeArguments (t);
1521 if (num_args == 0) {
1522 Report.Error (308, loc,
1523 "The non-generic type `{0}' cannot " +
1524 "be used with type arguments.",
1525 TypeManager.CSharpName (t));
1529 gt = t.GetGenericTypeDefinition ();
1530 return DoResolveType (ec);
1533 bool DoResolveType (EmitContext ec)
1536 // Resolve the arguments.
1538 if (args.Resolve (ec) == false)
1541 gen_params = gt.GetGenericArguments ();
1542 atypes = args.Arguments;
1544 if (atypes.Length != gen_params.Length) {
1545 Report.Error (305, loc,
1546 "Using the generic type `{0}' " +
1547 "requires {1} type arguments",
1548 TypeManager.CSharpName (gt),
1549 gen_params.Length.ToString ());
1554 // Now bind the parameters.
1556 type = gt.MakeGenericType (atypes);
1560 public Expression GetSimpleName (EmitContext ec)
1565 public override bool CheckAccessLevel (DeclSpace ds)
1567 return ds.CheckAccessLevel (gt);
1570 public override bool AsAccessible (DeclSpace ds, int flags)
1572 return ds.AsAccessible (gt, flags);
1575 public override bool IsClass {
1576 get { return gt.IsClass; }
1579 public override bool IsValueType {
1580 get { return gt.IsValueType; }
1583 public override bool IsInterface {
1584 get { return gt.IsInterface; }
1587 public override bool IsSealed {
1588 get { return gt.IsSealed; }
1591 public override bool Equals (object obj)
1593 ConstructedType cobj = obj as ConstructedType;
1597 if ((type == null) || (cobj.type == null))
1600 return type == cobj.type;
1603 public override int GetHashCode ()
1605 return base.GetHashCode ();
1608 public override string Name {
1615 public override string FullName {
1623 /// A generic method definition.
1625 public class GenericMethod : DeclSpace
1627 Expression return_type;
1628 Parameters parameters;
1630 public GenericMethod (NamespaceEntry ns, TypeContainer parent, MemberName name,
1631 Expression return_type, Parameters parameters)
1632 : base (ns, parent, name, null)
1634 this.return_type = return_type;
1635 this.parameters = parameters;
1638 public override TypeBuilder DefineType ()
1640 throw new Exception ();
1643 public override bool Define ()
1645 ec = new EmitContext (this, this, Location, null, null, ModFlags, false);
1647 for (int i = 0; i < TypeParameters.Length; i++)
1648 if (!TypeParameters [i].Resolve (this))
1655 /// Define and resolve the type parameters.
1656 /// We're called from Method.Define().
1658 public bool Define (MethodBuilder mb)
1660 GenericTypeParameterBuilder[] gen_params;
1661 string[] names = MemberName.TypeArguments.GetDeclarations ();
1662 gen_params = mb.DefineGenericParameters (names);
1663 for (int i = 0; i < TypeParameters.Length; i++)
1664 TypeParameters [i].Define (gen_params [i]);
1669 for (int i = 0; i < TypeParameters.Length; i++) {
1670 if (!TypeParameters [i].ResolveType (ec))
1674 for (int i = 0; i < TypeParameters.Length; i++)
1675 TypeParameters [i].DefineConstraints ();
1681 /// We're called from MethodData.Define() after creating the MethodBuilder.
1683 public bool DefineType (EmitContext ec, MethodBuilder mb,
1684 MethodInfo implementing, bool is_override)
1686 for (int i = 0; i < TypeParameters.Length; i++)
1687 if (!TypeParameters [i].DefineType (
1688 ec, mb, implementing, is_override))
1692 if (parameters.FixedParameters != null) {
1693 foreach (Parameter p in parameters.FixedParameters){
1694 if (!p.Resolve (ec))
1698 if (parameters.ArrayParameter != null) {
1699 if (!parameters.ArrayParameter.Resolve (ec))
1702 if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec) == null))
1708 public override bool DefineMembers (TypeContainer parent)
1713 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1714 MemberFilter filter, object criteria)
1716 throw new Exception ();
1719 public override MemberCache MemberCache {
1725 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1730 public override AttributeTargets AttributeTargets {
1732 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1736 public override string DocCommentHeader {
1737 get { return "M:"; }
1741 public class DefaultValueExpression : Expression
1745 public DefaultValueExpression (Expression expr, Location loc)
1751 public override Expression DoResolve (EmitContext ec)
1753 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
1759 eclass = ExprClass.Variable;
1763 public override void Emit (EmitContext ec)
1765 if (type.IsGenericParameter || TypeManager.IsValueType (type)) {
1766 LocalTemporary temp_storage = new LocalTemporary (ec, type);
1768 temp_storage.AddressOf (ec, AddressOp.LoadStore);
1769 ec.ig.Emit (OpCodes.Initobj, type);
1770 temp_storage.Emit (ec);
1772 ec.ig.Emit (OpCodes.Ldnull);
1776 public class NullableType : TypeExpr
1778 Expression underlying;
1780 public NullableType (Expression underlying, Location l)
1782 this.underlying = underlying;
1785 eclass = ExprClass.Type;
1788 public NullableType (Type type, Location loc)
1789 : this (new TypeExpression (type, loc), loc)
1792 public override string Name {
1793 get { return underlying.ToString () + "?"; }
1796 public override string FullName {
1797 get { return underlying.ToString () + "?"; }
1800 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
1802 TypeArguments args = new TypeArguments (loc);
1803 args.Add (underlying);
1805 ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
1806 return ctype.ResolveAsTypeTerminal (ec);
1810 public partial class TypeManager
1813 // A list of core types that the compiler requires or uses
1815 static public Type activator_type;
1816 static public Type generic_ienumerator_type;
1817 static public Type generic_ienumerable_type;
1818 static public Type generic_nullable_type;
1821 // Tracks the generic parameters.
1823 static PtrHashtable builder_to_type_param;
1826 // These methods are called by code generated by the compiler
1828 static public MethodInfo activator_create_instance;
1830 static void InitGenerics ()
1832 builder_to_type_param = new PtrHashtable ();
1835 static void CleanUpGenerics ()
1837 builder_to_type_param = null;
1840 static void InitGenericCoreTypes ()
1842 activator_type = CoreLookupType ("System", "Activator");
1844 generic_ienumerator_type = CoreLookupType (
1845 "System.Collections.Generic", "IEnumerator", 1);
1846 generic_ienumerable_type = CoreLookupType (
1847 "System.Collections.Generic", "IEnumerable", 1);
1848 generic_nullable_type = CoreLookupType (
1849 "System", "Nullable", 1);
1852 static void InitGenericCodeHelpers ()
1855 Type [] type_arg = { type_type };
1856 activator_create_instance = GetMethod (
1857 activator_type, "CreateInstance", type_arg);
1860 static Type CoreLookupType (string ns, string name, int arity)
1862 return CoreLookupType (ns, MemberName.MakeName (name, arity));
1865 public static void AddTypeParameter (Type t, TypeParameter tparam)
1867 if (!builder_to_type_param.Contains (t))
1868 builder_to_type_param.Add (t, tparam);
1871 public static TypeContainer LookupGenericTypeContainer (Type t)
1873 while (t.IsGenericInstance)
1874 t = t.GetGenericTypeDefinition ();
1876 return LookupTypeContainer (t);
1879 public static TypeParameter LookupTypeParameter (Type t)
1881 return (TypeParameter) builder_to_type_param [t];
1884 public static GenericConstraints GetTypeParameterConstraints (Type t)
1886 if (!t.IsGenericParameter)
1887 throw new InvalidOperationException ();
1889 TypeParameter tparam = LookupTypeParameter (t);
1891 return tparam.GenericConstraints;
1893 return new ReflectionConstraints (t);
1896 public static bool IsGeneric (Type t)
1898 DeclSpace ds = (DeclSpace) builder_to_declspace [t];
1900 return ds.IsGeneric;
1903 public static bool HasGenericArguments (Type t)
1905 return GetNumberOfTypeArguments (t) > 0;
1908 public static int GetNumberOfTypeArguments (Type t)
1910 if (t.IsGenericParameter)
1912 DeclSpace tc = LookupDeclSpace (t);
1914 return tc.IsGeneric ? tc.CountTypeParameters : 0;
1916 return t.IsGenericType ? t.GetGenericArguments ().Length : 0;
1919 public static Type[] GetTypeArguments (Type t)
1921 DeclSpace tc = LookupDeclSpace (t);
1924 return Type.EmptyTypes;
1926 TypeParameter[] tparam = tc.TypeParameters;
1927 Type[] ret = new Type [tparam.Length];
1928 for (int i = 0; i < tparam.Length; i++) {
1929 ret [i] = tparam [i].Type;
1930 if (ret [i] == null)
1931 throw new InternalErrorException ();
1936 return t.GetGenericArguments ();
1940 // Whether `array' is an array of T and `enumerator' is `IEnumerable<T>'.
1941 // For instance "string[]" -> "IEnumerable<string>".
1943 public static bool IsIEnumerable (Type array, Type enumerator)
1945 if (!array.IsArray || !enumerator.IsGenericInstance)
1948 if (enumerator.GetGenericTypeDefinition () != generic_ienumerable_type)
1951 Type[] args = GetTypeArguments (enumerator);
1952 return args [0] == GetElementType (array);
1955 public static bool IsEqual (Type a, Type b)
1960 if ((a is TypeBuilder) && a.IsGenericTypeDefinition && b.IsGenericInstance) {
1962 // `a' is a generic type definition's TypeBuilder and `b' is a
1963 // generic instance of the same type.
1969 // void Test (Stack<T> stack) { }
1972 // The first argument of `Test' will be the generic instance
1973 // "Stack<!0>" - which is the same type than the "Stack" TypeBuilder.
1976 // We hit this via Closure.Filter() for gen-82.cs.
1978 if (a != b.GetGenericTypeDefinition ())
1981 Type[] aparams = a.GetGenericArguments ();
1982 Type[] bparams = b.GetGenericArguments ();
1984 if (aparams.Length != bparams.Length)
1987 for (int i = 0; i < aparams.Length; i++)
1988 if (!IsEqual (aparams [i], bparams [i]))
1994 if ((b is TypeBuilder) && b.IsGenericTypeDefinition && a.IsGenericInstance)
1995 return IsEqual (b, a);
1997 if (a.IsGenericParameter && b.IsGenericParameter) {
1998 if (a.DeclaringMethod != b.DeclaringMethod &&
1999 (a.DeclaringMethod == null || b.DeclaringMethod == null))
2001 return a.GenericParameterPosition == b.GenericParameterPosition;
2004 if (a.IsArray && b.IsArray) {
2005 if (a.GetArrayRank () != b.GetArrayRank ())
2007 return IsEqual (a.GetElementType (), b.GetElementType ());
2010 if (a.IsGenericInstance && b.IsGenericInstance) {
2011 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2014 Type[] aargs = a.GetGenericArguments ();
2015 Type[] bargs = b.GetGenericArguments ();
2017 if (aargs.Length != bargs.Length)
2020 for (int i = 0; i < aargs.Length; i++) {
2021 if (!IsEqual (aargs [i], bargs [i]))
2032 /// Check whether `a' and `b' may become equal generic types.
2033 /// The algorithm to do that is a little bit complicated.
2035 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_infered,
2036 Type[] method_infered)
2038 if (a.IsGenericParameter) {
2040 // If a is an array of a's type, they may never
2044 b = b.GetElementType ();
2050 // If b is a generic parameter or an actual type,
2051 // they may become equal:
2053 // class X<T,U> : I<T>, I<U>
2054 // class X<T> : I<T>, I<float>
2056 if (b.IsGenericParameter || !b.IsGenericInstance) {
2057 int pos = a.GenericParameterPosition;
2058 Type[] args = a.DeclaringMethod != null ? method_infered : class_infered;
2059 if (args [pos] == null) {
2064 return args [pos] == a;
2068 // We're now comparing a type parameter with a
2069 // generic instance. They may become equal unless
2070 // the type parameter appears anywhere in the
2071 // generic instance:
2073 // class X<T,U> : I<T>, I<X<U>>
2074 // -> error because you could instanciate it as
2077 // class X<T> : I<T>, I<X<T>> -> ok
2080 Type[] bargs = GetTypeArguments (b);
2081 for (int i = 0; i < bargs.Length; i++) {
2082 if (a.Equals (bargs [i]))
2089 if (b.IsGenericParameter)
2090 return MayBecomeEqualGenericTypes (b, a, class_infered, method_infered);
2093 // At this point, neither a nor b are a type parameter.
2095 // If one of them is a generic instance, let
2096 // MayBecomeEqualGenericInstances() compare them (if the
2097 // other one is not a generic instance, they can never
2101 if (a.IsGenericInstance || b.IsGenericInstance)
2102 return MayBecomeEqualGenericInstances (a, b, class_infered, method_infered);
2105 // If both of them are arrays.
2108 if (a.IsArray && b.IsArray) {
2109 if (a.GetArrayRank () != b.GetArrayRank ())
2112 a = a.GetElementType ();
2113 b = b.GetElementType ();
2115 return MayBecomeEqualGenericTypes (a, b, class_infered, method_infered);
2119 // Ok, two ordinary types.
2122 return a.Equals (b);
2126 // Checks whether two generic instances may become equal for some
2127 // particular instantiation (26.3.1).
2129 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
2130 Type[] class_infered,
2131 Type[] method_infered)
2133 if (!a.IsGenericInstance || !b.IsGenericInstance)
2135 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2138 return MayBecomeEqualGenericInstances (
2139 GetTypeArguments (a), GetTypeArguments (b), class_infered, method_infered);
2142 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
2143 Type[] class_infered,
2144 Type[] method_infered)
2146 if (aargs.Length != bargs.Length)
2149 for (int i = 0; i < aargs.Length; i++) {
2150 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_infered, method_infered))
2158 /// Check whether `type' and `parent' are both instantiations of the same
2159 /// generic type. Note that we do not check the type parameters here.
2161 public static bool IsInstantiationOfSameGenericType (Type type, Type parent)
2163 int tcount = GetNumberOfTypeArguments (type);
2164 int pcount = GetNumberOfTypeArguments (parent);
2166 if (type.IsGenericInstance)
2167 type = type.GetGenericTypeDefinition ();
2168 if (parent.IsGenericInstance)
2169 parent = parent.GetGenericTypeDefinition ();
2171 if (tcount != pcount)
2174 return type.Equals (parent);
2178 /// Whether `mb' is a generic method definition.
2180 public static bool IsGenericMethod (MethodBase mb)
2182 if (mb.DeclaringType is TypeBuilder) {
2183 IMethodData method = (IMethodData) builder_to_method [mb];
2187 return method.GenericMethod != null;
2190 return mb.IsGenericMethodDefinition;
2197 static bool InferType (Type pt, Type at, Type[] infered)
2199 if (pt.IsGenericParameter && (pt.DeclaringMethod != null)) {
2200 int pos = pt.GenericParameterPosition;
2202 if (infered [pos] == null) {
2204 while (check.IsArray)
2205 check = check.GetElementType ();
2214 if (infered [pos] != at)
2220 if (!pt.ContainsGenericParameters) {
2221 if (at.ContainsGenericParameters)
2222 return InferType (at, pt, infered);
2229 (at.GetArrayRank () != pt.GetArrayRank ()))
2232 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2237 (pt.GetArrayRank () != at.GetArrayRank ()))
2240 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2243 if (pt.IsByRef && at.IsByRef)
2244 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2245 ArrayList list = new ArrayList ();
2246 if (at.IsGenericInstance)
2248 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
2251 list.AddRange (TypeManager.GetInterfaces (at));
2253 bool found_one = false;
2255 foreach (Type type in list) {
2256 if (!type.IsGenericInstance)
2259 Type[] infered_types = new Type [infered.Length];
2261 if (!InferGenericInstance (pt, type, infered_types))
2264 for (int i = 0; i < infered_types.Length; i++) {
2265 if (infered [i] == null) {
2266 infered [i] = infered_types [i];
2270 if (infered [i] != infered_types [i])
2280 static bool InferGenericInstance (Type pt, Type at, Type[] infered_types)
2282 Type[] at_args = at.GetGenericArguments ();
2283 Type[] pt_args = pt.GetGenericArguments ();
2285 if (at_args.Length != pt_args.Length)
2288 for (int i = 0; i < at_args.Length; i++) {
2289 if (!InferType (pt_args [i], at_args [i], infered_types))
2293 for (int i = 0; i < infered_types.Length; i++) {
2294 if (infered_types [i] == null)
2302 /// Type inference. Try to infer the type arguments from the params method
2303 /// `method', which is invoked with the arguments `arguments'. This is used
2304 /// when resolving an Invocation or a DelegateInvocation and the user
2305 /// did not explicitly specify type arguments.
2307 public static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
2308 ref MethodBase method)
2310 if ((arguments == null) || !TypeManager.IsGenericMethod (method))
2315 if (arguments == null)
2318 arg_count = arguments.Count;
2320 ParameterData pd = TypeManager.GetParameterData (method);
2322 int pd_count = pd.Count;
2327 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2330 if (pd_count - 1 > arg_count)
2333 if (pd_count == 1 && arg_count == 0)
2336 Type[] method_args = method.GetGenericArguments ();
2337 Type[] infered_types = new Type [method_args.Length];
2340 // If we have come this far, the case which
2341 // remains is when the number of parameters is
2342 // less than or equal to the argument count.
2344 for (int i = 0; i < pd_count - 1; ++i) {
2345 Argument a = (Argument) arguments [i];
2347 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2350 Type pt = pd.ParameterType (i);
2353 if (!InferType (pt, at, infered_types))
2357 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
2359 for (int i = pd_count - 1; i < arg_count; i++) {
2360 Argument a = (Argument) arguments [i];
2362 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2365 if (!InferType (element_type, a.Type, infered_types))
2369 for (int i = 0; i < infered_types.Length; i++)
2370 if (infered_types [i] == null)
2373 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2377 static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
2378 Type[] infered_types)
2380 if (infered_types == null)
2383 for (int i = 0; i < arg_types.Length; i++) {
2384 if (arg_types [i] == null)
2387 if (!InferType (param_types [i], arg_types [i], infered_types))
2391 for (int i = 0; i < infered_types.Length; i++)
2392 if (infered_types [i] == null)
2399 /// Type inference. Try to infer the type arguments from `method',
2400 /// which is invoked with the arguments `arguments'. This is used
2401 /// when resolving an Invocation or a DelegateInvocation and the user
2402 /// did not explicitly specify type arguments.
2404 public static bool InferTypeArguments (EmitContext ec, ArrayList arguments,
2405 ref MethodBase method)
2407 if (!TypeManager.IsGenericMethod (method))
2411 if (arguments != null)
2412 arg_count = arguments.Count;
2416 ParameterData pd = TypeManager.GetParameterData (method);
2417 if (arg_count != pd.Count)
2420 Type[] method_args = method.GetGenericArguments ();
2422 bool is_open = false;
2423 for (int i = 0; i < method_args.Length; i++) {
2424 if (method_args [i].IsGenericParameter) {
2432 Type[] infered_types = new Type [method_args.Length];
2434 Type[] param_types = new Type [pd.Count];
2435 Type[] arg_types = new Type [pd.Count];
2437 for (int i = 0; i < arg_count; i++) {
2438 param_types [i] = pd.ParameterType (i);
2440 Argument a = (Argument) arguments [i];
2441 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr) ||
2442 (a.Expr is AnonymousMethod))
2445 arg_types [i] = a.Type;
2448 if (!InferTypeArguments (param_types, arg_types, infered_types))
2451 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2458 public static bool InferTypeArguments (EmitContext ec, ParameterData apd,
2459 ref MethodBase method)
2461 if (!TypeManager.IsGenericMethod (method))
2464 ParameterData pd = TypeManager.GetParameterData (method);
2465 if (apd.Count != pd.Count)
2468 Type[] method_args = method.GetGenericArguments ();
2469 Type[] infered_types = new Type [method_args.Length];
2471 Type[] param_types = new Type [pd.Count];
2472 Type[] arg_types = new Type [pd.Count];
2474 for (int i = 0; i < apd.Count; i++) {
2475 param_types [i] = pd.ParameterType (i);
2476 arg_types [i] = apd.ParameterType (i);
2479 if (!InferTypeArguments (param_types, arg_types, infered_types))
2482 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2486 public static bool IsNullableType (Type t)
2488 if (!t.IsGenericInstance)
2491 Type gt = t.GetGenericTypeDefinition ();
2492 return gt == generic_nullable_type;
2496 public abstract class Nullable
2498 protected sealed class NullableInfo
2500 public readonly Type Type;
2501 public readonly Type UnderlyingType;
2502 public readonly MethodInfo HasValue;
2503 public readonly MethodInfo Value;
2504 public readonly ConstructorInfo Constructor;
2506 public NullableInfo (Type type)
2509 UnderlyingType = TypeManager.GetTypeArguments (type) [0];
2511 PropertyInfo has_value_pi = type.GetProperty ("HasValue");
2512 PropertyInfo value_pi = type.GetProperty ("Value");
2514 HasValue = has_value_pi.GetGetMethod (false);
2515 Value = value_pi.GetGetMethod (false);
2516 Constructor = type.GetConstructor (new Type[] { UnderlyingType });
2520 protected class Unwrap : Expression, IMemoryLocation, IAssignMethod
2525 LocalTemporary temp;
2528 public Unwrap (Expression expr, Location loc)
2534 public override Expression DoResolve (EmitContext ec)
2536 expr = expr.Resolve (ec);
2540 if (!(expr is IMemoryLocation))
2541 temp = new LocalTemporary (ec, expr.Type);
2543 info = new NullableInfo (expr.Type);
2544 type = info.UnderlyingType;
2545 eclass = expr.eclass;
2549 public override void Emit (EmitContext ec)
2551 AddressOf (ec, AddressOp.LoadStore);
2552 ec.ig.EmitCall (OpCodes.Call, info.Value, null);
2555 public void EmitCheck (EmitContext ec)
2557 AddressOf (ec, AddressOp.LoadStore);
2558 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
2561 void create_temp (EmitContext ec)
2563 if ((temp != null) && !has_temp) {
2570 public void AddressOf (EmitContext ec, AddressOp mode)
2574 temp.AddressOf (ec, AddressOp.LoadStore);
2576 ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
2579 public void Emit (EmitContext ec, bool leave_copy)
2592 public void EmitAssign (EmitContext ec, Expression source,
2593 bool leave_copy, bool prepare_for_load)
2596 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2599 ec.ig.Emit (OpCodes.Dup);
2601 Expression empty = new EmptyExpression (expr.Type);
2602 ((IAssignMethod) expr).EmitAssign (ec, empty, false, prepare_for_load);
2606 protected class Wrap : Expression
2611 public Wrap (Expression expr, Location loc)
2617 public override Expression DoResolve (EmitContext ec)
2619 expr = expr.Resolve (ec);
2623 TypeExpr target_type = new NullableType (expr.Type, loc);
2624 target_type = target_type.ResolveAsTypeTerminal (ec);
2625 if (target_type == null)
2628 type = target_type.Type;
2629 info = new NullableInfo (type);
2630 eclass = ExprClass.Value;
2634 public override void Emit (EmitContext ec)
2637 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2641 public class NullableLiteral : Expression, IMemoryLocation {
2642 public NullableLiteral (Type target_type, Location loc)
2644 this.type = target_type;
2647 eclass = ExprClass.Value;
2650 public override Expression DoResolve (EmitContext ec)
2655 public override void Emit (EmitContext ec)
2657 LocalTemporary value_target = new LocalTemporary (ec, type);
2659 value_target.AddressOf (ec, AddressOp.Store);
2660 ec.ig.Emit (OpCodes.Initobj, type);
2661 value_target.Emit (ec);
2664 public void AddressOf (EmitContext ec, AddressOp Mode)
2666 LocalTemporary value_target = new LocalTemporary (ec, type);
2668 value_target.AddressOf (ec, AddressOp.Store);
2669 ec.ig.Emit (OpCodes.Initobj, type);
2670 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
2674 public abstract class Lifted : Expression, IMemoryLocation
2676 Expression expr, underlying, wrap, null_value;
2679 protected Lifted (Expression expr, Location loc)
2685 public override Expression DoResolve (EmitContext ec)
2687 expr = expr.Resolve (ec);
2691 unwrap = (Unwrap) new Unwrap (expr, loc).Resolve (ec);
2695 underlying = ResolveUnderlying (unwrap, ec);
2696 if (underlying == null)
2699 wrap = new Wrap (underlying, loc).Resolve (ec);
2703 null_value = new NullableLiteral (wrap.Type, loc).Resolve (ec);
2704 if (null_value == null)
2708 eclass = ExprClass.Value;
2712 protected abstract Expression ResolveUnderlying (Expression unwrap, EmitContext ec);
2714 public override void Emit (EmitContext ec)
2716 ILGenerator ig = ec.ig;
2717 Label is_null_label = ig.DefineLabel ();
2718 Label end_label = ig.DefineLabel ();
2720 unwrap.EmitCheck (ec);
2721 ig.Emit (OpCodes.Brfalse, is_null_label);
2724 ig.Emit (OpCodes.Br, end_label);
2726 ig.MarkLabel (is_null_label);
2727 null_value.Emit (ec);
2729 ig.MarkLabel (end_label);
2732 public void AddressOf (EmitContext ec, AddressOp mode)
2734 unwrap.AddressOf (ec, mode);
2738 public class LiftedConversion : Lifted
2740 public readonly bool IsUser;
2741 public readonly bool IsExplicit;
2742 public readonly Type TargetType;
2744 public LiftedConversion (Expression expr, Type target_type, bool is_user,
2745 bool is_explicit, Location loc)
2748 this.IsUser = is_user;
2749 this.IsExplicit = is_explicit;
2750 this.TargetType = target_type;
2753 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2755 Type type = TypeManager.GetTypeArguments (TargetType) [0];
2758 return Convert.UserDefinedConversion (ec, unwrap, type, loc, IsExplicit);
2761 return Convert.ExplicitConversion (ec, unwrap, type, loc);
2763 return Convert.ImplicitConversion (ec, unwrap, type, loc);
2768 public class LiftedUnaryOperator : Lifted
2770 public readonly Unary.Operator Oper;
2772 public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
2778 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2780 return new Unary (Oper, unwrap, loc);
2784 public class LiftedConditional : Lifted
2786 Expression true_expr, false_expr;
2788 public LiftedConditional (Expression expr, Expression true_expr, Expression false_expr,
2792 this.true_expr = true_expr;
2793 this.false_expr = false_expr;
2796 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2798 return new Conditional (unwrap, true_expr, false_expr);
2802 public class LiftedBinaryOperator : Expression
2804 public readonly Binary.Operator Oper;
2806 Expression left, right, underlying, null_value, bool_wrap;
2807 Unwrap left_unwrap, right_unwrap;
2808 bool is_equality, is_comparision, is_boolean;
2810 public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
2819 public override Expression DoResolve (EmitContext ec)
2821 if (TypeManager.IsNullableType (left.Type)) {
2822 left_unwrap = new Unwrap (left, loc);
2823 left = left_unwrap.Resolve (ec);
2828 if (TypeManager.IsNullableType (right.Type)) {
2829 right_unwrap = new Unwrap (right, loc);
2830 right = right_unwrap.Resolve (ec);
2835 if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr) ||
2836 (Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr)) &&
2837 ((left.Type == TypeManager.bool_type) && (right.Type == TypeManager.bool_type))) {
2838 Expression empty = new EmptyExpression (TypeManager.bool_type);
2839 bool_wrap = new Wrap (empty, loc).Resolve (ec);
2840 null_value = new NullableLiteral (bool_wrap.Type, loc).Resolve (ec);
2842 type = bool_wrap.Type;
2844 } else if ((Oper == Binary.Operator.Equality) || (Oper == Binary.Operator.Inequality)) {
2845 if (!(left is NullLiteral) && !(right is NullLiteral)) {
2846 underlying = new Binary (Oper, left, right).Resolve (ec);
2847 if (underlying == null)
2851 type = TypeManager.bool_type;
2853 } else if ((Oper == Binary.Operator.LessThan) ||
2854 (Oper == Binary.Operator.GreaterThan) ||
2855 (Oper == Binary.Operator.LessThanOrEqual) ||
2856 (Oper == Binary.Operator.GreaterThanOrEqual)) {
2857 underlying = new Binary (Oper, left, right).Resolve (ec);
2858 if (underlying == null)
2861 type = TypeManager.bool_type;
2862 is_comparision = true;
2864 underlying = new Binary (Oper, left, right).Resolve (ec);
2865 if (underlying == null)
2868 underlying = new Wrap (underlying, loc).Resolve (ec);
2869 if (underlying == null)
2872 type = underlying.Type;
2873 null_value = new NullableLiteral (type, loc).Resolve (ec);
2876 eclass = ExprClass.Value;
2880 void EmitBoolean (EmitContext ec)
2882 ILGenerator ig = ec.ig;
2884 Label left_is_null_label = ig.DefineLabel ();
2885 Label right_is_null_label = ig.DefineLabel ();
2886 Label is_null_label = ig.DefineLabel ();
2887 Label wrap_label = ig.DefineLabel ();
2888 Label end_label = ig.DefineLabel ();
2890 if (left_unwrap != null) {
2891 left_unwrap.EmitCheck (ec);
2892 ig.Emit (OpCodes.Brfalse, left_is_null_label);
2896 ig.Emit (OpCodes.Dup);
2897 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
2898 ig.Emit (OpCodes.Brtrue, wrap_label);
2900 ig.Emit (OpCodes.Brfalse, wrap_label);
2902 if (right_unwrap != null) {
2903 right_unwrap.EmitCheck (ec);
2904 ig.Emit (OpCodes.Brfalse, right_is_null_label);
2907 if ((Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr))
2908 ig.Emit (OpCodes.Pop);
2911 if (Oper == Binary.Operator.BitwiseOr)
2912 ig.Emit (OpCodes.Or);
2913 else if (Oper == Binary.Operator.BitwiseAnd)
2914 ig.Emit (OpCodes.And);
2915 ig.Emit (OpCodes.Br, wrap_label);
2917 ig.MarkLabel (left_is_null_label);
2918 if (right_unwrap != null) {
2919 right_unwrap.EmitCheck (ec);
2920 ig.Emit (OpCodes.Brfalse, is_null_label);
2924 ig.Emit (OpCodes.Dup);
2925 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
2926 ig.Emit (OpCodes.Brtrue, wrap_label);
2928 ig.Emit (OpCodes.Brfalse, wrap_label);
2930 ig.MarkLabel (right_is_null_label);
2931 ig.Emit (OpCodes.Pop);
2932 ig.MarkLabel (is_null_label);
2933 null_value.Emit (ec);
2934 ig.Emit (OpCodes.Br, end_label);
2936 ig.MarkLabel (wrap_label);
2937 ig.Emit (OpCodes.Nop);
2938 bool_wrap.Emit (ec);
2939 ig.Emit (OpCodes.Nop);
2941 ig.MarkLabel (end_label);
2944 void EmitEquality (EmitContext ec)
2946 ILGenerator ig = ec.ig;
2948 Label left_not_null_label = ig.DefineLabel ();
2949 Label false_label = ig.DefineLabel ();
2950 Label true_label = ig.DefineLabel ();
2951 Label end_label = ig.DefineLabel ();
2953 bool false_label_used = false;
2954 bool true_label_used = false;
2956 if (left_unwrap != null) {
2957 left_unwrap.EmitCheck (ec);
2958 if (right is NullLiteral) {
2959 if (Oper == Binary.Operator.Equality) {
2960 true_label_used = true;
2961 ig.Emit (OpCodes.Brfalse, true_label);
2963 false_label_used = true;
2964 ig.Emit (OpCodes.Brfalse, false_label);
2966 } else if (right_unwrap != null) {
2967 ig.Emit (OpCodes.Dup);
2968 ig.Emit (OpCodes.Brtrue, left_not_null_label);
2969 right_unwrap.EmitCheck (ec);
2970 ig.Emit (OpCodes.Ceq);
2971 if (Oper == Binary.Operator.Inequality) {
2972 ig.Emit (OpCodes.Ldc_I4_0);
2973 ig.Emit (OpCodes.Ceq);
2975 ig.Emit (OpCodes.Br, end_label);
2977 ig.MarkLabel (left_not_null_label);
2978 ig.Emit (OpCodes.Pop);
2980 if (Oper == Binary.Operator.Equality) {
2981 false_label_used = true;
2982 ig.Emit (OpCodes.Brfalse, false_label);
2984 true_label_used = true;
2985 ig.Emit (OpCodes.Brfalse, true_label);
2990 if (right_unwrap != null) {
2991 right_unwrap.EmitCheck (ec);
2992 if (left is NullLiteral) {
2993 if (Oper == Binary.Operator.Equality) {
2994 true_label_used = true;
2995 ig.Emit (OpCodes.Brfalse, true_label);
2997 false_label_used = true;
2998 ig.Emit (OpCodes.Brfalse, false_label);
3001 if (Oper == Binary.Operator.Equality) {
3002 false_label_used = true;
3003 ig.Emit (OpCodes.Brfalse, false_label);
3005 true_label_used = true;
3006 ig.Emit (OpCodes.Brfalse, true_label);
3011 bool left_is_null = left is NullLiteral;
3012 bool right_is_null = right is NullLiteral;
3013 if (left_is_null || right_is_null) {
3014 if (((Oper == Binary.Operator.Equality) && (left_is_null == right_is_null)) ||
3015 ((Oper == Binary.Operator.Inequality) && (left_is_null != right_is_null))) {
3016 true_label_used = true;
3017 ig.Emit (OpCodes.Br, true_label);
3019 false_label_used = true;
3020 ig.Emit (OpCodes.Br, false_label);
3023 underlying.Emit (ec);
3024 ig.Emit (OpCodes.Br, end_label);
3027 ig.MarkLabel (false_label);
3028 if (false_label_used) {
3029 ig.Emit (OpCodes.Ldc_I4_0);
3030 if (true_label_used)
3031 ig.Emit (OpCodes.Br, end_label);
3034 ig.MarkLabel (true_label);
3035 if (true_label_used)
3036 ig.Emit (OpCodes.Ldc_I4_1);
3038 ig.MarkLabel (end_label);
3041 void EmitComparision (EmitContext ec)
3043 ILGenerator ig = ec.ig;
3045 Label is_null_label = ig.DefineLabel ();
3046 Label end_label = ig.DefineLabel ();
3048 if (left_unwrap != null) {
3049 left_unwrap.EmitCheck (ec);
3050 ig.Emit (OpCodes.Brfalse, is_null_label);
3053 if (right_unwrap != null) {
3054 right_unwrap.EmitCheck (ec);
3055 ig.Emit (OpCodes.Brfalse, is_null_label);
3058 underlying.Emit (ec);
3059 ig.Emit (OpCodes.Br, end_label);
3061 ig.MarkLabel (is_null_label);
3062 ig.Emit (OpCodes.Ldc_I4_0);
3064 ig.MarkLabel (end_label);
3067 public override void Emit (EmitContext ec)
3072 } else if (is_equality) {
3075 } else if (is_comparision) {
3076 EmitComparision (ec);
3080 ILGenerator ig = ec.ig;
3082 Label is_null_label = ig.DefineLabel ();
3083 Label end_label = ig.DefineLabel ();
3085 if (left_unwrap != null) {
3086 left_unwrap.EmitCheck (ec);
3087 ig.Emit (OpCodes.Brfalse, is_null_label);
3090 if (right_unwrap != null) {
3091 right_unwrap.EmitCheck (ec);
3092 ig.Emit (OpCodes.Brfalse, is_null_label);
3095 underlying.Emit (ec);
3096 ig.Emit (OpCodes.Br, end_label);
3098 ig.MarkLabel (is_null_label);
3099 null_value.Emit (ec);
3101 ig.MarkLabel (end_label);
3105 public class OperatorTrueOrFalse : Expression
3107 public readonly bool IsTrue;
3112 public OperatorTrueOrFalse (Expression expr, bool is_true, Location loc)
3114 this.IsTrue = is_true;
3119 public override Expression DoResolve (EmitContext ec)
3121 unwrap = new Unwrap (expr, loc);
3122 expr = unwrap.Resolve (ec);
3126 if (unwrap.Type != TypeManager.bool_type)
3129 type = TypeManager.bool_type;
3130 eclass = ExprClass.Value;
3134 public override void Emit (EmitContext ec)
3136 ILGenerator ig = ec.ig;
3138 Label is_null_label = ig.DefineLabel ();
3139 Label end_label = ig.DefineLabel ();
3141 unwrap.EmitCheck (ec);
3142 ig.Emit (OpCodes.Brfalse, is_null_label);
3146 ig.Emit (OpCodes.Ldc_I4_0);
3147 ig.Emit (OpCodes.Ceq);
3149 ig.Emit (OpCodes.Br, end_label);
3151 ig.MarkLabel (is_null_label);
3152 ig.Emit (OpCodes.Ldc_I4_0);
3154 ig.MarkLabel (end_label);
3158 public class NullCoalescingOperator : Expression
3160 Expression left, right;
3164 public NullCoalescingOperator (Expression left, Expression right, Location loc)
3170 eclass = ExprClass.Value;
3173 public override Expression DoResolve (EmitContext ec)
3178 left = left.Resolve (ec);
3182 right = right.Resolve (ec);
3186 Type ltype = left.Type, rtype = right.Type;
3188 if (!TypeManager.IsNullableType (ltype) && ltype.IsValueType) {
3189 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3193 if (TypeManager.IsNullableType (ltype)) {
3194 NullableInfo info = new NullableInfo (ltype);
3196 unwrap = (Unwrap) new Unwrap (left, loc).Resolve (ec);
3200 expr = Convert.ImplicitConversion (ec, right, info.UnderlyingType, loc);
3208 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
3214 if (unwrap != null) {
3215 expr = Convert.ImplicitConversion (ec, unwrap, rtype, loc);
3224 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3228 public override void Emit (EmitContext ec)
3230 ILGenerator ig = ec.ig;
3232 Label is_null_label = ig.DefineLabel ();
3233 Label end_label = ig.DefineLabel ();
3235 if (unwrap != null) {
3236 unwrap.EmitCheck (ec);
3237 ig.Emit (OpCodes.Brfalse, is_null_label);
3240 ig.Emit (OpCodes.Br, end_label);
3242 ig.MarkLabel (is_null_label);
3245 ig.MarkLabel (end_label);
3248 ig.Emit (OpCodes.Dup);
3249 ig.Emit (OpCodes.Brtrue, end_label);
3251 ig.MarkLabel (is_null_label);
3253 ig.Emit (OpCodes.Pop);
3256 ig.MarkLabel (end_label);
3261 public class LiftedUnaryMutator : ExpressionStatement
3263 public readonly UnaryMutator.Mode Mode;
3264 Expression expr, null_value;
3265 UnaryMutator underlying;
3268 public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
3274 eclass = ExprClass.Value;
3277 public override Expression DoResolve (EmitContext ec)
3279 expr = expr.Resolve (ec);
3283 unwrap = (Unwrap) new Unwrap (expr, loc).Resolve (ec);
3287 underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
3288 if (underlying == null)
3291 null_value = new NullableLiteral (expr.Type, loc).Resolve (ec);
3292 if (null_value == null)
3299 void DoEmit (EmitContext ec, bool is_expr)
3301 ILGenerator ig = ec.ig;
3302 Label is_null_label = ig.DefineLabel ();
3303 Label end_label = ig.DefineLabel ();
3305 unwrap.EmitCheck (ec);
3306 ig.Emit (OpCodes.Brfalse, is_null_label);
3309 underlying.Emit (ec);
3311 underlying.EmitStatement (ec);
3312 ig.Emit (OpCodes.Br, end_label);
3314 ig.MarkLabel (is_null_label);
3316 null_value.Emit (ec);
3318 ig.MarkLabel (end_label);
3321 public override void Emit (EmitContext ec)
3326 public override void EmitStatement (EmitContext ec)