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))
466 public override GenericParameterAttributes Attributes {
467 get { return attrs; }
470 public override bool HasClassConstraint {
471 get { return class_constraint != null; }
474 public override Type ClassConstraint {
475 get { return class_constraint_type; }
478 public override Type[] InterfaceConstraints {
479 get { return iface_constraint_types; }
482 public override Type EffectiveBaseClass {
483 get { return effective_base_type; }
486 public bool IsSubclassOf (Type t)
488 if ((class_constraint_type != null) &&
489 class_constraint_type.IsSubclassOf (t))
492 if (iface_constraint_types == null)
495 foreach (Type iface in iface_constraint_types) {
496 if (TypeManager.IsSubclassOf (iface, t))
504 /// This is used when we're implementing a generic interface method.
505 /// Each method type parameter in implementing method must have the same
506 /// constraints than the corresponding type parameter in the interface
507 /// method. To do that, we're called on each of the implementing method's
510 public bool CheckInterfaceMethod (EmitContext ec, GenericConstraints gc)
512 if (gc.Attributes != attrs)
515 if (HasClassConstraint != gc.HasClassConstraint)
517 if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
520 int gc_icount = gc.InterfaceConstraints != null ?
521 gc.InterfaceConstraints.Length : 0;
522 int icount = InterfaceConstraints != null ?
523 InterfaceConstraints.Length : 0;
525 if (gc_icount != icount)
528 foreach (Type iface in gc.InterfaceConstraints) {
530 foreach (Type check in InterfaceConstraints) {
531 if (TypeManager.IsEqual (iface, check)) {
546 /// A type parameter from a generic type definition.
548 public class TypeParameter : MemberCore, IMemberContainer {
551 GenericConstraints gc;
552 Constraints constraints;
554 GenericTypeParameterBuilder type;
556 public TypeParameter (DeclSpace parent, DeclSpace decl, string name,
557 Constraints constraints, Attributes attrs, Location loc)
558 : base (parent, new MemberName (name, loc), attrs)
562 this.constraints = constraints;
566 public GenericConstraints GenericConstraints {
568 return gc != null ? gc : constraints;
572 public Constraints Constraints {
578 public bool HasConstructorConstraint {
580 if (constraints != null)
581 return constraints.HasConstructorConstraint;
587 public DeclSpace DeclSpace {
600 /// This is the first method which is called during the resolving
601 /// process; we're called immediately after creating the type parameters
602 /// with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
605 /// We're either called from TypeContainer.DefineType() or from
606 /// GenericMethod.Define() (called from Method.Define()).
608 public void Define (GenericTypeParameterBuilder type)
610 if (this.type != null)
611 throw new InvalidOperationException ();
614 TypeManager.AddTypeParameter (type, this);
618 /// This is the second method which is called during the resolving
619 /// process - in case of class type parameters, we're called from
620 /// TypeContainer.ResolveType() - after it resolved the class'es
621 /// base class and interfaces. For method type parameters, we're
622 /// called immediately after Define().
624 /// We're just resolving the constraints into expressions here, we
625 /// don't resolve them into actual types.
627 /// Note that in the special case of partial generic classes, we may be
628 /// called _before_ Define() and we may also be called multiple types.
630 public bool Resolve (DeclSpace ds)
632 if (constraints != null) {
633 if (!constraints.Resolve (ds.EmitContext)) {
643 /// This is the third method which is called during the resolving
644 /// process. We're called immediately after calling DefineConstraints()
645 /// on all of the current class'es type parameters.
647 /// Our job is to resolve the constraints to actual types.
649 /// Note that we may have circular dependencies on type parameters - this
650 /// is why Resolve() and ResolveType() are separate.
652 public bool ResolveType (EmitContext ec)
654 if (constraints != null) {
655 if (!constraints.ResolveTypes (ec)) {
665 /// This is the fourth and last method which is called during the resolving
666 /// process. We're called after everything is fully resolved and actually
667 /// register the constraints with SRE and the TypeManager.
669 public bool DefineType (EmitContext ec)
671 return DefineType (ec, null, null, false);
675 /// This is the fith and last method which is called during the resolving
676 /// process. We're called after everything is fully resolved and actually
677 /// register the constraints with SRE and the TypeManager.
679 /// The `builder', `implementing' and `is_override' arguments are only
680 /// applicable to method type parameters.
682 public bool DefineType (EmitContext ec, MethodBuilder builder,
683 MethodInfo implementing, bool is_override)
685 if (!ResolveType (ec))
688 if (implementing != null) {
689 if (is_override && (constraints != null)) {
691 460, loc, "Constraints for override and " +
692 "explicit interface implementation methods " +
693 "are inherited from the base method so they " +
694 "cannot be specified directly");
698 MethodBase mb = TypeManager.DropGenericMethodArguments (implementing);
700 int pos = type.GenericParameterPosition;
701 Type mparam = mb.GetGenericArguments () [pos];
702 GenericConstraints temp_gc = ReflectionConstraints.GetConstraints (mparam);
705 gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
706 else if (constraints != null)
707 gc = new InflatedConstraints (constraints, implementing.DeclaringType);
710 if (constraints != null) {
713 else if (!constraints.CheckInterfaceMethod (ec, gc))
716 if (!is_override && (temp_gc != null))
721 Report.SymbolRelatedToPreviousError (implementing);
724 425, loc, "The constraints for type " +
725 "parameter `{0}' of method `{1}' must match " +
726 "the constraints for type parameter `{2}' " +
727 "of interface method `{3}'. Consider using " +
728 "an explicit interface implementation instead",
729 Name, TypeManager.CSharpSignature (builder),
730 TypeManager.CSharpName (mparam), TypeManager.CSharpSignature (mb));
733 } else if (DeclSpace is Iterator) {
734 TypeParameter[] tparams = DeclSpace.TypeParameters;
735 Type[] types = new Type [tparams.Length];
736 for (int i = 0; i < tparams.Length; i++)
737 types [i] = tparams [i].Type;
739 if (constraints != null)
740 gc = new InflatedConstraints (constraints, types);
742 gc = (GenericConstraints) constraints;
748 if (gc.HasClassConstraint)
749 type.SetBaseTypeConstraint (gc.ClassConstraint);
751 type.SetInterfaceConstraints (gc.InterfaceConstraints);
752 type.SetGenericParameterAttributes (gc.Attributes);
753 TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
759 /// Check whether there are no conflicts in our type parameter constraints.
761 /// This is an example:
765 /// where U : T, struct
767 public bool CheckDependencies (EmitContext ec)
769 if (constraints != null)
770 return constraints.CheckDependencies (ec);
776 /// This is called for each part of a partial generic type definition.
778 /// If `new_constraints' is not null and we don't already have constraints,
779 /// they become our constraints. If we already have constraints, we must
780 /// check that they're the same.
783 public bool UpdateConstraints (EmitContext ec, Constraints new_constraints)
786 throw new InvalidOperationException ();
788 if (constraints == null) {
789 new_constraints = constraints;
791 } else if (new_constraints == null)
794 if (!new_constraints.Resolve (ec))
796 if (!new_constraints.ResolveTypes (ec))
799 return constraints.CheckInterfaceMethod (ec, new_constraints);
802 public void EmitAttributes (EmitContext ec)
804 if (OptAttributes != null)
805 OptAttributes.Emit (ec, this);
808 public override string DocCommentHeader {
810 throw new InvalidOperationException (
811 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
819 public override bool Define ()
824 public override void ApplyAttributeBuilder (Attribute a,
825 CustomAttributeBuilder cb)
827 type.SetCustomAttribute (cb);
830 public override AttributeTargets AttributeTargets {
832 return (AttributeTargets) AttributeTargets.GenericParameter;
836 public override string[] ValidAttributeTargets {
838 return new string [] { "type parameter" };
846 string IMemberContainer.Name {
850 MemberCache IMemberContainer.BaseCache {
854 bool IMemberContainer.IsInterface {
858 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
860 return FindMembers (mt, bf, null, null);
863 MemberCache IMemberContainer.MemberCache {
867 public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
868 MemberFilter filter, object criteria)
870 if (constraints == null)
871 return MemberList.Empty;
873 ArrayList members = new ArrayList ();
875 if (gc.HasClassConstraint) {
876 MemberList list = TypeManager.FindMembers (
877 gc.ClassConstraint, mt, bf, filter, criteria);
879 members.AddRange (list);
882 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
883 foreach (Type t in ifaces) {
884 MemberList list = TypeManager.FindMembers (
885 t, mt, bf, filter, criteria);
887 members.AddRange (list);
890 return new MemberList (members);
893 public bool IsSubclassOf (Type t)
898 if (constraints != null)
899 return constraints.IsSubclassOf (t);
904 public override string ToString ()
906 return "TypeParameter[" + name + "]";
909 public static string GetSignatureForError (TypeParameter[] tp)
911 if (tp == null || tp.Length == 0)
914 StringBuilder sb = new StringBuilder ("<");
915 for (int i = 0; i < tp.Length; ++i) {
918 sb.Append (tp[i].GetSignatureForError ());
921 return sb.ToString ();
924 public void InflateConstraints (Type declaring)
926 if (constraints != null)
927 gc = new InflatedConstraints (constraints, declaring);
930 protected class InflatedConstraints : GenericConstraints
932 GenericConstraints gc;
934 Type class_constraint;
935 Type[] iface_constraints;
938 public InflatedConstraints (GenericConstraints gc, Type declaring)
939 : this (gc, TypeManager.GetTypeArguments (declaring))
942 public InflatedConstraints (GenericConstraints gc, Type[] dargs)
947 ArrayList list = new ArrayList ();
948 if (gc.HasClassConstraint)
949 list.Add (inflate (gc.ClassConstraint));
950 foreach (Type iface in gc.InterfaceConstraints)
951 list.Add (inflate (iface));
953 bool has_class_constr = false;
954 if (list.Count > 0) {
955 Type first = (Type) list [0];
956 has_class_constr = !first.IsInterface && !first.IsGenericParameter;
959 if ((list.Count > 0) && has_class_constr) {
960 class_constraint = (Type) list [0];
961 iface_constraints = new Type [list.Count - 1];
962 list.CopyTo (1, iface_constraints, 0, list.Count - 1);
964 iface_constraints = new Type [list.Count];
965 list.CopyTo (iface_constraints, 0);
968 if (HasValueTypeConstraint)
969 base_type = TypeManager.value_type;
970 else if (class_constraint != null)
971 base_type = class_constraint;
973 base_type = TypeManager.object_type;
976 Type inflate (Type t)
980 if (t.IsGenericParameter)
981 return dargs [t.GenericParameterPosition];
982 if (t.IsGenericType) {
983 t = t.GetGenericTypeDefinition ();
984 t = t.MakeGenericType (dargs);
990 public override string TypeParameter {
991 get { return gc.TypeParameter; }
994 public override GenericParameterAttributes Attributes {
995 get { return gc.Attributes; }
998 public override Type ClassConstraint {
999 get { return class_constraint; }
1002 public override Type EffectiveBaseClass {
1003 get { return base_type; }
1006 public override Type[] InterfaceConstraints {
1007 get { return iface_constraints; }
1013 /// A TypeExpr which already resolved to a type parameter.
1015 public class TypeParameterExpr : TypeExpr {
1016 TypeParameter type_parameter;
1018 public override string Name {
1020 return type_parameter.Name;
1024 public override string FullName {
1026 return type_parameter.Name;
1030 public TypeParameter TypeParameter {
1032 return type_parameter;
1036 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1038 this.type_parameter = type_parameter;
1042 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
1044 type = type_parameter.Type;
1049 public override bool IsInterface {
1050 get { return false; }
1053 public override bool CheckAccessLevel (DeclSpace ds)
1058 public void Error_CannotUseAsUnmanagedType (Location loc)
1060 Report.Error (-203, loc, "Can not use type parameter as unamanged type");
1065 /// Tracks the type arguments when instantiating a generic type. We're used in
1066 /// ConstructedType.
1068 public class TypeArguments {
1069 public readonly Location Location;
1076 public TypeArguments (Location loc)
1078 args = new ArrayList ();
1079 this.Location = loc;
1082 public TypeArguments (int dimension, Location loc)
1084 this.dimension = dimension;
1085 this.Location = loc;
1088 public void Add (Expression type)
1091 throw new InvalidOperationException ();
1096 public void Add (TypeArguments new_args)
1099 throw new InvalidOperationException ();
1101 args.AddRange (new_args.args);
1105 /// We're used during the parsing process: the parser can't distinguish
1106 /// between type parameters and type arguments. Because of that, the
1107 /// parser creates a `MemberName' with `TypeArguments' for both cases and
1108 /// in case of a generic type definition, we call GetDeclarations().
1110 public TypeParameterName[] GetDeclarations ()
1112 TypeParameterName[] ret = new TypeParameterName [args.Count];
1113 for (int i = 0; i < args.Count; i++) {
1114 TypeParameterName name = args [i] as TypeParameterName;
1119 SimpleName sn = args [i] as SimpleName;
1121 ret [i] = new TypeParameterName (sn.Name, null, sn.Location);
1125 Report.Error (81, Location, "Type parameter declaration " +
1126 "must be an identifier not a type");
1133 /// We may only be used after Resolve() is called and return the fully
1136 public Type[] Arguments {
1142 public bool HasTypeArguments {
1144 return has_type_args;
1157 public bool IsUnbound {
1159 return dimension > 0;
1163 public override string ToString ()
1165 StringBuilder s = new StringBuilder ();
1168 for (int i = 0; i < count; i++){
1170 // FIXME: Use TypeManager.CSharpname once we have the type
1173 s.Append (args [i].ToString ());
1177 return s.ToString ();
1181 /// Resolve the type arguments.
1183 public bool Resolve (EmitContext ec)
1185 int count = args.Count;
1188 atypes = new Type [count];
1190 for (int i = 0; i < count; i++){
1191 TypeExpr te = ((Expression) args [i]).ResolveAsTypeTerminal (ec);
1196 if (te is TypeParameterExpr)
1197 has_type_args = true;
1199 if (te.Type.IsPointer) {
1200 Report.Error (306, Location, "The type `{0}' may not be used " +
1201 "as a type argument.", TypeManager.CSharpName (te.Type));
1203 } else if (te.Type == TypeManager.void_type) {
1204 Report.Error (1547, Location,
1205 "Keyword `void' cannot be used in this context");
1209 atypes [i] = te.Type;
1215 public class TypeParameterName : SimpleName
1217 Attributes attributes;
1219 public TypeParameterName (string name, Attributes attrs, Location loc)
1225 public Attributes OptAttributes {
1233 /// An instantiation of a generic type.
1235 public class ConstructedType : TypeExpr {
1237 FullNamedExpression name;
1239 Type[] gen_params, atypes;
1243 /// Instantiate the generic type `fname' with the type arguments `args'.
1245 public ConstructedType (FullNamedExpression fname, TypeArguments args, Location l)
1251 eclass = ExprClass.Type;
1252 full_name = name + "<" + args.ToString () + ">";
1255 protected ConstructedType (TypeArguments args, Location l)
1260 eclass = ExprClass.Type;
1263 protected ConstructedType (TypeParameter[] type_params, Location l)
1267 args = new TypeArguments (l);
1268 foreach (TypeParameter type_param in type_params)
1269 args.Add (new TypeParameterExpr (type_param, l));
1271 eclass = ExprClass.Type;
1275 /// This is used to construct the `this' type inside a generic type definition.
1277 public ConstructedType (Type t, TypeParameter[] type_params, Location l)
1278 : this (type_params, l)
1280 gt = t.GetGenericTypeDefinition ();
1282 this.name = new TypeExpression (gt, l);
1283 full_name = gt.FullName + "<" + args.ToString () + ">";
1287 /// Instantiate the generic type `t' with the type arguments `args'.
1288 /// Use this constructor if you already know the fully resolved
1291 public ConstructedType (Type t, TypeArguments args, Location l)
1294 gt = t.GetGenericTypeDefinition ();
1296 this.name = new TypeExpression (gt, l);
1297 full_name = gt.FullName + "<" + args.ToString () + ">";
1300 public TypeArguments TypeArguments {
1301 get { return args; }
1304 public override string GetSignatureForError ()
1306 return TypeManager.CSharpName (gt);
1309 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
1311 if (!ResolveConstructedType (ec))
1318 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1319 /// after fully resolving the constructed type.
1321 public bool CheckConstraints (EmitContext ec)
1323 return ConstraintChecker.CheckConstraints (ec, gt, gen_params, atypes, loc);
1327 /// Resolve the constructed type, but don't check the constraints.
1329 public bool ResolveConstructedType (EmitContext ec)
1333 // If we already know the fully resolved generic type.
1335 return DoResolveType (ec);
1341 Report.Error (246, loc, "Cannot find type `{0}'<...>", Name);
1345 num_args = TypeManager.GetNumberOfTypeArguments (t);
1346 if (num_args == 0) {
1347 Report.Error (308, loc,
1348 "The non-generic type `{0}' cannot " +
1349 "be used with type arguments.",
1350 TypeManager.CSharpName (t));
1354 gt = t.GetGenericTypeDefinition ();
1355 return DoResolveType (ec);
1358 bool DoResolveType (EmitContext ec)
1361 // Resolve the arguments.
1363 if (args.Resolve (ec) == false)
1366 gen_params = gt.GetGenericArguments ();
1367 atypes = args.Arguments;
1369 if (atypes.Length != gen_params.Length) {
1370 Report.Error (305, loc,
1371 "Using the generic type `{0}' " +
1372 "requires {1} type arguments",
1373 TypeManager.CSharpName (gt),
1374 gen_params.Length.ToString ());
1379 // Now bind the parameters.
1381 type = gt.MakeGenericType (atypes);
1385 public Expression GetSimpleName (EmitContext ec)
1390 public override bool CheckAccessLevel (DeclSpace ds)
1392 return ds.CheckAccessLevel (gt);
1395 public override bool AsAccessible (DeclSpace ds, int flags)
1397 return ds.AsAccessible (gt, flags);
1400 public override bool IsClass {
1401 get { return gt.IsClass; }
1404 public override bool IsValueType {
1405 get { return gt.IsValueType; }
1408 public override bool IsInterface {
1409 get { return gt.IsInterface; }
1412 public override bool IsSealed {
1413 get { return gt.IsSealed; }
1416 public override bool Equals (object obj)
1418 ConstructedType cobj = obj as ConstructedType;
1422 if ((type == null) || (cobj.type == null))
1425 return type == cobj.type;
1428 public override int GetHashCode ()
1430 return base.GetHashCode ();
1433 public override string Name {
1440 public override string FullName {
1447 public abstract class ConstraintChecker
1449 protected readonly Type[] gen_params;
1450 protected readonly Type[] atypes;
1451 protected readonly Location loc;
1453 protected ConstraintChecker (Type[] gen_params, Type[] atypes, Location loc)
1455 this.gen_params = gen_params;
1456 this.atypes = atypes;
1461 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1462 /// after fully resolving the constructed type.
1464 public bool CheckConstraints (EmitContext ec)
1466 for (int i = 0; i < gen_params.Length; i++) {
1467 if (!CheckConstraints (ec, i))
1474 protected bool CheckConstraints (EmitContext ec, int index)
1476 Type atype = atypes [index];
1477 Type ptype = gen_params [index];
1482 Expression aexpr = new EmptyExpression (atype);
1484 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1488 bool is_class, is_struct;
1489 if (atype.IsGenericParameter) {
1490 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1492 is_class = agc.HasReferenceTypeConstraint;
1493 is_struct = agc.HasValueTypeConstraint;
1495 is_class = is_struct = false;
1498 is_class = atype.IsClass || atype.IsInterface;
1499 is_struct = atype.IsValueType && !TypeManager.IsNullableType (atype);
1503 // First, check the `class' and `struct' constraints.
1505 if (gc.HasReferenceTypeConstraint && !is_class) {
1506 Report.Error (452, loc, "The type `{0}' must be " +
1507 "a reference type in order to use it " +
1508 "as type parameter `{1}' in the " +
1509 "generic type or method `{2}'.",
1510 TypeManager.CSharpName (atype),
1511 TypeManager.CSharpName (ptype),
1512 GetSignatureForError ());
1514 } else if (gc.HasValueTypeConstraint && !is_struct) {
1515 Report.Error (453, loc, "The type `{0}' must be a " +
1516 "non-nullable value type in order to use it " +
1517 "as type parameter `{1}' in the " +
1518 "generic type or method `{2}'.",
1519 TypeManager.CSharpName (atype),
1520 TypeManager.CSharpName (ptype),
1521 GetSignatureForError ());
1526 // The class constraint comes next.
1528 if (gc.HasClassConstraint) {
1529 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint))
1534 // Now, check the interface constraints.
1536 foreach (Type it in gc.InterfaceConstraints) {
1537 if (!CheckConstraint (ec, ptype, aexpr, it))
1542 // Finally, check the constructor constraint.
1545 if (!gc.HasConstructorConstraint)
1548 if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
1551 if (HasDefaultConstructor (ec, atype))
1554 Report_SymbolRelatedToPreviousError ();
1555 Report.SymbolRelatedToPreviousError (atype);
1556 Report.Error (310, loc, "The type `{0}' must have a public " +
1557 "parameterless constructor in order to use it " +
1558 "as parameter `{1}' in the generic type or " +
1560 TypeManager.CSharpName (atype),
1561 TypeManager.CSharpName (ptype),
1562 GetSignatureForError ());
1566 protected bool CheckConstraint (EmitContext ec, Type ptype, Expression expr,
1569 if (TypeManager.HasGenericArguments (ctype)) {
1570 Type[] types = TypeManager.GetTypeArguments (ctype);
1572 TypeArguments new_args = new TypeArguments (loc);
1574 for (int i = 0; i < types.Length; i++) {
1577 if (t.IsGenericParameter) {
1578 int pos = t.GenericParameterPosition;
1581 new_args.Add (new TypeExpression (t, loc));
1584 TypeExpr ct = new ConstructedType (ctype, new_args, loc);
1585 if (ct.ResolveAsTypeStep (ec) == null)
1588 } else if (ctype.IsGenericParameter) {
1589 int pos = ctype.GenericParameterPosition;
1590 ctype = atypes [pos];
1593 if (Convert.ImplicitStandardConversionExists (ec, expr, ctype))
1596 Error_TypeMustBeConvertible (expr.Type, ctype, ptype);
1600 bool HasDefaultConstructor (EmitContext ec, Type atype)
1602 atype = TypeManager.DropGenericTypeArguments (atype);
1604 if (atype is TypeBuilder) {
1605 if (atype.IsAbstract)
1608 TypeContainer tc = TypeManager.LookupTypeContainer (atype);
1609 foreach (Constructor c in tc.InstanceConstructors) {
1610 if ((c.ModFlags & Modifiers.PUBLIC) == 0)
1612 if ((c.Parameters.FixedParameters != null) &&
1613 (c.Parameters.FixedParameters.Length != 0))
1615 if (c.Parameters.HasArglist || c.Parameters.HasParams)
1622 MethodGroupExpr mg = Expression.MemberLookup (
1623 ec, atype, ".ctor", MemberTypes.Constructor,
1624 BindingFlags.Public | BindingFlags.Instance |
1625 BindingFlags.DeclaredOnly, loc)
1628 if (!atype.IsAbstract && (mg != null) && mg.IsInstance) {
1629 foreach (MethodBase mb in mg.Methods) {
1630 ParameterData pd = TypeManager.GetParameterData (mb);
1639 protected abstract string GetSignatureForError ();
1640 protected abstract void Report_SymbolRelatedToPreviousError ();
1642 void Error_TypeMustBeConvertible (Type atype, Type gc, Type ptype)
1644 Report_SymbolRelatedToPreviousError ();
1645 Report.SymbolRelatedToPreviousError (atype);
1646 Report.Error (309, loc,
1647 "The type `{0}' must be convertible to `{1}' in order to " +
1648 "use it as parameter `{2}' in the generic type or method `{3}'",
1649 TypeManager.CSharpName (atype), TypeManager.CSharpName (gc),
1650 TypeManager.CSharpName (ptype), GetSignatureForError ());
1653 public static bool CheckConstraints (EmitContext ec, MethodBase definition,
1654 MethodBase instantiated, Location loc)
1656 MethodConstraintChecker checker = new MethodConstraintChecker (
1657 definition, definition.GetGenericArguments (),
1658 instantiated.GetGenericArguments (), loc);
1660 return checker.CheckConstraints (ec);
1663 public static bool CheckConstraints (EmitContext ec, Type gt, Type[] gen_params,
1664 Type[] atypes, Location loc)
1666 TypeConstraintChecker checker = new TypeConstraintChecker (
1667 gt, gen_params, atypes, loc);
1669 return checker.CheckConstraints (ec);
1672 protected class MethodConstraintChecker : ConstraintChecker
1674 MethodBase definition;
1676 public MethodConstraintChecker (MethodBase definition, Type[] gen_params,
1677 Type[] atypes, Location loc)
1678 : base (gen_params, atypes, loc)
1680 this.definition = definition;
1683 protected override string GetSignatureForError ()
1685 return TypeManager.CSharpSignature (definition);
1688 protected override void Report_SymbolRelatedToPreviousError ()
1690 Report.SymbolRelatedToPreviousError (definition);
1694 protected class TypeConstraintChecker : ConstraintChecker
1698 public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
1700 : base (gen_params, atypes, loc)
1705 protected override string GetSignatureForError ()
1707 return TypeManager.CSharpName (gt);
1710 protected override void Report_SymbolRelatedToPreviousError ()
1712 Report.SymbolRelatedToPreviousError (gt);
1718 /// A generic method definition.
1720 public class GenericMethod : DeclSpace
1722 Expression return_type;
1723 Parameters parameters;
1725 public GenericMethod (NamespaceEntry ns, TypeContainer parent, MemberName name,
1726 Expression return_type, Parameters parameters)
1727 : base (ns, parent, name, null)
1729 this.return_type = return_type;
1730 this.parameters = parameters;
1733 public override TypeBuilder DefineType ()
1735 throw new Exception ();
1738 public override bool Define ()
1740 ec = new EmitContext (this, this, Location, null, null, ModFlags, false);
1742 for (int i = 0; i < TypeParameters.Length; i++)
1743 if (!TypeParameters [i].Resolve (this))
1750 /// Define and resolve the type parameters.
1751 /// We're called from Method.Define().
1753 public bool Define (MethodBuilder mb)
1755 GenericTypeParameterBuilder[] gen_params;
1756 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1757 string[] snames = new string [names.Length];
1758 for (int i = 0; i < names.Length; i++)
1759 snames [i] = names [i].Name;
1760 gen_params = mb.DefineGenericParameters (snames);
1761 for (int i = 0; i < TypeParameters.Length; i++)
1762 TypeParameters [i].Define (gen_params [i]);
1767 for (int i = 0; i < TypeParameters.Length; i++) {
1768 if (!TypeParameters [i].ResolveType (ec))
1776 /// We're called from MethodData.Define() after creating the MethodBuilder.
1778 public bool DefineType (EmitContext ec, MethodBuilder mb,
1779 MethodInfo implementing, bool is_override)
1781 for (int i = 0; i < TypeParameters.Length; i++)
1782 if (!TypeParameters [i].DefineType (
1783 ec, mb, implementing, is_override))
1787 foreach (Parameter p in parameters.FixedParameters){
1788 if (!p.Resolve (ec))
1791 if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec) == null))
1797 public void EmitAttributes (EmitContext ec)
1799 for (int i = 0; i < TypeParameters.Length; i++)
1800 TypeParameters [i].EmitAttributes (ec);
1802 if (OptAttributes != null)
1803 OptAttributes.Emit (ec, this);
1806 public override bool DefineMembers ()
1811 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1812 MemberFilter filter, object criteria)
1814 throw new Exception ();
1817 public override MemberCache MemberCache {
1823 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1825 base.ApplyAttributeBuilder (a, cb);
1828 public override AttributeTargets AttributeTargets {
1830 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1834 public override string DocCommentHeader {
1835 get { return "M:"; }
1839 public class DefaultValueExpression : Expression
1843 public DefaultValueExpression (Expression expr, Location loc)
1849 public override Expression DoResolve (EmitContext ec)
1851 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
1857 eclass = ExprClass.Variable;
1861 public override void Emit (EmitContext ec)
1863 if (type.IsGenericParameter || TypeManager.IsValueType (type)) {
1864 LocalTemporary temp_storage = new LocalTemporary (ec, type);
1866 temp_storage.AddressOf (ec, AddressOp.LoadStore);
1867 ec.ig.Emit (OpCodes.Initobj, type);
1868 temp_storage.Emit (ec);
1870 ec.ig.Emit (OpCodes.Ldnull);
1874 public class NullableType : TypeExpr
1876 Expression underlying;
1878 public NullableType (Expression underlying, Location l)
1880 this.underlying = underlying;
1883 eclass = ExprClass.Type;
1886 public NullableType (Type type, Location loc)
1887 : this (new TypeExpression (type, loc), loc)
1890 public override string Name {
1891 get { return underlying.ToString () + "?"; }
1894 public override string FullName {
1895 get { return underlying.ToString () + "?"; }
1898 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
1900 TypeArguments args = new TypeArguments (loc);
1901 args.Add (underlying);
1903 ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
1904 return ctype.ResolveAsTypeTerminal (ec);
1908 public partial class TypeManager
1911 // A list of core types that the compiler requires or uses
1913 static public Type activator_type;
1914 static public Type generic_ienumerator_type;
1915 static public Type generic_ienumerable_type;
1916 static public Type generic_nullable_type;
1919 // Tracks the generic parameters.
1921 static PtrHashtable builder_to_type_param;
1924 // These methods are called by code generated by the compiler
1926 static public MethodInfo activator_create_instance;
1928 static void InitGenerics ()
1930 builder_to_type_param = new PtrHashtable ();
1933 static void CleanUpGenerics ()
1935 builder_to_type_param = null;
1938 static void InitGenericCoreTypes ()
1940 activator_type = CoreLookupType ("System", "Activator");
1942 generic_ienumerator_type = CoreLookupType (
1943 "System.Collections.Generic", "IEnumerator", 1);
1944 generic_ienumerable_type = CoreLookupType (
1945 "System.Collections.Generic", "IEnumerable", 1);
1946 generic_nullable_type = CoreLookupType (
1947 "System", "Nullable", 1);
1950 static void InitGenericCodeHelpers ()
1953 Type [] type_arg = { type_type };
1954 activator_create_instance = GetMethod (
1955 activator_type, "CreateInstance", type_arg);
1958 static Type CoreLookupType (string ns, string name, int arity)
1960 return CoreLookupType (ns, MemberName.MakeName (name, arity));
1963 public static void AddTypeParameter (Type t, TypeParameter tparam)
1965 if (!builder_to_type_param.Contains (t))
1966 builder_to_type_param.Add (t, tparam);
1969 public static TypeContainer LookupGenericTypeContainer (Type t)
1971 t = DropGenericTypeArguments (t);
1972 return LookupTypeContainer (t);
1975 public static TypeParameter LookupTypeParameter (Type t)
1977 return (TypeParameter) builder_to_type_param [t];
1980 public static GenericConstraints GetTypeParameterConstraints (Type t)
1982 if (!t.IsGenericParameter)
1983 throw new InvalidOperationException ();
1985 TypeParameter tparam = LookupTypeParameter (t);
1987 return tparam.GenericConstraints;
1989 return ReflectionConstraints.GetConstraints (t);
1992 public static bool HasGenericArguments (Type t)
1994 return GetNumberOfTypeArguments (t) > 0;
1997 public static int GetNumberOfTypeArguments (Type t)
1999 if (t.IsGenericParameter)
2001 DeclSpace tc = LookupDeclSpace (t);
2003 return tc.IsGeneric ? tc.CountTypeParameters : 0;
2005 return t.IsGenericType ? t.GetGenericArguments ().Length : 0;
2008 public static Type[] GetTypeArguments (Type t)
2010 DeclSpace tc = LookupDeclSpace (t);
2013 return Type.EmptyTypes;
2015 TypeParameter[] tparam = tc.TypeParameters;
2016 Type[] ret = new Type [tparam.Length];
2017 for (int i = 0; i < tparam.Length; i++) {
2018 ret [i] = tparam [i].Type;
2019 if (ret [i] == null)
2020 throw new InternalErrorException ();
2025 return t.GetGenericArguments ();
2028 public static Type DropGenericTypeArguments (Type t)
2030 if (!t.IsGenericType)
2032 // Micro-optimization: a generic typebuilder is always a generic type definition
2033 if (t is TypeBuilder)
2035 return t.GetGenericTypeDefinition ();
2038 public static MethodBase DropGenericMethodArguments (MethodBase m)
2040 if (m.IsGenericMethodDefinition)
2042 if (m.IsGenericMethod)
2043 return ((MethodInfo) m).GetGenericMethodDefinition ();
2044 if (!m.DeclaringType.IsGenericType)
2047 Type t = m.DeclaringType.GetGenericTypeDefinition ();
2048 BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
2049 BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
2051 if (m is ConstructorInfo) {
2052 foreach (ConstructorInfo c in t.GetConstructors (bf))
2053 if (c.MetadataToken == m.MetadataToken)
2056 foreach (MethodBase mb in t.GetMethods (bf))
2057 if (mb.MetadataToken == m.MetadataToken)
2064 public static FieldInfo GetGenericFieldDefinition (FieldInfo fi)
2066 if (fi.DeclaringType.IsGenericTypeDefinition ||
2067 !fi.DeclaringType.IsGenericType)
2070 Type t = fi.DeclaringType.GetGenericTypeDefinition ();
2071 BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
2072 BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
2074 foreach (FieldInfo f in t.GetFields (bf))
2075 if (f.MetadataToken == fi.MetadataToken)
2082 // Whether `array' is an array of T and `enumerator' is `IEnumerable<T>'.
2083 // For instance "string[]" -> "IEnumerable<string>".
2085 public static bool IsIEnumerable (Type array, Type enumerator)
2087 if (!array.IsArray || !enumerator.IsGenericType)
2090 if (enumerator.GetGenericTypeDefinition () != generic_ienumerable_type)
2093 Type[] args = GetTypeArguments (enumerator);
2094 return args [0] == GetElementType (array);
2097 public static bool IsEqual (Type a, Type b)
2102 if (a.IsGenericParameter && b.IsGenericParameter) {
2103 if (a.DeclaringMethod != b.DeclaringMethod &&
2104 (a.DeclaringMethod == null || b.DeclaringMethod == null))
2106 return a.GenericParameterPosition == b.GenericParameterPosition;
2109 if (a.IsArray && b.IsArray) {
2110 if (a.GetArrayRank () != b.GetArrayRank ())
2112 return IsEqual (a.GetElementType (), b.GetElementType ());
2115 if (a.IsByRef && b.IsByRef)
2116 return IsEqual (a.GetElementType (), b.GetElementType ());
2118 if (a.IsGenericType && b.IsGenericType) {
2119 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2122 Type[] aargs = a.GetGenericArguments ();
2123 Type[] bargs = b.GetGenericArguments ();
2125 if (aargs.Length != bargs.Length)
2128 for (int i = 0; i < aargs.Length; i++) {
2129 if (!IsEqual (aargs [i], bargs [i]))
2137 // This is to build with the broken circular dependencies between
2138 // System and System.Configuration in the 2.x profile where we
2139 // end up with a situation where:
2141 // System on the second build is referencing the System.Configuration
2142 // that has references to the first System build.
2144 // Point in case: NameValueCollection built on the first pass, vs
2145 // NameValueCollection build on the second one. The problem is that
2146 // we need to override some methods sometimes, or we need to
2148 if (RootContext.BrokenCircularDeps){
2149 if (a.Name == b.Name && a.Namespace == b.Namespace){
2150 Console.WriteLine ("GonziMatch: {0}.{1}", a.Namespace, a.Name);
2158 /// Check whether `a' and `b' may become equal generic types.
2159 /// The algorithm to do that is a little bit complicated.
2161 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_infered,
2162 Type[] method_infered)
2164 if (a.IsGenericParameter) {
2166 // If a is an array of a's type, they may never
2170 b = b.GetElementType ();
2176 // If b is a generic parameter or an actual type,
2177 // they may become equal:
2179 // class X<T,U> : I<T>, I<U>
2180 // class X<T> : I<T>, I<float>
2182 if (b.IsGenericParameter || !b.IsGenericType) {
2183 int pos = a.GenericParameterPosition;
2184 Type[] args = a.DeclaringMethod != null ? method_infered : class_infered;
2185 if (args [pos] == null) {
2190 return args [pos] == a;
2194 // We're now comparing a type parameter with a
2195 // generic instance. They may become equal unless
2196 // the type parameter appears anywhere in the
2197 // generic instance:
2199 // class X<T,U> : I<T>, I<X<U>>
2200 // -> error because you could instanciate it as
2203 // class X<T> : I<T>, I<X<T>> -> ok
2206 Type[] bargs = GetTypeArguments (b);
2207 for (int i = 0; i < bargs.Length; i++) {
2208 if (a.Equals (bargs [i]))
2215 if (b.IsGenericParameter)
2216 return MayBecomeEqualGenericTypes (b, a, class_infered, method_infered);
2219 // At this point, neither a nor b are a type parameter.
2221 // If one of them is a generic instance, let
2222 // MayBecomeEqualGenericInstances() compare them (if the
2223 // other one is not a generic instance, they can never
2227 if (a.IsGenericType || b.IsGenericType)
2228 return MayBecomeEqualGenericInstances (a, b, class_infered, method_infered);
2231 // If both of them are arrays.
2234 if (a.IsArray && b.IsArray) {
2235 if (a.GetArrayRank () != b.GetArrayRank ())
2238 a = a.GetElementType ();
2239 b = b.GetElementType ();
2241 return MayBecomeEqualGenericTypes (a, b, class_infered, method_infered);
2245 // Ok, two ordinary types.
2248 return a.Equals (b);
2252 // Checks whether two generic instances may become equal for some
2253 // particular instantiation (26.3.1).
2255 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
2256 Type[] class_infered,
2257 Type[] method_infered)
2259 if (!a.IsGenericType || !b.IsGenericType)
2261 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2264 return MayBecomeEqualGenericInstances (
2265 GetTypeArguments (a), GetTypeArguments (b), class_infered, method_infered);
2268 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
2269 Type[] class_infered,
2270 Type[] method_infered)
2272 if (aargs.Length != bargs.Length)
2275 for (int i = 0; i < aargs.Length; i++) {
2276 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_infered, method_infered))
2284 /// Check whether `type' and `parent' are both instantiations of the same
2285 /// generic type. Note that we do not check the type parameters here.
2287 public static bool IsInstantiationOfSameGenericType (Type type, Type parent)
2289 int tcount = GetNumberOfTypeArguments (type);
2290 int pcount = GetNumberOfTypeArguments (parent);
2292 if (tcount != pcount)
2295 type = DropGenericTypeArguments (type);
2296 parent = DropGenericTypeArguments (parent);
2298 return type.Equals (parent);
2302 /// Whether `mb' is a generic method definition.
2304 public static bool IsGenericMethodDefinition (MethodBase mb)
2306 if (mb.DeclaringType is TypeBuilder) {
2307 IMethodData method = (IMethodData) builder_to_method [mb];
2311 return method.GenericMethod != null;
2314 return mb.IsGenericMethodDefinition;
2318 /// Whether `mb' is a generic method definition.
2320 public static bool IsGenericMethod (MethodBase mb)
2322 if (mb.DeclaringType is TypeBuilder) {
2323 IMethodData method = (IMethodData) builder_to_method [mb];
2327 return method.GenericMethod != null;
2330 return mb.IsGenericMethod;
2337 static bool InferType (Type pt, Type at, Type[] infered)
2342 if (pt.IsGenericParameter) {
2343 if (pt.DeclaringMethod == null)
2346 int pos = pt.GenericParameterPosition;
2348 if (infered [pos] == null) {
2350 while (check.IsArray)
2351 check = check.GetElementType ();
2360 if (infered [pos] != at)
2366 if (!pt.ContainsGenericParameters) {
2367 if (at.ContainsGenericParameters)
2368 return InferType (at, pt, infered);
2375 if (at.GetArrayRank () != pt.GetArrayRank ())
2378 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2381 if (!pt.IsGenericType ||
2382 (pt.GetGenericTypeDefinition () != generic_ienumerable_type))
2385 Type[] args = GetTypeArguments (pt);
2386 return InferType (args [0], at.GetElementType (), infered);
2391 (pt.GetArrayRank () != at.GetArrayRank ()))
2394 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2397 if (pt.IsByRef && at.IsByRef)
2398 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2399 ArrayList list = new ArrayList ();
2400 if (at.IsGenericType)
2402 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
2405 list.AddRange (TypeManager.GetInterfaces (at));
2407 bool found_one = false;
2409 foreach (Type type in list) {
2410 if (!type.IsGenericType)
2413 Type[] infered_types = new Type [infered.Length];
2415 if (!InferGenericInstance (pt, type, infered_types))
2418 for (int i = 0; i < infered_types.Length; i++) {
2419 if (infered [i] == null) {
2420 infered [i] = infered_types [i];
2424 if (infered [i] != infered_types [i])
2434 static bool InferGenericInstance (Type pt, Type at, Type[] infered_types)
2436 Type[] at_args = at.GetGenericArguments ();
2437 Type[] pt_args = pt.GetGenericArguments ();
2439 if (at_args.Length != pt_args.Length)
2442 for (int i = 0; i < at_args.Length; i++) {
2443 if (!InferType (pt_args [i], at_args [i], infered_types))
2447 for (int i = 0; i < infered_types.Length; i++) {
2448 if (infered_types [i] == null)
2456 /// Type inference. Try to infer the type arguments from the params method
2457 /// `method', which is invoked with the arguments `arguments'. This is used
2458 /// when resolving an Invocation or a DelegateInvocation and the user
2459 /// did not explicitly specify type arguments.
2461 public static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
2462 ref MethodBase method)
2464 if ((arguments == null) || !TypeManager.IsGenericMethod (method))
2469 if (arguments == null)
2472 arg_count = arguments.Count;
2474 ParameterData pd = TypeManager.GetParameterData (method);
2476 int pd_count = pd.Count;
2481 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2484 if (pd_count - 1 > arg_count)
2487 if (pd_count == 1 && arg_count == 0)
2490 Type[] method_args = method.GetGenericArguments ();
2491 Type[] infered_types = new Type [method_args.Length];
2494 // If we have come this far, the case which
2495 // remains is when the number of parameters is
2496 // less than or equal to the argument count.
2498 for (int i = 0; i < pd_count - 1; ++i) {
2499 Argument a = (Argument) arguments [i];
2501 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2504 Type pt = pd.ParameterType (i);
2507 if (!InferType (pt, at, infered_types))
2511 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
2513 for (int i = pd_count - 1; i < arg_count; i++) {
2514 Argument a = (Argument) arguments [i];
2516 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2519 if (!InferType (element_type, a.Type, infered_types))
2523 for (int i = 0; i < infered_types.Length; i++)
2524 if (infered_types [i] == null)
2527 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2531 static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
2532 Type[] infered_types)
2534 if (infered_types == null)
2537 for (int i = 0; i < arg_types.Length; i++) {
2538 if (arg_types [i] == null)
2541 if (!InferType (param_types [i], arg_types [i], infered_types))
2545 for (int i = 0; i < infered_types.Length; i++)
2546 if (infered_types [i] == null)
2553 /// Type inference. Try to infer the type arguments from `method',
2554 /// which is invoked with the arguments `arguments'. This is used
2555 /// when resolving an Invocation or a DelegateInvocation and the user
2556 /// did not explicitly specify type arguments.
2558 public static bool InferTypeArguments (EmitContext ec, ArrayList arguments,
2559 ref MethodBase method)
2561 if (!TypeManager.IsGenericMethod (method))
2565 if (arguments != null)
2566 arg_count = arguments.Count;
2570 ParameterData pd = TypeManager.GetParameterData (method);
2571 if (arg_count != pd.Count)
2574 Type[] method_args = method.GetGenericArguments ();
2576 bool is_open = false;
2577 for (int i = 0; i < method_args.Length; i++) {
2578 if (method_args [i].IsGenericParameter) {
2586 Type[] infered_types = new Type [method_args.Length];
2588 Type[] param_types = new Type [pd.Count];
2589 Type[] arg_types = new Type [pd.Count];
2591 for (int i = 0; i < arg_count; i++) {
2592 param_types [i] = pd.ParameterType (i);
2594 Argument a = (Argument) arguments [i];
2595 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr) ||
2596 (a.Expr is AnonymousMethod))
2599 arg_types [i] = a.Type;
2602 if (!InferTypeArguments (param_types, arg_types, infered_types))
2605 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2612 public static bool InferTypeArguments (EmitContext ec, ParameterData apd,
2613 ref MethodBase method)
2615 if (!TypeManager.IsGenericMethod (method))
2618 ParameterData pd = TypeManager.GetParameterData (method);
2619 if (apd.Count != pd.Count)
2622 Type[] method_args = method.GetGenericArguments ();
2623 Type[] infered_types = new Type [method_args.Length];
2625 Type[] param_types = new Type [pd.Count];
2626 Type[] arg_types = new Type [pd.Count];
2628 for (int i = 0; i < apd.Count; i++) {
2629 param_types [i] = pd.ParameterType (i);
2630 arg_types [i] = apd.ParameterType (i);
2633 if (!InferTypeArguments (param_types, arg_types, infered_types))
2636 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2640 public static bool IsNullableType (Type t)
2642 return generic_nullable_type == DropGenericTypeArguments (t);
2646 public abstract class Nullable
2648 protected sealed class NullableInfo
2650 public readonly Type Type;
2651 public readonly Type UnderlyingType;
2652 public readonly MethodInfo HasValue;
2653 public readonly MethodInfo Value;
2654 public readonly ConstructorInfo Constructor;
2656 public NullableInfo (Type type)
2659 UnderlyingType = TypeManager.GetTypeArguments (type) [0];
2661 PropertyInfo has_value_pi = TypeManager.GetProperty (type, "HasValue");
2662 PropertyInfo value_pi = TypeManager.GetProperty (type, "Value");
2664 HasValue = has_value_pi.GetGetMethod (false);
2665 Value = value_pi.GetGetMethod (false);
2666 Constructor = type.GetConstructor (new Type[] { UnderlyingType });
2670 protected class Unwrap : Expression, IMemoryLocation, IAssignMethod
2675 LocalTemporary temp;
2678 public Unwrap (Expression expr, Location loc)
2684 public override Expression DoResolve (EmitContext ec)
2686 expr = expr.Resolve (ec);
2690 temp = new LocalTemporary (ec, expr.Type);
2692 info = new NullableInfo (expr.Type);
2693 type = info.UnderlyingType;
2694 eclass = expr.eclass;
2698 public override void Emit (EmitContext ec)
2700 AddressOf (ec, AddressOp.LoadStore);
2701 ec.ig.EmitCall (OpCodes.Call, info.Value, null);
2704 public void EmitCheck (EmitContext ec)
2706 AddressOf (ec, AddressOp.LoadStore);
2707 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
2710 public void Store (EmitContext ec)
2715 void create_temp (EmitContext ec)
2717 if ((temp != null) && !has_temp) {
2724 public void AddressOf (EmitContext ec, AddressOp mode)
2728 temp.AddressOf (ec, AddressOp.LoadStore);
2730 ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
2733 public void Emit (EmitContext ec, bool leave_copy)
2746 public void EmitAssign (EmitContext ec, Expression source,
2747 bool leave_copy, bool prepare_for_load)
2749 InternalWrap wrap = new InternalWrap (source, info, loc);
2750 ((IAssignMethod) expr).EmitAssign (ec, wrap, leave_copy, false);
2753 protected class InternalWrap : Expression
2755 public Expression expr;
2756 public NullableInfo info;
2758 public InternalWrap (Expression expr, NullableInfo info, Location loc)
2765 eclass = ExprClass.Value;
2768 public override Expression DoResolve (EmitContext ec)
2773 public override void Emit (EmitContext ec)
2776 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2781 protected class Wrap : Expression
2786 public Wrap (Expression expr, Location loc)
2792 public override Expression DoResolve (EmitContext ec)
2794 expr = expr.Resolve (ec);
2798 TypeExpr target_type = new NullableType (expr.Type, loc);
2799 target_type = target_type.ResolveAsTypeTerminal (ec);
2800 if (target_type == null)
2803 type = target_type.Type;
2804 info = new NullableInfo (type);
2805 eclass = ExprClass.Value;
2809 public override void Emit (EmitContext ec)
2812 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2816 public class NullableLiteral : Expression, IMemoryLocation {
2817 public NullableLiteral (Type target_type, Location loc)
2819 this.type = target_type;
2822 eclass = ExprClass.Value;
2825 public override Expression DoResolve (EmitContext ec)
2830 public override void Emit (EmitContext ec)
2832 LocalTemporary value_target = new LocalTemporary (ec, type);
2834 value_target.AddressOf (ec, AddressOp.Store);
2835 ec.ig.Emit (OpCodes.Initobj, type);
2836 value_target.Emit (ec);
2839 public void AddressOf (EmitContext ec, AddressOp Mode)
2841 LocalTemporary value_target = new LocalTemporary (ec, type);
2843 value_target.AddressOf (ec, AddressOp.Store);
2844 ec.ig.Emit (OpCodes.Initobj, type);
2845 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
2849 public abstract class Lifted : Expression, IMemoryLocation
2851 Expression expr, underlying, wrap, null_value;
2854 protected Lifted (Expression expr, Location loc)
2860 public override Expression DoResolve (EmitContext ec)
2862 expr = expr.Resolve (ec);
2866 unwrap = (Unwrap) new Unwrap (expr, loc).Resolve (ec);
2870 underlying = ResolveUnderlying (unwrap, ec);
2871 if (underlying == null)
2874 wrap = new Wrap (underlying, loc).Resolve (ec);
2878 null_value = new NullableLiteral (wrap.Type, loc).Resolve (ec);
2879 if (null_value == null)
2883 eclass = ExprClass.Value;
2887 protected abstract Expression ResolveUnderlying (Expression unwrap, EmitContext ec);
2889 public override void Emit (EmitContext ec)
2891 ILGenerator ig = ec.ig;
2892 Label is_null_label = ig.DefineLabel ();
2893 Label end_label = ig.DefineLabel ();
2895 unwrap.EmitCheck (ec);
2896 ig.Emit (OpCodes.Brfalse, is_null_label);
2899 ig.Emit (OpCodes.Br, end_label);
2901 ig.MarkLabel (is_null_label);
2902 null_value.Emit (ec);
2904 ig.MarkLabel (end_label);
2907 public void AddressOf (EmitContext ec, AddressOp mode)
2909 unwrap.AddressOf (ec, mode);
2913 public class LiftedConversion : Lifted
2915 public readonly bool IsUser;
2916 public readonly bool IsExplicit;
2917 public readonly Type TargetType;
2919 public LiftedConversion (Expression expr, Type target_type, bool is_user,
2920 bool is_explicit, Location loc)
2923 this.IsUser = is_user;
2924 this.IsExplicit = is_explicit;
2925 this.TargetType = target_type;
2928 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2930 Type type = TypeManager.GetTypeArguments (TargetType) [0];
2933 return Convert.UserDefinedConversion (ec, unwrap, type, loc, IsExplicit);
2936 return Convert.ExplicitConversion (ec, unwrap, type, loc);
2938 return Convert.ImplicitConversion (ec, unwrap, type, loc);
2943 public class LiftedUnaryOperator : Lifted
2945 public readonly Unary.Operator Oper;
2947 public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
2953 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2955 return new Unary (Oper, unwrap, loc);
2959 public class LiftedConditional : Lifted
2961 Expression true_expr, false_expr;
2963 public LiftedConditional (Expression expr, Expression true_expr, Expression false_expr,
2967 this.true_expr = true_expr;
2968 this.false_expr = false_expr;
2971 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2973 return new Conditional (unwrap, true_expr, false_expr);
2977 public class LiftedBinaryOperator : Expression
2979 public readonly Binary.Operator Oper;
2981 Expression left, right, original_left, original_right;
2982 Expression underlying, null_value, bool_wrap;
2983 Unwrap left_unwrap, right_unwrap;
2984 bool is_equality, is_comparision, is_boolean;
2986 public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
2990 this.left = original_left = left;
2991 this.right = original_right = right;
2995 public override Expression DoResolve (EmitContext ec)
2997 if (TypeManager.IsNullableType (left.Type)) {
2998 left_unwrap = new Unwrap (left, loc);
2999 left = left_unwrap.Resolve (ec);
3004 if (TypeManager.IsNullableType (right.Type)) {
3005 right_unwrap = new Unwrap (right, loc);
3006 right = right_unwrap.Resolve (ec);
3011 if ((Oper == Binary.Operator.LogicalAnd) ||
3012 (Oper == Binary.Operator.LogicalOr)) {
3013 Binary.Error_OperatorCannotBeApplied (
3014 loc, Binary.OperName (Oper),
3015 original_left.GetSignatureForError (),
3016 original_right.GetSignatureForError ());
3020 if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr)) &&
3021 ((left.Type == TypeManager.bool_type) && (right.Type == TypeManager.bool_type))) {
3022 Expression empty = new EmptyExpression (TypeManager.bool_type);
3023 bool_wrap = new Wrap (empty, loc).Resolve (ec);
3024 null_value = new NullableLiteral (bool_wrap.Type, loc).Resolve (ec);
3026 type = bool_wrap.Type;
3028 } else if ((Oper == Binary.Operator.Equality) || (Oper == Binary.Operator.Inequality)) {
3029 if (!(left is NullLiteral) && !(right is NullLiteral)) {
3030 underlying = new Binary (Oper, left, right).Resolve (ec);
3031 if (underlying == null)
3035 type = TypeManager.bool_type;
3037 } else if ((Oper == Binary.Operator.LessThan) ||
3038 (Oper == Binary.Operator.GreaterThan) ||
3039 (Oper == Binary.Operator.LessThanOrEqual) ||
3040 (Oper == Binary.Operator.GreaterThanOrEqual)) {
3041 underlying = new Binary (Oper, left, right).Resolve (ec);
3042 if (underlying == null)
3045 type = TypeManager.bool_type;
3046 is_comparision = true;
3048 underlying = new Binary (Oper, left, right).Resolve (ec);
3049 if (underlying == null)
3052 underlying = new Wrap (underlying, loc).Resolve (ec);
3053 if (underlying == null)
3056 type = underlying.Type;
3057 null_value = new NullableLiteral (type, loc).Resolve (ec);
3060 eclass = ExprClass.Value;
3064 void EmitBoolean (EmitContext ec)
3066 ILGenerator ig = ec.ig;
3068 Label left_is_null_label = ig.DefineLabel ();
3069 Label right_is_null_label = ig.DefineLabel ();
3070 Label is_null_label = ig.DefineLabel ();
3071 Label wrap_label = ig.DefineLabel ();
3072 Label end_label = ig.DefineLabel ();
3074 if (left_unwrap != null) {
3075 left_unwrap.EmitCheck (ec);
3076 ig.Emit (OpCodes.Brfalse, left_is_null_label);
3080 ig.Emit (OpCodes.Dup);
3081 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3082 ig.Emit (OpCodes.Brtrue, wrap_label);
3084 ig.Emit (OpCodes.Brfalse, wrap_label);
3086 if (right_unwrap != null) {
3087 right_unwrap.EmitCheck (ec);
3088 ig.Emit (OpCodes.Brfalse, right_is_null_label);
3091 if ((Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr))
3092 ig.Emit (OpCodes.Pop);
3095 if (Oper == Binary.Operator.BitwiseOr)
3096 ig.Emit (OpCodes.Or);
3097 else if (Oper == Binary.Operator.BitwiseAnd)
3098 ig.Emit (OpCodes.And);
3099 ig.Emit (OpCodes.Br, wrap_label);
3101 ig.MarkLabel (left_is_null_label);
3102 if (right_unwrap != null) {
3103 right_unwrap.EmitCheck (ec);
3104 ig.Emit (OpCodes.Brfalse, is_null_label);
3108 ig.Emit (OpCodes.Dup);
3109 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3110 ig.Emit (OpCodes.Brtrue, wrap_label);
3112 ig.Emit (OpCodes.Brfalse, wrap_label);
3114 ig.MarkLabel (right_is_null_label);
3115 ig.Emit (OpCodes.Pop);
3116 ig.MarkLabel (is_null_label);
3117 null_value.Emit (ec);
3118 ig.Emit (OpCodes.Br, end_label);
3120 ig.MarkLabel (wrap_label);
3121 ig.Emit (OpCodes.Nop);
3122 bool_wrap.Emit (ec);
3123 ig.Emit (OpCodes.Nop);
3125 ig.MarkLabel (end_label);
3128 void EmitEquality (EmitContext ec)
3130 ILGenerator ig = ec.ig;
3132 Label left_not_null_label = ig.DefineLabel ();
3133 Label false_label = ig.DefineLabel ();
3134 Label true_label = ig.DefineLabel ();
3135 Label end_label = ig.DefineLabel ();
3137 bool false_label_used = false;
3138 bool true_label_used = false;
3140 if (left_unwrap != null) {
3141 left_unwrap.EmitCheck (ec);
3142 if (right is NullLiteral) {
3143 if (Oper == Binary.Operator.Equality) {
3144 true_label_used = true;
3145 ig.Emit (OpCodes.Brfalse, true_label);
3147 false_label_used = true;
3148 ig.Emit (OpCodes.Brfalse, false_label);
3150 } else if (right_unwrap != null) {
3151 ig.Emit (OpCodes.Dup);
3152 ig.Emit (OpCodes.Brtrue, left_not_null_label);
3153 right_unwrap.EmitCheck (ec);
3154 ig.Emit (OpCodes.Ceq);
3155 if (Oper == Binary.Operator.Inequality) {
3156 ig.Emit (OpCodes.Ldc_I4_0);
3157 ig.Emit (OpCodes.Ceq);
3159 ig.Emit (OpCodes.Br, end_label);
3161 ig.MarkLabel (left_not_null_label);
3162 ig.Emit (OpCodes.Pop);
3164 if (Oper == Binary.Operator.Equality) {
3165 false_label_used = true;
3166 ig.Emit (OpCodes.Brfalse, false_label);
3168 true_label_used = true;
3169 ig.Emit (OpCodes.Brfalse, true_label);
3174 if (right_unwrap != null) {
3175 right_unwrap.EmitCheck (ec);
3176 if (left is NullLiteral) {
3177 if (Oper == Binary.Operator.Equality) {
3178 true_label_used = true;
3179 ig.Emit (OpCodes.Brfalse, true_label);
3181 false_label_used = true;
3182 ig.Emit (OpCodes.Brfalse, false_label);
3185 if (Oper == Binary.Operator.Equality) {
3186 false_label_used = true;
3187 ig.Emit (OpCodes.Brfalse, false_label);
3189 true_label_used = true;
3190 ig.Emit (OpCodes.Brfalse, true_label);
3195 bool left_is_null = left is NullLiteral;
3196 bool right_is_null = right is NullLiteral;
3197 if (left_is_null || right_is_null) {
3198 if (((Oper == Binary.Operator.Equality) && (left_is_null == right_is_null)) ||
3199 ((Oper == Binary.Operator.Inequality) && (left_is_null != right_is_null))) {
3200 true_label_used = true;
3201 ig.Emit (OpCodes.Br, true_label);
3203 false_label_used = true;
3204 ig.Emit (OpCodes.Br, false_label);
3207 underlying.Emit (ec);
3208 ig.Emit (OpCodes.Br, end_label);
3211 ig.MarkLabel (false_label);
3212 if (false_label_used) {
3213 ig.Emit (OpCodes.Ldc_I4_0);
3214 if (true_label_used)
3215 ig.Emit (OpCodes.Br, end_label);
3218 ig.MarkLabel (true_label);
3219 if (true_label_used)
3220 ig.Emit (OpCodes.Ldc_I4_1);
3222 ig.MarkLabel (end_label);
3225 void EmitComparision (EmitContext ec)
3227 ILGenerator ig = ec.ig;
3229 Label is_null_label = ig.DefineLabel ();
3230 Label end_label = ig.DefineLabel ();
3232 if (left_unwrap != null) {
3233 left_unwrap.EmitCheck (ec);
3234 ig.Emit (OpCodes.Brfalse, is_null_label);
3237 if (right_unwrap != null) {
3238 right_unwrap.EmitCheck (ec);
3239 ig.Emit (OpCodes.Brfalse, is_null_label);
3242 underlying.Emit (ec);
3243 ig.Emit (OpCodes.Br, end_label);
3245 ig.MarkLabel (is_null_label);
3246 ig.Emit (OpCodes.Ldc_I4_0);
3248 ig.MarkLabel (end_label);
3251 public override void Emit (EmitContext ec)
3253 if (left_unwrap != null)
3254 left_unwrap.Store (ec);
3255 if (right_unwrap != null)
3256 right_unwrap.Store (ec);
3261 } else if (is_equality) {
3264 } else if (is_comparision) {
3265 EmitComparision (ec);
3269 ILGenerator ig = ec.ig;
3271 Label is_null_label = ig.DefineLabel ();
3272 Label end_label = ig.DefineLabel ();
3274 if (left_unwrap != null) {
3275 left_unwrap.EmitCheck (ec);
3276 ig.Emit (OpCodes.Brfalse, is_null_label);
3279 if (right_unwrap != null) {
3280 right_unwrap.EmitCheck (ec);
3281 ig.Emit (OpCodes.Brfalse, is_null_label);
3284 underlying.Emit (ec);
3285 ig.Emit (OpCodes.Br, end_label);
3287 ig.MarkLabel (is_null_label);
3288 null_value.Emit (ec);
3290 ig.MarkLabel (end_label);
3294 public class OperatorTrueOrFalse : Expression
3296 public readonly bool IsTrue;
3301 public OperatorTrueOrFalse (Expression expr, bool is_true, Location loc)
3303 this.IsTrue = is_true;
3308 public override Expression DoResolve (EmitContext ec)
3310 unwrap = new Unwrap (expr, loc);
3311 expr = unwrap.Resolve (ec);
3315 if (unwrap.Type != TypeManager.bool_type)
3318 type = TypeManager.bool_type;
3319 eclass = ExprClass.Value;
3323 public override void Emit (EmitContext ec)
3325 ILGenerator ig = ec.ig;
3327 Label is_null_label = ig.DefineLabel ();
3328 Label end_label = ig.DefineLabel ();
3330 unwrap.EmitCheck (ec);
3331 ig.Emit (OpCodes.Brfalse, is_null_label);
3335 ig.Emit (OpCodes.Ldc_I4_0);
3336 ig.Emit (OpCodes.Ceq);
3338 ig.Emit (OpCodes.Br, end_label);
3340 ig.MarkLabel (is_null_label);
3341 ig.Emit (OpCodes.Ldc_I4_0);
3343 ig.MarkLabel (end_label);
3347 public class NullCoalescingOperator : Expression
3349 Expression left, right;
3353 public NullCoalescingOperator (Expression left, Expression right, Location loc)
3359 eclass = ExprClass.Value;
3362 public override Expression DoResolve (EmitContext ec)
3367 left = left.Resolve (ec);
3371 right = right.Resolve (ec);
3375 Type ltype = left.Type, rtype = right.Type;
3377 if (!TypeManager.IsNullableType (ltype) && ltype.IsValueType) {
3378 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3382 if (TypeManager.IsNullableType (ltype)) {
3383 NullableInfo info = new NullableInfo (ltype);
3385 unwrap = (Unwrap) new Unwrap (left, loc).Resolve (ec);
3389 expr = Convert.ImplicitConversion (ec, right, info.UnderlyingType, loc);
3397 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
3403 if (unwrap != null) {
3404 expr = Convert.ImplicitConversion (ec, unwrap, rtype, loc);
3413 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3417 public override void Emit (EmitContext ec)
3419 ILGenerator ig = ec.ig;
3421 Label is_null_label = ig.DefineLabel ();
3422 Label end_label = ig.DefineLabel ();
3424 if (unwrap != null) {
3425 unwrap.EmitCheck (ec);
3426 ig.Emit (OpCodes.Brfalse, is_null_label);
3429 ig.Emit (OpCodes.Br, end_label);
3431 ig.MarkLabel (is_null_label);
3434 ig.MarkLabel (end_label);
3437 ig.Emit (OpCodes.Dup);
3438 ig.Emit (OpCodes.Brtrue, end_label);
3440 ig.MarkLabel (is_null_label);
3442 ig.Emit (OpCodes.Pop);
3445 ig.MarkLabel (end_label);
3450 public class LiftedUnaryMutator : ExpressionStatement
3452 public readonly UnaryMutator.Mode Mode;
3453 Expression expr, null_value;
3454 UnaryMutator underlying;
3457 public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
3463 eclass = ExprClass.Value;
3466 public override Expression DoResolve (EmitContext ec)
3468 expr = expr.Resolve (ec);
3472 unwrap = (Unwrap) new Unwrap (expr, loc).Resolve (ec);
3476 underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
3477 if (underlying == null)
3480 null_value = new NullableLiteral (expr.Type, loc).Resolve (ec);
3481 if (null_value == null)
3488 void DoEmit (EmitContext ec, bool is_expr)
3490 ILGenerator ig = ec.ig;
3491 Label is_null_label = ig.DefineLabel ();
3492 Label end_label = ig.DefineLabel ();
3494 unwrap.EmitCheck (ec);
3495 ig.Emit (OpCodes.Brfalse, is_null_label);
3498 underlying.Emit (ec);
3500 underlying.EmitStatement (ec);
3501 ig.Emit (OpCodes.Br, end_label);
3503 ig.MarkLabel (is_null_label);
3505 null_value.Emit (ec);
3507 ig.MarkLabel (end_label);
3510 public override void Emit (EmitContext ec)
3515 public override void EmitStatement (EmitContext ec)