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 (IResolveContext 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, false);
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, false);
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 (e1, t2) &&
446 !Convert.ImplicitReferenceConversionExists (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)) {
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 ()
804 if (OptAttributes != null)
805 OptAttributes.Emit ();
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 (IResolveContext 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 (IResolveContext 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, false);
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 (IResolveContext 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 (IResolveContext 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 (IResolveContext 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 (IResolveContext 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 (IResolveContext ec)
1466 for (int i = 0; i < gen_params.Length; i++) {
1467 if (!CheckConstraints (ec, i))
1474 protected bool CheckConstraints (IResolveContext 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 if (agc is Constraints)
1493 ((Constraints) agc).Resolve (ec);
1494 is_class = agc.HasReferenceTypeConstraint;
1495 is_struct = agc.HasValueTypeConstraint;
1497 is_class = is_struct = false;
1502 if (!atype.IsGenericType)
1504 is_class = atype.IsClass || atype.IsInterface;
1505 is_struct = atype.IsValueType && !TypeManager.IsNullableType (atype);
1509 // First, check the `class' and `struct' constraints.
1511 if (gc.HasReferenceTypeConstraint && !is_class) {
1512 Report.Error (452, loc, "The type `{0}' must be " +
1513 "a reference type in order to use it " +
1514 "as type parameter `{1}' in the " +
1515 "generic type or method `{2}'.",
1516 TypeManager.CSharpName (atype),
1517 TypeManager.CSharpName (ptype),
1518 GetSignatureForError ());
1520 } else if (gc.HasValueTypeConstraint && !is_struct) {
1521 Report.Error (453, loc, "The type `{0}' must be a " +
1522 "non-nullable value type in order to use it " +
1523 "as type parameter `{1}' in the " +
1524 "generic type or method `{2}'.",
1525 TypeManager.CSharpName (atype),
1526 TypeManager.CSharpName (ptype),
1527 GetSignatureForError ());
1532 // The class constraint comes next.
1534 if (gc.HasClassConstraint) {
1535 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint))
1540 // Now, check the interface constraints.
1542 if (gc.InterfaceConstraints != null) {
1543 foreach (Type it in gc.InterfaceConstraints) {
1544 if (!CheckConstraint (ec, ptype, aexpr, it))
1550 // Finally, check the constructor constraint.
1553 if (!gc.HasConstructorConstraint)
1556 if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
1559 if (HasDefaultConstructor (ec.DeclContainer.TypeBuilder, atype))
1562 Report_SymbolRelatedToPreviousError ();
1563 Report.SymbolRelatedToPreviousError (atype);
1564 Report.Error (310, loc, "The type `{0}' must have a public " +
1565 "parameterless constructor in order to use it " +
1566 "as parameter `{1}' in the generic type or " +
1568 TypeManager.CSharpName (atype),
1569 TypeManager.CSharpName (ptype),
1570 GetSignatureForError ());
1574 protected bool CheckConstraint (IResolveContext ec, Type ptype, Expression expr,
1577 if (TypeManager.HasGenericArguments (ctype)) {
1578 Type[] types = TypeManager.GetTypeArguments (ctype);
1580 TypeArguments new_args = new TypeArguments (loc);
1582 for (int i = 0; i < types.Length; i++) {
1585 if (t.IsGenericParameter) {
1586 int pos = t.GenericParameterPosition;
1589 new_args.Add (new TypeExpression (t, loc));
1592 TypeExpr ct = new ConstructedType (ctype, new_args, loc);
1593 if (ct.ResolveAsTypeStep (ec, false) == null)
1596 } else if (ctype.IsGenericParameter) {
1597 int pos = ctype.GenericParameterPosition;
1598 ctype = atypes [pos];
1601 if (Convert.ImplicitStandardConversionExists (expr, ctype))
1604 Error_TypeMustBeConvertible (expr.Type, ctype, ptype);
1608 bool HasDefaultConstructor (Type containerType, Type atype)
1610 if (atype.IsAbstract)
1614 atype = TypeManager.DropGenericTypeArguments (atype);
1615 if (atype is TypeBuilder) {
1616 TypeContainer tc = TypeManager.LookupTypeContainer (atype);
1617 if (tc.InstanceConstructors == null) {
1618 atype = atype.BaseType;
1622 foreach (Constructor c in tc.InstanceConstructors) {
1623 if ((c.ModFlags & Modifiers.PUBLIC) == 0)
1625 if ((c.Parameters.FixedParameters != null) &&
1626 (c.Parameters.FixedParameters.Length != 0))
1628 if (c.Parameters.HasArglist || c.Parameters.HasParams)
1635 MethodGroupExpr mg = Expression.MemberLookup (
1636 containerType, atype, ".ctor", MemberTypes.Constructor,
1637 BindingFlags.Public | BindingFlags.Instance |
1638 BindingFlags.DeclaredOnly, loc)
1641 if (!atype.IsAbstract && (mg != null) && mg.IsInstance) {
1642 foreach (MethodBase mb in mg.Methods) {
1643 ParameterData pd = TypeManager.GetParameterData (mb);
1652 protected abstract string GetSignatureForError ();
1653 protected abstract void Report_SymbolRelatedToPreviousError ();
1655 void Error_TypeMustBeConvertible (Type atype, Type gc, Type ptype)
1657 Report_SymbolRelatedToPreviousError ();
1658 Report.SymbolRelatedToPreviousError (atype);
1659 Report.Error (309, loc,
1660 "The type `{0}' must be convertible to `{1}' in order to " +
1661 "use it as parameter `{2}' in the generic type or method `{3}'",
1662 TypeManager.CSharpName (atype), TypeManager.CSharpName (gc),
1663 TypeManager.CSharpName (ptype), GetSignatureForError ());
1666 public static bool CheckConstraints (EmitContext ec, MethodBase definition,
1667 MethodBase instantiated, Location loc)
1669 MethodConstraintChecker checker = new MethodConstraintChecker (
1670 definition, definition.GetGenericArguments (),
1671 instantiated.GetGenericArguments (), loc);
1673 return checker.CheckConstraints (ec);
1676 public static bool CheckConstraints (IResolveContext ec, Type gt, Type[] gen_params,
1677 Type[] atypes, Location loc)
1679 TypeConstraintChecker checker = new TypeConstraintChecker (
1680 gt, gen_params, atypes, loc);
1682 return checker.CheckConstraints (ec);
1685 protected class MethodConstraintChecker : ConstraintChecker
1687 MethodBase definition;
1689 public MethodConstraintChecker (MethodBase definition, Type[] gen_params,
1690 Type[] atypes, Location loc)
1691 : base (gen_params, atypes, loc)
1693 this.definition = definition;
1696 protected override string GetSignatureForError ()
1698 return TypeManager.CSharpSignature (definition);
1701 protected override void Report_SymbolRelatedToPreviousError ()
1703 Report.SymbolRelatedToPreviousError (definition);
1707 protected class TypeConstraintChecker : ConstraintChecker
1711 public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
1713 : base (gen_params, atypes, loc)
1718 protected override string GetSignatureForError ()
1720 return TypeManager.CSharpName (gt);
1723 protected override void Report_SymbolRelatedToPreviousError ()
1725 Report.SymbolRelatedToPreviousError (gt);
1731 /// A generic method definition.
1733 public class GenericMethod : DeclSpace
1735 Expression return_type;
1736 Parameters parameters;
1738 public GenericMethod (NamespaceEntry ns, TypeContainer parent, MemberName name,
1739 Expression return_type, Parameters parameters)
1740 : base (ns, parent, name, null)
1742 this.return_type = return_type;
1743 this.parameters = parameters;
1746 public override TypeBuilder DefineType ()
1748 throw new Exception ();
1751 public override bool Define ()
1753 ec = new EmitContext (this, this, this, Location, null, null, ModFlags, false);
1755 for (int i = 0; i < TypeParameters.Length; i++)
1756 if (!TypeParameters [i].Resolve (this))
1763 /// Define and resolve the type parameters.
1764 /// We're called from Method.Define().
1766 public bool Define (MethodBuilder mb)
1768 GenericTypeParameterBuilder[] gen_params;
1769 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1770 string[] snames = new string [names.Length];
1771 for (int i = 0; i < names.Length; i++)
1772 snames [i] = names [i].Name;
1773 gen_params = mb.DefineGenericParameters (snames);
1774 for (int i = 0; i < TypeParameters.Length; i++)
1775 TypeParameters [i].Define (gen_params [i]);
1780 for (int i = 0; i < TypeParameters.Length; i++) {
1781 if (!TypeParameters [i].ResolveType (ec))
1789 /// We're called from MethodData.Define() after creating the MethodBuilder.
1791 public bool DefineType (EmitContext ec, MethodBuilder mb,
1792 MethodInfo implementing, bool is_override)
1794 for (int i = 0; i < TypeParameters.Length; i++)
1795 if (!TypeParameters [i].DefineType (
1796 ec, mb, implementing, is_override))
1800 foreach (Parameter p in parameters.FixedParameters){
1801 if (!p.Resolve (ec))
1804 if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec, false) == null))
1810 public void EmitAttributes ()
1812 for (int i = 0; i < TypeParameters.Length; i++)
1813 TypeParameters [i].EmitAttributes ();
1815 if (OptAttributes != null)
1816 OptAttributes.Emit ();
1819 public override bool DefineMembers ()
1824 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1825 MemberFilter filter, object criteria)
1827 throw new Exception ();
1830 public override MemberCache MemberCache {
1836 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1838 base.ApplyAttributeBuilder (a, cb);
1841 public override AttributeTargets AttributeTargets {
1843 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1847 public override string DocCommentHeader {
1848 get { return "M:"; }
1852 public class DefaultValueExpression : Expression
1856 public DefaultValueExpression (Expression expr, Location loc)
1862 public override Expression DoResolve (EmitContext ec)
1864 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
1870 eclass = ExprClass.Variable;
1874 public override void Emit (EmitContext ec)
1876 if (type.IsGenericParameter || TypeManager.IsValueType (type)) {
1877 LocalTemporary temp_storage = new LocalTemporary (ec, type);
1879 temp_storage.AddressOf (ec, AddressOp.LoadStore);
1880 ec.ig.Emit (OpCodes.Initobj, type);
1881 temp_storage.Emit (ec);
1883 ec.ig.Emit (OpCodes.Ldnull);
1887 public class NullableType : TypeExpr
1889 Expression underlying;
1891 public NullableType (Expression underlying, Location l)
1893 this.underlying = underlying;
1896 eclass = ExprClass.Type;
1899 public NullableType (Type type, Location loc)
1900 : this (new TypeExpression (type, loc), loc)
1903 public override string Name {
1904 get { return underlying.ToString () + "?"; }
1907 public override string FullName {
1908 get { return underlying.ToString () + "?"; }
1911 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1913 TypeArguments args = new TypeArguments (loc);
1914 args.Add (underlying);
1916 ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
1917 return ctype.ResolveAsTypeTerminal (ec, false);
1921 public partial class TypeManager
1924 // A list of core types that the compiler requires or uses
1926 static public Type activator_type;
1927 static public Type generic_ienumerator_type;
1928 static public Type generic_ienumerable_type;
1929 static public Type generic_nullable_type;
1932 // Tracks the generic parameters.
1934 static PtrHashtable builder_to_type_param;
1937 // These methods are called by code generated by the compiler
1939 static public MethodInfo activator_create_instance;
1941 static void InitGenerics ()
1943 builder_to_type_param = new PtrHashtable ();
1946 static void CleanUpGenerics ()
1948 builder_to_type_param = null;
1951 static void InitGenericCoreTypes ()
1953 activator_type = CoreLookupType ("System", "Activator");
1955 generic_ienumerator_type = CoreLookupType (
1956 "System.Collections.Generic", "IEnumerator", 1);
1957 generic_ienumerable_type = CoreLookupType (
1958 "System.Collections.Generic", "IEnumerable", 1);
1959 generic_nullable_type = CoreLookupType (
1960 "System", "Nullable", 1);
1963 static void InitGenericCodeHelpers ()
1966 Type [] type_arg = { type_type };
1967 activator_create_instance = GetMethod (
1968 activator_type, "CreateInstance", type_arg);
1971 static Type CoreLookupType (string ns, string name, int arity)
1973 return CoreLookupType (ns, MemberName.MakeName (name, arity));
1976 public static void AddTypeParameter (Type t, TypeParameter tparam)
1978 if (!builder_to_type_param.Contains (t))
1979 builder_to_type_param.Add (t, tparam);
1982 public static TypeContainer LookupGenericTypeContainer (Type t)
1984 t = DropGenericTypeArguments (t);
1985 return LookupTypeContainer (t);
1988 public static TypeParameter LookupTypeParameter (Type t)
1990 return (TypeParameter) builder_to_type_param [t];
1993 public static GenericConstraints GetTypeParameterConstraints (Type t)
1995 if (!t.IsGenericParameter)
1996 throw new InvalidOperationException ();
1998 TypeParameter tparam = LookupTypeParameter (t);
2000 return tparam.GenericConstraints;
2002 return ReflectionConstraints.GetConstraints (t);
2005 public static bool HasGenericArguments (Type t)
2007 return GetNumberOfTypeArguments (t) > 0;
2010 public static int GetNumberOfTypeArguments (Type t)
2012 if (t.IsGenericParameter)
2014 DeclSpace tc = LookupDeclSpace (t);
2016 return tc.IsGeneric ? tc.CountTypeParameters : 0;
2018 return t.IsGenericType ? t.GetGenericArguments ().Length : 0;
2021 public static Type[] GetTypeArguments (Type t)
2023 DeclSpace tc = LookupDeclSpace (t);
2026 return Type.EmptyTypes;
2028 TypeParameter[] tparam = tc.TypeParameters;
2029 Type[] ret = new Type [tparam.Length];
2030 for (int i = 0; i < tparam.Length; i++) {
2031 ret [i] = tparam [i].Type;
2032 if (ret [i] == null)
2033 throw new InternalErrorException ();
2038 return t.GetGenericArguments ();
2041 public static Type DropGenericTypeArguments (Type t)
2043 if (!t.IsGenericType)
2045 // Micro-optimization: a generic typebuilder is always a generic type definition
2046 if (t is TypeBuilder)
2048 return t.GetGenericTypeDefinition ();
2051 public static MethodBase DropGenericMethodArguments (MethodBase m)
2053 if (m.IsGenericMethodDefinition)
2055 if (m.IsGenericMethod)
2056 return ((MethodInfo) m).GetGenericMethodDefinition ();
2057 if (!m.DeclaringType.IsGenericType)
2060 Type t = m.DeclaringType.GetGenericTypeDefinition ();
2061 BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
2062 BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
2064 if (m is ConstructorInfo) {
2065 foreach (ConstructorInfo c in t.GetConstructors (bf))
2066 if (c.MetadataToken == m.MetadataToken)
2069 foreach (MethodBase mb in t.GetMethods (bf))
2070 if (mb.MetadataToken == m.MetadataToken)
2077 public static FieldInfo GetGenericFieldDefinition (FieldInfo fi)
2079 if (fi.DeclaringType.IsGenericTypeDefinition ||
2080 !fi.DeclaringType.IsGenericType)
2083 Type t = fi.DeclaringType.GetGenericTypeDefinition ();
2084 BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
2085 BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
2087 foreach (FieldInfo f in t.GetFields (bf))
2088 if (f.MetadataToken == fi.MetadataToken)
2095 // Whether `array' is an array of T and `enumerator' is `IEnumerable<T>'.
2096 // For instance "string[]" -> "IEnumerable<string>".
2098 public static bool IsIEnumerable (Type array, Type enumerator)
2100 if (!array.IsArray || !enumerator.IsGenericType)
2103 if (enumerator.GetGenericTypeDefinition () != generic_ienumerable_type)
2106 Type[] args = GetTypeArguments (enumerator);
2107 return args [0] == GetElementType (array);
2110 public static bool IsEqual (Type a, Type b)
2115 if (a.IsGenericParameter && b.IsGenericParameter) {
2116 if (a.DeclaringMethod != b.DeclaringMethod &&
2117 (a.DeclaringMethod == null || b.DeclaringMethod == null))
2119 return a.GenericParameterPosition == b.GenericParameterPosition;
2122 if (a.IsArray && b.IsArray) {
2123 if (a.GetArrayRank () != b.GetArrayRank ())
2125 return IsEqual (a.GetElementType (), b.GetElementType ());
2128 if (a.IsByRef && b.IsByRef)
2129 return IsEqual (a.GetElementType (), b.GetElementType ());
2131 if (a.IsGenericType && b.IsGenericType) {
2132 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2135 Type[] aargs = a.GetGenericArguments ();
2136 Type[] bargs = b.GetGenericArguments ();
2138 if (aargs.Length != bargs.Length)
2141 for (int i = 0; i < aargs.Length; i++) {
2142 if (!IsEqual (aargs [i], bargs [i]))
2150 // This is to build with the broken circular dependencies between
2151 // System and System.Configuration in the 2.x profile where we
2152 // end up with a situation where:
2154 // System on the second build is referencing the System.Configuration
2155 // that has references to the first System build.
2157 // Point in case: NameValueCollection built on the first pass, vs
2158 // NameValueCollection build on the second one. The problem is that
2159 // we need to override some methods sometimes, or we need to
2161 if (RootContext.BrokenCircularDeps){
2162 if (a.Name == b.Name && a.Namespace == b.Namespace){
2163 Console.WriteLine ("GonziMatch: {0}.{1}", a.Namespace, a.Name);
2171 /// Check whether `a' and `b' may become equal generic types.
2172 /// The algorithm to do that is a little bit complicated.
2174 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_infered,
2175 Type[] method_infered)
2177 if (a.IsGenericParameter) {
2179 // If a is an array of a's type, they may never
2183 b = b.GetElementType ();
2189 // If b is a generic parameter or an actual type,
2190 // they may become equal:
2192 // class X<T,U> : I<T>, I<U>
2193 // class X<T> : I<T>, I<float>
2195 if (b.IsGenericParameter || !b.IsGenericType) {
2196 int pos = a.GenericParameterPosition;
2197 Type[] args = a.DeclaringMethod != null ? method_infered : class_infered;
2198 if (args [pos] == null) {
2203 return args [pos] == a;
2207 // We're now comparing a type parameter with a
2208 // generic instance. They may become equal unless
2209 // the type parameter appears anywhere in the
2210 // generic instance:
2212 // class X<T,U> : I<T>, I<X<U>>
2213 // -> error because you could instanciate it as
2216 // class X<T> : I<T>, I<X<T>> -> ok
2219 Type[] bargs = GetTypeArguments (b);
2220 for (int i = 0; i < bargs.Length; i++) {
2221 if (a.Equals (bargs [i]))
2228 if (b.IsGenericParameter)
2229 return MayBecomeEqualGenericTypes (b, a, class_infered, method_infered);
2232 // At this point, neither a nor b are a type parameter.
2234 // If one of them is a generic instance, let
2235 // MayBecomeEqualGenericInstances() compare them (if the
2236 // other one is not a generic instance, they can never
2240 if (a.IsGenericType || b.IsGenericType)
2241 return MayBecomeEqualGenericInstances (a, b, class_infered, method_infered);
2244 // If both of them are arrays.
2247 if (a.IsArray && b.IsArray) {
2248 if (a.GetArrayRank () != b.GetArrayRank ())
2251 a = a.GetElementType ();
2252 b = b.GetElementType ();
2254 return MayBecomeEqualGenericTypes (a, b, class_infered, method_infered);
2258 // Ok, two ordinary types.
2261 return a.Equals (b);
2265 // Checks whether two generic instances may become equal for some
2266 // particular instantiation (26.3.1).
2268 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
2269 Type[] class_infered,
2270 Type[] method_infered)
2272 if (!a.IsGenericType || !b.IsGenericType)
2274 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2277 return MayBecomeEqualGenericInstances (
2278 GetTypeArguments (a), GetTypeArguments (b), class_infered, method_infered);
2281 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
2282 Type[] class_infered,
2283 Type[] method_infered)
2285 if (aargs.Length != bargs.Length)
2288 for (int i = 0; i < aargs.Length; i++) {
2289 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_infered, method_infered))
2297 /// Check whether `type' and `parent' are both instantiations of the same
2298 /// generic type. Note that we do not check the type parameters here.
2300 public static bool IsInstantiationOfSameGenericType (Type type, Type parent)
2302 int tcount = GetNumberOfTypeArguments (type);
2303 int pcount = GetNumberOfTypeArguments (parent);
2305 if (tcount != pcount)
2308 type = DropGenericTypeArguments (type);
2309 parent = DropGenericTypeArguments (parent);
2311 return type.Equals (parent);
2315 /// Whether `mb' is a generic method definition.
2317 public static bool IsGenericMethodDefinition (MethodBase mb)
2319 if (mb.DeclaringType is TypeBuilder) {
2320 IMethodData method = (IMethodData) builder_to_method [mb];
2324 return method.GenericMethod != null;
2327 return mb.IsGenericMethodDefinition;
2331 /// Whether `mb' is a generic method definition.
2333 public static bool IsGenericMethod (MethodBase mb)
2335 if (mb.DeclaringType is TypeBuilder) {
2336 IMethodData method = (IMethodData) builder_to_method [mb];
2340 return method.GenericMethod != null;
2343 return mb.IsGenericMethod;
2350 static bool InferType (Type pt, Type at, Type[] infered)
2355 if (pt.IsGenericParameter) {
2356 if (pt.DeclaringMethod == null)
2359 int pos = pt.GenericParameterPosition;
2361 if (infered [pos] == null) {
2363 while (check.IsArray)
2364 check = check.GetElementType ();
2373 if (infered [pos] != at)
2379 if (!pt.ContainsGenericParameters) {
2380 if (at.ContainsGenericParameters)
2381 return InferType (at, pt, infered);
2388 if (at.GetArrayRank () != pt.GetArrayRank ())
2391 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2394 if (!pt.IsGenericType ||
2395 (pt.GetGenericTypeDefinition () != generic_ienumerable_type))
2398 Type[] args = GetTypeArguments (pt);
2399 return InferType (args [0], at.GetElementType (), infered);
2404 (pt.GetArrayRank () != at.GetArrayRank ()))
2407 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2410 if (pt.IsByRef && at.IsByRef)
2411 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2412 ArrayList list = new ArrayList ();
2413 if (at.IsGenericType)
2415 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
2418 list.AddRange (TypeManager.GetInterfaces (at));
2420 bool found_one = false;
2422 foreach (Type type in list) {
2423 if (!type.IsGenericType)
2426 Type[] infered_types = new Type [infered.Length];
2428 if (!InferGenericInstance (pt, type, infered_types))
2431 for (int i = 0; i < infered_types.Length; i++) {
2432 if (infered [i] == null) {
2433 infered [i] = infered_types [i];
2437 if (infered [i] != infered_types [i])
2447 static bool InferGenericInstance (Type pt, Type at, Type[] infered_types)
2449 Type[] at_args = at.GetGenericArguments ();
2450 Type[] pt_args = pt.GetGenericArguments ();
2452 if (at_args.Length != pt_args.Length)
2455 for (int i = 0; i < at_args.Length; i++) {
2456 if (!InferType (pt_args [i], at_args [i], infered_types))
2460 for (int i = 0; i < infered_types.Length; i++) {
2461 if (infered_types [i] == null)
2469 /// Type inference. Try to infer the type arguments from the params method
2470 /// `method', which is invoked with the arguments `arguments'. This is used
2471 /// when resolving an Invocation or a DelegateInvocation and the user
2472 /// did not explicitly specify type arguments.
2474 public static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
2475 ref MethodBase method)
2477 if ((arguments == null) || !TypeManager.IsGenericMethod (method))
2482 if (arguments == null)
2485 arg_count = arguments.Count;
2487 ParameterData pd = TypeManager.GetParameterData (method);
2489 int pd_count = pd.Count;
2494 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2497 if (pd_count - 1 > arg_count)
2500 if (pd_count == 1 && arg_count == 0)
2503 Type[] method_args = method.GetGenericArguments ();
2504 Type[] infered_types = new Type [method_args.Length];
2507 // If we have come this far, the case which
2508 // remains is when the number of parameters is
2509 // less than or equal to the argument count.
2511 for (int i = 0; i < pd_count - 1; ++i) {
2512 Argument a = (Argument) arguments [i];
2514 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2517 Type pt = pd.ParameterType (i);
2520 if (!InferType (pt, at, infered_types))
2524 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
2526 for (int i = pd_count - 1; i < arg_count; i++) {
2527 Argument a = (Argument) arguments [i];
2529 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2532 if (!InferType (element_type, a.Type, infered_types))
2536 for (int i = 0; i < infered_types.Length; i++)
2537 if (infered_types [i] == null)
2540 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2544 static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
2545 Type[] infered_types)
2547 if (infered_types == null)
2550 for (int i = 0; i < arg_types.Length; i++) {
2551 if (arg_types [i] == null)
2554 if (!InferType (param_types [i], arg_types [i], infered_types))
2558 for (int i = 0; i < infered_types.Length; i++)
2559 if (infered_types [i] == null)
2566 /// Type inference. Try to infer the type arguments from `method',
2567 /// which is invoked with the arguments `arguments'. This is used
2568 /// when resolving an Invocation or a DelegateInvocation and the user
2569 /// did not explicitly specify type arguments.
2571 public static bool InferTypeArguments (ArrayList arguments,
2572 ref MethodBase method)
2574 if (!TypeManager.IsGenericMethod (method))
2578 if (arguments != null)
2579 arg_count = arguments.Count;
2583 ParameterData pd = TypeManager.GetParameterData (method);
2584 if (arg_count != pd.Count)
2587 Type[] method_args = method.GetGenericArguments ();
2589 bool is_open = false;
2590 for (int i = 0; i < method_args.Length; i++) {
2591 if (method_args [i].IsGenericParameter) {
2599 Type[] infered_types = new Type [method_args.Length];
2601 Type[] param_types = new Type [pd.Count];
2602 Type[] arg_types = new Type [pd.Count];
2604 for (int i = 0; i < arg_count; i++) {
2605 param_types [i] = pd.ParameterType (i);
2607 Argument a = (Argument) arguments [i];
2608 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr) ||
2609 (a.Expr is AnonymousMethod))
2612 arg_types [i] = a.Type;
2615 if (!InferTypeArguments (param_types, arg_types, infered_types))
2618 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2625 public static bool InferTypeArguments (ParameterData apd,
2626 ref MethodBase method)
2628 if (!TypeManager.IsGenericMethod (method))
2631 ParameterData pd = TypeManager.GetParameterData (method);
2632 if (apd.Count != pd.Count)
2635 Type[] method_args = method.GetGenericArguments ();
2636 Type[] infered_types = new Type [method_args.Length];
2638 Type[] param_types = new Type [pd.Count];
2639 Type[] arg_types = new Type [pd.Count];
2641 for (int i = 0; i < apd.Count; i++) {
2642 param_types [i] = pd.ParameterType (i);
2643 arg_types [i] = apd.ParameterType (i);
2646 if (!InferTypeArguments (param_types, arg_types, infered_types))
2649 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2653 public static bool IsNullableType (Type t)
2655 return generic_nullable_type == DropGenericTypeArguments (t);
2658 public static bool IsNullableValueType (Type t)
2660 if (!IsNullableType (t))
2663 return GetTypeArguments (t) [0].IsValueType;
2667 public abstract class Nullable
2669 protected sealed class NullableInfo
2671 public readonly Type Type;
2672 public readonly Type UnderlyingType;
2673 public readonly MethodInfo HasValue;
2674 public readonly MethodInfo Value;
2675 public readonly ConstructorInfo Constructor;
2677 public NullableInfo (Type type)
2680 UnderlyingType = TypeManager.GetTypeArguments (type) [0];
2682 PropertyInfo has_value_pi = TypeManager.GetProperty (type, "HasValue");
2683 PropertyInfo value_pi = TypeManager.GetProperty (type, "Value");
2685 HasValue = has_value_pi.GetGetMethod (false);
2686 Value = value_pi.GetGetMethod (false);
2687 Constructor = type.GetConstructor (new Type[] { UnderlyingType });
2691 protected class Unwrap : Expression, IMemoryLocation, IAssignMethod
2696 LocalTemporary temp;
2699 public Unwrap (Expression expr, Location loc)
2705 public override Expression DoResolve (EmitContext ec)
2707 expr = expr.Resolve (ec);
2711 temp = new LocalTemporary (ec, expr.Type);
2713 info = new NullableInfo (expr.Type);
2714 type = info.UnderlyingType;
2715 eclass = expr.eclass;
2719 public override void Emit (EmitContext ec)
2721 AddressOf (ec, AddressOp.LoadStore);
2722 ec.ig.EmitCall (OpCodes.Call, info.Value, null);
2725 public void EmitCheck (EmitContext ec)
2727 AddressOf (ec, AddressOp.LoadStore);
2728 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
2731 public void Store (EmitContext ec)
2736 void create_temp (EmitContext ec)
2738 if ((temp != null) && !has_temp) {
2745 public void AddressOf (EmitContext ec, AddressOp mode)
2749 temp.AddressOf (ec, AddressOp.LoadStore);
2751 ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
2754 public void Emit (EmitContext ec, bool leave_copy)
2767 public void EmitAssign (EmitContext ec, Expression source,
2768 bool leave_copy, bool prepare_for_load)
2770 InternalWrap wrap = new InternalWrap (source, info, loc);
2771 ((IAssignMethod) expr).EmitAssign (ec, wrap, leave_copy, false);
2774 protected class InternalWrap : Expression
2776 public Expression expr;
2777 public NullableInfo info;
2779 public InternalWrap (Expression expr, NullableInfo info, Location loc)
2786 eclass = ExprClass.Value;
2789 public override Expression DoResolve (EmitContext ec)
2794 public override void Emit (EmitContext ec)
2797 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2802 protected class Wrap : Expression
2807 public Wrap (Expression expr, Location loc)
2813 public override Expression DoResolve (EmitContext ec)
2815 expr = expr.Resolve (ec);
2819 TypeExpr target_type = new NullableType (expr.Type, loc);
2820 target_type = target_type.ResolveAsTypeTerminal (ec, false);
2821 if (target_type == null)
2824 type = target_type.Type;
2825 info = new NullableInfo (type);
2826 eclass = ExprClass.Value;
2830 public override void Emit (EmitContext ec)
2833 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2837 public class NullableLiteral : Expression, IMemoryLocation {
2838 public NullableLiteral (Type target_type, Location loc)
2840 this.type = target_type;
2843 eclass = ExprClass.Value;
2846 public override Expression DoResolve (EmitContext ec)
2851 public override void Emit (EmitContext ec)
2853 LocalTemporary value_target = new LocalTemporary (ec, type);
2855 value_target.AddressOf (ec, AddressOp.Store);
2856 ec.ig.Emit (OpCodes.Initobj, type);
2857 value_target.Emit (ec);
2860 public void AddressOf (EmitContext ec, AddressOp Mode)
2862 LocalTemporary value_target = new LocalTemporary (ec, type);
2864 value_target.AddressOf (ec, AddressOp.Store);
2865 ec.ig.Emit (OpCodes.Initobj, type);
2866 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
2870 public abstract class Lifted : Expression, IMemoryLocation
2872 Expression expr, underlying, wrap, null_value;
2875 protected Lifted (Expression expr, Location loc)
2881 public override Expression DoResolve (EmitContext ec)
2883 expr = expr.Resolve (ec);
2887 unwrap = (Unwrap) new Unwrap (expr, loc).Resolve (ec);
2891 underlying = ResolveUnderlying (unwrap, ec);
2892 if (underlying == null)
2895 wrap = new Wrap (underlying, loc).Resolve (ec);
2899 null_value = new NullableLiteral (wrap.Type, loc).Resolve (ec);
2900 if (null_value == null)
2904 eclass = ExprClass.Value;
2908 protected abstract Expression ResolveUnderlying (Expression unwrap, EmitContext ec);
2910 public override void Emit (EmitContext ec)
2912 ILGenerator ig = ec.ig;
2913 Label is_null_label = ig.DefineLabel ();
2914 Label end_label = ig.DefineLabel ();
2916 unwrap.EmitCheck (ec);
2917 ig.Emit (OpCodes.Brfalse, is_null_label);
2920 ig.Emit (OpCodes.Br, end_label);
2922 ig.MarkLabel (is_null_label);
2923 null_value.Emit (ec);
2925 ig.MarkLabel (end_label);
2928 public void AddressOf (EmitContext ec, AddressOp mode)
2930 unwrap.AddressOf (ec, mode);
2934 public class LiftedConversion : Lifted
2936 public readonly bool IsUser;
2937 public readonly bool IsExplicit;
2938 public readonly Type TargetType;
2940 public LiftedConversion (Expression expr, Type target_type, bool is_user,
2941 bool is_explicit, Location loc)
2944 this.IsUser = is_user;
2945 this.IsExplicit = is_explicit;
2946 this.TargetType = target_type;
2949 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2951 Type type = TypeManager.GetTypeArguments (TargetType) [0];
2954 return Convert.UserDefinedConversion (ec, unwrap, type, loc, IsExplicit);
2957 return Convert.ExplicitConversion (ec, unwrap, type, loc);
2959 return Convert.ImplicitConversion (ec, unwrap, type, loc);
2964 public class LiftedUnaryOperator : Lifted
2966 public readonly Unary.Operator Oper;
2968 public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
2974 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2976 return new Unary (Oper, unwrap, loc);
2980 public class LiftedConditional : Lifted
2982 Expression true_expr, false_expr;
2984 public LiftedConditional (Expression expr, Expression true_expr, Expression false_expr,
2988 this.true_expr = true_expr;
2989 this.false_expr = false_expr;
2992 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2994 return new Conditional (unwrap, true_expr, false_expr);
2998 public class LiftedBinaryOperator : Expression
3000 public readonly Binary.Operator Oper;
3002 Expression left, right, original_left, original_right;
3003 Expression underlying, null_value, bool_wrap;
3004 Unwrap left_unwrap, right_unwrap;
3005 bool is_equality, is_comparision, is_boolean;
3007 public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
3011 this.left = original_left = left;
3012 this.right = original_right = right;
3016 public override Expression DoResolve (EmitContext ec)
3018 if (TypeManager.IsNullableType (left.Type)) {
3019 left_unwrap = new Unwrap (left, loc);
3020 left = left_unwrap.Resolve (ec);
3025 if (TypeManager.IsNullableType (right.Type)) {
3026 right_unwrap = new Unwrap (right, loc);
3027 right = right_unwrap.Resolve (ec);
3032 if ((Oper == Binary.Operator.LogicalAnd) ||
3033 (Oper == Binary.Operator.LogicalOr)) {
3034 Binary.Error_OperatorCannotBeApplied (
3035 loc, Binary.OperName (Oper),
3036 original_left.GetSignatureForError (),
3037 original_right.GetSignatureForError ());
3041 if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr)) &&
3042 ((left.Type == TypeManager.bool_type) && (right.Type == TypeManager.bool_type))) {
3043 Expression empty = new EmptyExpression (TypeManager.bool_type);
3044 bool_wrap = new Wrap (empty, loc).Resolve (ec);
3045 null_value = new NullableLiteral (bool_wrap.Type, loc).Resolve (ec);
3047 type = bool_wrap.Type;
3049 } else if ((Oper == Binary.Operator.Equality) || (Oper == Binary.Operator.Inequality)) {
3050 if (!(left is NullLiteral) && !(right is NullLiteral)) {
3051 underlying = new Binary (Oper, left, right).Resolve (ec);
3052 if (underlying == null)
3056 type = TypeManager.bool_type;
3058 } else if ((Oper == Binary.Operator.LessThan) ||
3059 (Oper == Binary.Operator.GreaterThan) ||
3060 (Oper == Binary.Operator.LessThanOrEqual) ||
3061 (Oper == Binary.Operator.GreaterThanOrEqual)) {
3062 underlying = new Binary (Oper, left, right).Resolve (ec);
3063 if (underlying == null)
3066 type = TypeManager.bool_type;
3067 is_comparision = true;
3069 underlying = new Binary (Oper, left, right).Resolve (ec);
3070 if (underlying == null)
3073 underlying = new Wrap (underlying, loc).Resolve (ec);
3074 if (underlying == null)
3077 type = underlying.Type;
3078 null_value = new NullableLiteral (type, loc).Resolve (ec);
3081 eclass = ExprClass.Value;
3085 void EmitBoolean (EmitContext ec)
3087 ILGenerator ig = ec.ig;
3089 Label left_is_null_label = ig.DefineLabel ();
3090 Label right_is_null_label = ig.DefineLabel ();
3091 Label is_null_label = ig.DefineLabel ();
3092 Label wrap_label = ig.DefineLabel ();
3093 Label end_label = ig.DefineLabel ();
3095 if (left_unwrap != null) {
3096 left_unwrap.EmitCheck (ec);
3097 ig.Emit (OpCodes.Brfalse, left_is_null_label);
3101 ig.Emit (OpCodes.Dup);
3102 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3103 ig.Emit (OpCodes.Brtrue, wrap_label);
3105 ig.Emit (OpCodes.Brfalse, wrap_label);
3107 if (right_unwrap != null) {
3108 right_unwrap.EmitCheck (ec);
3109 ig.Emit (OpCodes.Brfalse, right_is_null_label);
3112 if ((Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr))
3113 ig.Emit (OpCodes.Pop);
3116 if (Oper == Binary.Operator.BitwiseOr)
3117 ig.Emit (OpCodes.Or);
3118 else if (Oper == Binary.Operator.BitwiseAnd)
3119 ig.Emit (OpCodes.And);
3120 ig.Emit (OpCodes.Br, wrap_label);
3122 ig.MarkLabel (left_is_null_label);
3123 if (right_unwrap != null) {
3124 right_unwrap.EmitCheck (ec);
3125 ig.Emit (OpCodes.Brfalse, is_null_label);
3129 ig.Emit (OpCodes.Dup);
3130 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3131 ig.Emit (OpCodes.Brtrue, wrap_label);
3133 ig.Emit (OpCodes.Brfalse, wrap_label);
3135 ig.MarkLabel (right_is_null_label);
3136 ig.Emit (OpCodes.Pop);
3137 ig.MarkLabel (is_null_label);
3138 null_value.Emit (ec);
3139 ig.Emit (OpCodes.Br, end_label);
3141 ig.MarkLabel (wrap_label);
3142 ig.Emit (OpCodes.Nop);
3143 bool_wrap.Emit (ec);
3144 ig.Emit (OpCodes.Nop);
3146 ig.MarkLabel (end_label);
3149 void EmitEquality (EmitContext ec)
3151 ILGenerator ig = ec.ig;
3153 Label left_not_null_label = ig.DefineLabel ();
3154 Label false_label = ig.DefineLabel ();
3155 Label true_label = ig.DefineLabel ();
3156 Label end_label = ig.DefineLabel ();
3158 bool false_label_used = false;
3159 bool true_label_used = false;
3161 if (left_unwrap != null) {
3162 left_unwrap.EmitCheck (ec);
3163 if (right is NullLiteral) {
3164 if (Oper == Binary.Operator.Equality) {
3165 true_label_used = true;
3166 ig.Emit (OpCodes.Brfalse, true_label);
3168 false_label_used = true;
3169 ig.Emit (OpCodes.Brfalse, false_label);
3171 } else if (right_unwrap != null) {
3172 ig.Emit (OpCodes.Dup);
3173 ig.Emit (OpCodes.Brtrue, left_not_null_label);
3174 right_unwrap.EmitCheck (ec);
3175 ig.Emit (OpCodes.Ceq);
3176 if (Oper == Binary.Operator.Inequality) {
3177 ig.Emit (OpCodes.Ldc_I4_0);
3178 ig.Emit (OpCodes.Ceq);
3180 ig.Emit (OpCodes.Br, end_label);
3182 ig.MarkLabel (left_not_null_label);
3183 ig.Emit (OpCodes.Pop);
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 if (right_unwrap != null) {
3196 right_unwrap.EmitCheck (ec);
3197 if (left is NullLiteral) {
3198 if (Oper == Binary.Operator.Equality) {
3199 true_label_used = true;
3200 ig.Emit (OpCodes.Brfalse, true_label);
3202 false_label_used = true;
3203 ig.Emit (OpCodes.Brfalse, false_label);
3206 if (Oper == Binary.Operator.Equality) {
3207 false_label_used = true;
3208 ig.Emit (OpCodes.Brfalse, false_label);
3210 true_label_used = true;
3211 ig.Emit (OpCodes.Brfalse, true_label);
3216 bool left_is_null = left is NullLiteral;
3217 bool right_is_null = right is NullLiteral;
3218 if (left_is_null || right_is_null) {
3219 if (((Oper == Binary.Operator.Equality) && (left_is_null == right_is_null)) ||
3220 ((Oper == Binary.Operator.Inequality) && (left_is_null != right_is_null))) {
3221 true_label_used = true;
3222 ig.Emit (OpCodes.Br, true_label);
3224 false_label_used = true;
3225 ig.Emit (OpCodes.Br, false_label);
3228 underlying.Emit (ec);
3229 ig.Emit (OpCodes.Br, end_label);
3232 ig.MarkLabel (false_label);
3233 if (false_label_used) {
3234 ig.Emit (OpCodes.Ldc_I4_0);
3235 if (true_label_used)
3236 ig.Emit (OpCodes.Br, end_label);
3239 ig.MarkLabel (true_label);
3240 if (true_label_used)
3241 ig.Emit (OpCodes.Ldc_I4_1);
3243 ig.MarkLabel (end_label);
3246 void EmitComparision (EmitContext ec)
3248 ILGenerator ig = ec.ig;
3250 Label is_null_label = ig.DefineLabel ();
3251 Label end_label = ig.DefineLabel ();
3253 if (left_unwrap != null) {
3254 left_unwrap.EmitCheck (ec);
3255 ig.Emit (OpCodes.Brfalse, is_null_label);
3258 if (right_unwrap != null) {
3259 right_unwrap.EmitCheck (ec);
3260 ig.Emit (OpCodes.Brfalse, is_null_label);
3263 underlying.Emit (ec);
3264 ig.Emit (OpCodes.Br, end_label);
3266 ig.MarkLabel (is_null_label);
3267 ig.Emit (OpCodes.Ldc_I4_0);
3269 ig.MarkLabel (end_label);
3272 public override void Emit (EmitContext ec)
3274 if (left_unwrap != null)
3275 left_unwrap.Store (ec);
3276 if (right_unwrap != null)
3277 right_unwrap.Store (ec);
3282 } else if (is_equality) {
3285 } else if (is_comparision) {
3286 EmitComparision (ec);
3290 ILGenerator ig = ec.ig;
3292 Label is_null_label = ig.DefineLabel ();
3293 Label end_label = ig.DefineLabel ();
3295 if (left_unwrap != null) {
3296 left_unwrap.EmitCheck (ec);
3297 ig.Emit (OpCodes.Brfalse, is_null_label);
3300 if (right_unwrap != null) {
3301 right_unwrap.EmitCheck (ec);
3302 ig.Emit (OpCodes.Brfalse, is_null_label);
3305 underlying.Emit (ec);
3306 ig.Emit (OpCodes.Br, end_label);
3308 ig.MarkLabel (is_null_label);
3309 null_value.Emit (ec);
3311 ig.MarkLabel (end_label);
3315 public class OperatorTrueOrFalse : Expression
3317 public readonly bool IsTrue;
3322 public OperatorTrueOrFalse (Expression expr, bool is_true, Location loc)
3324 this.IsTrue = is_true;
3329 public override Expression DoResolve (EmitContext ec)
3331 unwrap = new Unwrap (expr, loc);
3332 expr = unwrap.Resolve (ec);
3336 if (unwrap.Type != TypeManager.bool_type)
3339 type = TypeManager.bool_type;
3340 eclass = ExprClass.Value;
3344 public override void Emit (EmitContext ec)
3346 ILGenerator ig = ec.ig;
3348 Label is_null_label = ig.DefineLabel ();
3349 Label end_label = ig.DefineLabel ();
3351 unwrap.EmitCheck (ec);
3352 ig.Emit (OpCodes.Brfalse, is_null_label);
3356 ig.Emit (OpCodes.Ldc_I4_0);
3357 ig.Emit (OpCodes.Ceq);
3359 ig.Emit (OpCodes.Br, end_label);
3361 ig.MarkLabel (is_null_label);
3362 ig.Emit (OpCodes.Ldc_I4_0);
3364 ig.MarkLabel (end_label);
3368 public class NullCoalescingOperator : Expression
3370 Expression left, right;
3374 public NullCoalescingOperator (Expression left, Expression right, Location loc)
3380 eclass = ExprClass.Value;
3383 public override Expression DoResolve (EmitContext ec)
3388 left = left.Resolve (ec);
3392 right = right.Resolve (ec);
3396 Type ltype = left.Type, rtype = right.Type;
3398 if (!TypeManager.IsNullableType (ltype) && ltype.IsValueType) {
3399 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3403 if (TypeManager.IsNullableType (ltype)) {
3404 NullableInfo info = new NullableInfo (ltype);
3406 unwrap = (Unwrap) new Unwrap (left, loc).Resolve (ec);
3410 expr = Convert.ImplicitConversion (ec, right, info.UnderlyingType, loc);
3418 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
3424 if (unwrap != null) {
3425 expr = Convert.ImplicitConversion (ec, unwrap, rtype, loc);
3434 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3438 public override void Emit (EmitContext ec)
3440 ILGenerator ig = ec.ig;
3442 Label is_null_label = ig.DefineLabel ();
3443 Label end_label = ig.DefineLabel ();
3445 if (unwrap != null) {
3446 unwrap.EmitCheck (ec);
3447 ig.Emit (OpCodes.Brfalse, is_null_label);
3450 ig.Emit (OpCodes.Br, end_label);
3452 ig.MarkLabel (is_null_label);
3455 ig.MarkLabel (end_label);
3458 ig.Emit (OpCodes.Dup);
3459 ig.Emit (OpCodes.Brtrue, end_label);
3461 ig.MarkLabel (is_null_label);
3463 ig.Emit (OpCodes.Pop);
3466 ig.MarkLabel (end_label);
3471 public class LiftedUnaryMutator : ExpressionStatement
3473 public readonly UnaryMutator.Mode Mode;
3474 Expression expr, null_value;
3475 UnaryMutator underlying;
3478 public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
3484 eclass = ExprClass.Value;
3487 public override Expression DoResolve (EmitContext ec)
3489 expr = expr.Resolve (ec);
3493 unwrap = (Unwrap) new Unwrap (expr, loc).Resolve (ec);
3497 underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
3498 if (underlying == null)
3501 null_value = new NullableLiteral (expr.Type, loc).Resolve (ec);
3502 if (null_value == null)
3509 void DoEmit (EmitContext ec, bool is_expr)
3511 ILGenerator ig = ec.ig;
3512 Label is_null_label = ig.DefineLabel ();
3513 Label end_label = ig.DefineLabel ();
3515 unwrap.EmitCheck (ec);
3516 ig.Emit (OpCodes.Brfalse, is_null_label);
3519 underlying.Emit (ec);
3521 underlying.EmitStatement (ec);
3522 ig.Emit (OpCodes.Br, end_label);
3524 ig.MarkLabel (is_null_label);
3526 null_value.Emit (ec);
3528 ig.MarkLabel (end_label);
3531 public override void Emit (EmitContext ec)
3536 public override void EmitStatement (EmitContext ec)