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 {
157 public Constraints Clone ()
159 return new Constraints (name, constraints, loc);
162 GenericParameterAttributes attrs;
163 TypeExpr class_constraint;
164 ArrayList iface_constraints;
165 ArrayList type_param_constraints;
167 Type class_constraint_type;
168 Type[] iface_constraint_types;
169 Type effective_base_type;
174 /// Resolve the constraints - but only resolve things into Expression's, not
175 /// into actual types.
177 public bool Resolve (IResolveContext ec)
182 iface_constraints = new ArrayList ();
183 type_param_constraints = new ArrayList ();
185 foreach (object obj in constraints) {
186 if (HasConstructorConstraint) {
187 Report.Error (401, loc,
188 "The new() constraint must be last.");
192 if (obj is SpecialConstraint) {
193 SpecialConstraint sc = (SpecialConstraint) obj;
195 if (sc == SpecialConstraint.Constructor) {
196 if (!HasValueTypeConstraint) {
197 attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
202 451, loc, "The new () constraint " +
203 "cannot be used with the `struct' " +
208 if ((num_constraints > 0) || HasReferenceTypeConstraint || HasValueTypeConstraint) {
209 Report.Error (449, loc,
210 "The `class' or `struct' " +
211 "constraint must be first");
215 if (sc == SpecialConstraint.ReferenceType)
216 attrs |= GenericParameterAttributes.ReferenceTypeConstraint;
218 attrs |= GenericParameterAttributes.NotNullableValueTypeConstraint;
222 int errors = Report.Errors;
223 FullNamedExpression fn = ((Expression) obj).ResolveAsTypeStep (ec, false);
226 if (errors != Report.Errors)
229 Report.Error (246, loc, "Cannot find type '{0}'", ((Expression) obj).GetSignatureForError ());
234 ConstructedType cexpr = fn as ConstructedType;
236 if (!cexpr.ResolveConstructedType (ec))
241 expr = fn.ResolveAsTypeTerminal (ec, false);
243 if ((expr == null) || (expr.Type == null))
246 TypeParameterExpr texpr = expr as TypeParameterExpr;
248 type_param_constraints.Add (expr);
249 else if (expr.IsInterface)
250 iface_constraints.Add (expr);
251 else if (class_constraint != null) {
252 Report.Error (406, loc,
253 "`{0}': the class constraint for `{1}' " +
254 "must come before any other constraints.",
257 } else if (HasReferenceTypeConstraint || HasValueTypeConstraint) {
258 Report.Error (450, loc, "`{0}': cannot specify both " +
259 "a constraint class and the `class' " +
260 "or `struct' constraint.", expr.Name);
263 class_constraint = expr;
268 ArrayList list = new ArrayList ();
269 foreach (TypeExpr iface_constraint in iface_constraints) {
270 foreach (Type type in list) {
271 if (!type.Equals (iface_constraint.Type))
274 Report.Error (405, loc,
275 "Duplicate constraint `{0}' for type " +
276 "parameter `{1}'.", iface_constraint.GetSignatureForError (),
281 list.Add (iface_constraint.Type);
284 foreach (TypeParameterExpr expr in type_param_constraints) {
285 foreach (Type type in list) {
286 if (!type.Equals (expr.Type))
289 Report.Error (405, loc,
290 "Duplicate constraint `{0}' for type " +
291 "parameter `{1}'.", expr.GetSignatureForError (), name);
295 list.Add (expr.Type);
298 iface_constraint_types = new Type [list.Count];
299 list.CopyTo (iface_constraint_types, 0);
301 if (class_constraint != null) {
302 class_constraint_type = class_constraint.Type;
303 if (class_constraint_type == null)
306 if (class_constraint_type.IsSealed) {
307 Report.Error (701, loc,
308 "`{0}' is not a valid bound. Bounds " +
309 "must be interfaces or non sealed " +
310 "classes", TypeManager.CSharpName (class_constraint_type));
314 if ((class_constraint_type == TypeManager.array_type) ||
315 (class_constraint_type == TypeManager.delegate_type) ||
316 (class_constraint_type == TypeManager.enum_type) ||
317 (class_constraint_type == TypeManager.value_type) ||
318 (class_constraint_type == TypeManager.object_type)) {
319 Report.Error (702, loc,
320 "Bound cannot be special class `{0}'",
321 TypeManager.CSharpName (class_constraint_type));
326 if (class_constraint_type != null)
327 effective_base_type = class_constraint_type;
328 else if (HasValueTypeConstraint)
329 effective_base_type = TypeManager.value_type;
331 effective_base_type = TypeManager.object_type;
337 bool CheckTypeParameterConstraints (TypeParameter tparam, Hashtable seen)
339 seen.Add (tparam, true);
341 Constraints constraints = tparam.Constraints;
342 if (constraints == null)
345 if (constraints.HasValueTypeConstraint) {
346 Report.Error (456, loc, "Type parameter `{0}' has " +
347 "the `struct' constraint, so it cannot " +
348 "be used as a constraint for `{1}'",
353 if (constraints.type_param_constraints == null)
356 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
357 if (seen.Contains (expr.TypeParameter)) {
358 Report.Error (454, loc, "Circular constraint " +
359 "dependency involving `{0}' and `{1}'",
360 tparam.Name, expr.Name);
364 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
372 /// Resolve the constraints into actual types.
374 public bool ResolveTypes (IResolveContext ec)
379 resolved_types = true;
381 foreach (object obj in constraints) {
382 ConstructedType cexpr = obj as ConstructedType;
386 if (!cexpr.CheckConstraints (ec))
390 foreach (TypeParameterExpr expr in type_param_constraints) {
391 Hashtable seen = new Hashtable ();
392 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
396 for (int i = 0; i < iface_constraints.Count; ++i) {
397 TypeExpr iface_constraint = (TypeExpr) iface_constraints [i];
398 iface_constraint = iface_constraint.ResolveAsTypeTerminal (ec, false);
399 if (iface_constraint == null)
401 iface_constraints [i] = iface_constraint;
404 if (class_constraint != null) {
405 class_constraint = class_constraint.ResolveAsTypeTerminal (ec, false);
406 if (class_constraint == null)
414 /// Check whether there are no conflicts in our type parameter constraints.
416 /// This is an example:
420 /// where U : T, struct
422 public bool CheckDependencies ()
424 foreach (TypeParameterExpr expr in type_param_constraints) {
425 if (!CheckDependencies (expr.TypeParameter))
432 bool CheckDependencies (TypeParameter tparam)
434 Constraints constraints = tparam.Constraints;
435 if (constraints == null)
438 if (HasValueTypeConstraint && constraints.HasClassConstraint) {
439 Report.Error (455, loc, "Type parameter `{0}' inherits " +
440 "conflicting constraints `{1}' and `{2}'",
441 name, TypeManager.CSharpName (constraints.ClassConstraint),
446 if (HasClassConstraint && constraints.HasClassConstraint) {
447 Type t1 = ClassConstraint;
448 TypeExpr e1 = class_constraint;
449 Type t2 = constraints.ClassConstraint;
450 TypeExpr e2 = constraints.class_constraint;
452 if (!Convert.ImplicitReferenceConversionExists (e1, t2) &&
453 !Convert.ImplicitReferenceConversionExists (e2, t1)) {
454 Report.Error (455, loc,
455 "Type parameter `{0}' inherits " +
456 "conflicting constraints `{1}' and `{2}'",
457 name, TypeManager.CSharpName (t1), TypeManager.CSharpName (t2));
462 if (constraints.type_param_constraints == null)
465 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
466 if (!CheckDependencies (expr.TypeParameter))
473 public override GenericParameterAttributes Attributes {
474 get { return attrs; }
477 public override bool HasClassConstraint {
478 get { return class_constraint != null; }
481 public override Type ClassConstraint {
482 get { return class_constraint_type; }
485 public override Type[] InterfaceConstraints {
486 get { return iface_constraint_types; }
489 public override Type EffectiveBaseClass {
490 get { return effective_base_type; }
493 public bool IsSubclassOf (Type t)
495 if ((class_constraint_type != null) &&
496 class_constraint_type.IsSubclassOf (t))
499 if (iface_constraint_types == null)
502 foreach (Type iface in iface_constraint_types) {
503 if (TypeManager.IsSubclassOf (iface, t))
510 public Location Location {
517 /// This is used when we're implementing a generic interface method.
518 /// Each method type parameter in implementing method must have the same
519 /// constraints than the corresponding type parameter in the interface
520 /// method. To do that, we're called on each of the implementing method's
523 public bool CheckInterfaceMethod (GenericConstraints gc)
525 if (gc.Attributes != attrs)
528 if (HasClassConstraint != gc.HasClassConstraint)
530 if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
533 int gc_icount = gc.InterfaceConstraints != null ?
534 gc.InterfaceConstraints.Length : 0;
535 int icount = InterfaceConstraints != null ?
536 InterfaceConstraints.Length : 0;
538 if (gc_icount != icount)
541 foreach (Type iface in gc.InterfaceConstraints) {
543 foreach (Type check in InterfaceConstraints) {
544 if (TypeManager.IsEqual (iface, check)) {
559 /// A type parameter from a generic type definition.
561 public class TypeParameter : MemberCore, IMemberContainer {
564 GenericConstraints gc;
565 Constraints constraints;
567 GenericTypeParameterBuilder type;
569 public TypeParameter (DeclSpace parent, DeclSpace decl, string name,
570 Constraints constraints, Attributes attrs, Location loc)
571 : base (parent, new MemberName (name, loc), attrs)
575 this.constraints = constraints;
579 public GenericConstraints GenericConstraints {
580 get { return gc != null ? gc : constraints; }
583 public Constraints Constraints {
584 get { return constraints; }
587 public bool HasConstructorConstraint {
588 get { return constraints != null && constraints.HasConstructorConstraint; }
591 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 (IResolveContext 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 (IResolveContext 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 (IResolveContext 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 (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 CompilerGeneratedClass) {
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 ()
769 if (constraints != null)
770 return constraints.CheckDependencies ();
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 (IResolveContext ec, Constraints new_constraints)
786 throw new InvalidOperationException ();
788 if (new_constraints == null)
791 if (!new_constraints.Resolve (ec))
793 if (!new_constraints.ResolveTypes (ec))
796 if (constraints != null)
797 return constraints.CheckInterfaceMethod (new_constraints);
799 constraints = new_constraints;
803 public void EmitAttributes ()
805 if (OptAttributes != null)
806 OptAttributes.Emit ();
809 public override string DocCommentHeader {
811 throw new InvalidOperationException (
812 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
820 public override bool Define ()
825 public override void ApplyAttributeBuilder (Attribute a,
826 CustomAttributeBuilder cb)
828 type.SetCustomAttribute (cb);
831 public override AttributeTargets AttributeTargets {
833 return (AttributeTargets) AttributeTargets.GenericParameter;
837 public override string[] ValidAttributeTargets {
839 return new string [] { "type parameter" };
847 string IMemberContainer.Name {
851 MemberCache IMemberContainer.BaseCache {
855 bool IMemberContainer.IsInterface {
859 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
861 return FindMembers (mt, bf, null, null);
864 MemberCache IMemberContainer.MemberCache {
868 public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
869 MemberFilter filter, object criteria)
871 if (constraints == null)
872 return MemberList.Empty;
874 ArrayList members = new ArrayList ();
876 if (gc.HasClassConstraint) {
877 MemberList list = TypeManager.FindMembers (
878 gc.ClassConstraint, mt, bf, filter, criteria);
880 members.AddRange (list);
883 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
884 foreach (Type t in ifaces) {
885 MemberList list = TypeManager.FindMembers (
886 t, mt, bf, filter, criteria);
888 members.AddRange (list);
891 return new MemberList (members);
894 public bool IsSubclassOf (Type t)
899 if (constraints != null)
900 return constraints.IsSubclassOf (t);
905 public override string ToString ()
907 return "TypeParameter[" + name + "]";
910 public static string GetSignatureForError (TypeParameter[] tp)
912 if (tp == null || tp.Length == 0)
915 StringBuilder sb = new StringBuilder ("<");
916 for (int i = 0; i < tp.Length; ++i) {
919 sb.Append (tp[i].GetSignatureForError ());
922 return sb.ToString ();
925 public void InflateConstraints (Type declaring)
927 if (constraints != null)
928 gc = new InflatedConstraints (constraints, declaring);
931 protected class InflatedConstraints : GenericConstraints
933 GenericConstraints gc;
935 Type class_constraint;
936 Type[] iface_constraints;
939 public InflatedConstraints (GenericConstraints gc, Type declaring)
940 : this (gc, TypeManager.GetTypeArguments (declaring))
943 public InflatedConstraints (GenericConstraints gc, Type[] dargs)
948 ArrayList list = new ArrayList ();
949 if (gc.HasClassConstraint)
950 list.Add (inflate (gc.ClassConstraint));
951 foreach (Type iface in gc.InterfaceConstraints)
952 list.Add (inflate (iface));
954 bool has_class_constr = false;
955 if (list.Count > 0) {
956 Type first = (Type) list [0];
957 has_class_constr = !first.IsInterface && !first.IsGenericParameter;
960 if ((list.Count > 0) && has_class_constr) {
961 class_constraint = (Type) list [0];
962 iface_constraints = new Type [list.Count - 1];
963 list.CopyTo (1, iface_constraints, 0, list.Count - 1);
965 iface_constraints = new Type [list.Count];
966 list.CopyTo (iface_constraints, 0);
969 if (HasValueTypeConstraint)
970 base_type = TypeManager.value_type;
971 else if (class_constraint != null)
972 base_type = class_constraint;
974 base_type = TypeManager.object_type;
977 Type inflate (Type t)
981 if (t.IsGenericParameter)
982 return dargs [t.GenericParameterPosition];
983 if (t.IsGenericType) {
984 Type[] args = t.GetGenericArguments ();
985 Type[] inflated = new Type [args.Length];
987 for (int i = 0; i < args.Length; i++)
988 inflated [i] = inflate (args [i]);
990 t = t.GetGenericTypeDefinition ();
991 t = t.MakeGenericType (inflated);
997 public override string TypeParameter {
998 get { return gc.TypeParameter; }
1001 public override GenericParameterAttributes Attributes {
1002 get { return gc.Attributes; }
1005 public override Type ClassConstraint {
1006 get { return class_constraint; }
1009 public override Type EffectiveBaseClass {
1010 get { return base_type; }
1013 public override Type[] InterfaceConstraints {
1014 get { return iface_constraints; }
1020 /// A TypeExpr which already resolved to a type parameter.
1022 public class TypeParameterExpr : TypeExpr {
1023 TypeParameter type_parameter;
1025 public override string Name {
1027 return type_parameter.Name;
1031 public override string FullName {
1033 return type_parameter.Name;
1037 public TypeParameter TypeParameter {
1039 return type_parameter;
1043 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1045 this.type_parameter = type_parameter;
1049 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1051 type = type_parameter.Type;
1056 public override bool IsInterface {
1057 get { return false; }
1060 public override bool CheckAccessLevel (DeclSpace ds)
1065 public void Error_CannotUseAsUnmanagedType (Location loc)
1067 Report.Error (-203, loc, "Can not use type parameter as unmanaged type");
1072 /// Tracks the type arguments when instantiating a generic type. We're used in
1073 /// ConstructedType.
1075 public class TypeArguments {
1076 public readonly Location Location;
1083 public TypeArguments (Location loc)
1085 args = new ArrayList ();
1086 this.Location = loc;
1089 public TypeArguments (int dimension, Location loc)
1091 this.dimension = dimension;
1092 this.Location = loc;
1095 public void Add (Expression type)
1098 throw new InvalidOperationException ();
1103 public void Add (TypeArguments new_args)
1106 throw new InvalidOperationException ();
1108 args.AddRange (new_args.args);
1112 /// We're used during the parsing process: the parser can't distinguish
1113 /// between type parameters and type arguments. Because of that, the
1114 /// parser creates a `MemberName' with `TypeArguments' for both cases and
1115 /// in case of a generic type definition, we call GetDeclarations().
1117 public TypeParameterName[] GetDeclarations ()
1119 TypeParameterName[] ret = new TypeParameterName [args.Count];
1120 for (int i = 0; i < args.Count; i++) {
1121 TypeParameterName name = args [i] as TypeParameterName;
1126 SimpleName sn = args [i] as SimpleName;
1128 ret [i] = new TypeParameterName (sn.Name, null, sn.Location);
1132 Report.Error (81, Location, "Type parameter declaration " +
1133 "must be an identifier not a type");
1140 /// We may only be used after Resolve() is called and return the fully
1143 public Type[] Arguments {
1149 public bool HasTypeArguments {
1151 return has_type_args;
1164 public bool IsUnbound {
1166 return dimension > 0;
1170 public override string ToString ()
1172 StringBuilder s = new StringBuilder ();
1175 for (int i = 0; i < count; i++){
1177 // FIXME: Use TypeManager.CSharpname once we have the type
1180 s.Append (args [i].ToString ());
1184 return s.ToString ();
1188 /// Resolve the type arguments.
1190 public bool Resolve (IResolveContext ec)
1192 int count = args.Count;
1195 atypes = new Type [count];
1197 for (int i = 0; i < count; i++){
1198 TypeExpr te = ((Expression) args [i]).ResolveAsTypeTerminal (ec, false);
1203 if (te is TypeParameterExpr)
1204 has_type_args = true;
1206 if (te.Type.IsPointer) {
1207 Report.Error (306, Location, "The type `{0}' may not be used " +
1208 "as a type argument", TypeManager.CSharpName (te.Type));
1210 } else if (te.Type == TypeManager.void_type) {
1211 Report.Error (1547, Location,
1212 "Keyword `void' cannot be used in this context");
1216 atypes [i] = te.Type;
1222 public class TypeParameterName : SimpleName
1224 Attributes attributes;
1226 public TypeParameterName (string name, Attributes attrs, Location loc)
1232 public Attributes OptAttributes {
1240 /// An instantiation of a generic type.
1242 public class ConstructedType : TypeExpr {
1244 FullNamedExpression name;
1246 Type[] gen_params, atypes;
1250 /// Instantiate the generic type `fname' with the type arguments `args'.
1252 public ConstructedType (FullNamedExpression fname, TypeArguments args, Location l)
1258 eclass = ExprClass.Type;
1259 full_name = name + "<" + args.ToString () + ">";
1262 protected ConstructedType (TypeArguments args, Location l)
1267 eclass = ExprClass.Type;
1270 protected ConstructedType (TypeParameter[] type_params, Location l)
1274 args = new TypeArguments (l);
1275 foreach (TypeParameter type_param in type_params)
1276 args.Add (new TypeParameterExpr (type_param, l));
1278 eclass = ExprClass.Type;
1282 /// This is used to construct the `this' type inside a generic type definition.
1284 public ConstructedType (Type t, TypeParameter[] type_params, Location l)
1285 : this (type_params, l)
1287 gt = t.GetGenericTypeDefinition ();
1289 this.name = new TypeExpression (gt, l);
1290 full_name = gt.FullName + "<" + args.ToString () + ">";
1294 /// Instantiate the generic type `t' with the type arguments `args'.
1295 /// Use this constructor if you already know the fully resolved
1298 public ConstructedType (Type t, TypeArguments args, Location l)
1301 gt = t.GetGenericTypeDefinition ();
1303 this.name = new TypeExpression (gt, l);
1304 full_name = gt.FullName + "<" + args.ToString () + ">";
1307 public TypeArguments TypeArguments {
1308 get { return args; }
1311 public override string GetSignatureForError ()
1313 return TypeManager.CSharpName (gt);
1316 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1318 if (!ResolveConstructedType (ec))
1325 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1326 /// after fully resolving the constructed type.
1328 public bool CheckConstraints (IResolveContext ec)
1330 return ConstraintChecker.CheckConstraints (ec, gt, gen_params, atypes, loc);
1334 /// Resolve the constructed type, but don't check the constraints.
1336 public bool ResolveConstructedType (IResolveContext ec)
1340 // If we already know the fully resolved generic type.
1342 return DoResolveType (ec);
1348 Report.Error (246, loc, "Cannot find type `{0}'<...>", Name);
1352 num_args = TypeManager.GetNumberOfTypeArguments (t);
1353 if (num_args == 0) {
1354 Report.Error (308, loc,
1355 "The non-generic type `{0}' cannot " +
1356 "be used with type arguments.",
1357 TypeManager.CSharpName (t));
1361 gt = t.GetGenericTypeDefinition ();
1362 return DoResolveType (ec);
1365 bool DoResolveType (IResolveContext ec)
1368 // Resolve the arguments.
1370 if (args.Resolve (ec) == false)
1373 gen_params = gt.GetGenericArguments ();
1374 atypes = args.Arguments;
1376 if (atypes.Length != gen_params.Length) {
1377 Report.Error (305, loc,
1378 "Using the generic type `{0}' " +
1379 "requires {1} type arguments",
1380 TypeManager.CSharpName (gt),
1381 gen_params.Length.ToString ());
1386 // Now bind the parameters.
1388 type = gt.MakeGenericType (atypes);
1392 public Expression GetSimpleName (EmitContext ec)
1397 public override bool CheckAccessLevel (DeclSpace ds)
1399 return ds.CheckAccessLevel (gt);
1402 public override bool AsAccessible (DeclSpace ds, int flags)
1404 return ds.AsAccessible (gt, flags);
1407 public override bool IsClass {
1408 get { return gt.IsClass; }
1411 public override bool IsValueType {
1412 get { return gt.IsValueType; }
1415 public override bool IsInterface {
1416 get { return gt.IsInterface; }
1419 public override bool IsSealed {
1420 get { return gt.IsSealed; }
1423 public override bool Equals (object obj)
1425 ConstructedType cobj = obj as ConstructedType;
1429 if ((type == null) || (cobj.type == null))
1432 return type == cobj.type;
1435 public override int GetHashCode ()
1437 return base.GetHashCode ();
1440 public override string Name {
1447 public override string FullName {
1454 public abstract class ConstraintChecker
1456 protected readonly Type[] gen_params;
1457 protected readonly Type[] atypes;
1458 protected readonly Location loc;
1460 protected ConstraintChecker (Type[] gen_params, Type[] atypes, Location loc)
1462 this.gen_params = gen_params;
1463 this.atypes = atypes;
1468 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1469 /// after fully resolving the constructed type.
1471 public bool CheckConstraints (IResolveContext ec)
1473 for (int i = 0; i < gen_params.Length; i++) {
1474 if (!CheckConstraints (ec, i))
1481 protected bool CheckConstraints (IResolveContext ec, int index)
1483 Type atype = atypes [index];
1484 Type ptype = gen_params [index];
1489 Expression aexpr = new EmptyExpression (atype);
1491 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1495 bool is_class, is_struct;
1496 if (atype.IsGenericParameter) {
1497 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1499 if (agc is Constraints)
1500 ((Constraints) agc).Resolve (ec);
1501 is_class = agc.HasReferenceTypeConstraint;
1502 is_struct = agc.HasValueTypeConstraint;
1504 is_class = is_struct = false;
1509 if (!atype.IsGenericType)
1511 is_class = atype.IsClass || atype.IsInterface;
1512 is_struct = atype.IsValueType && !TypeManager.IsNullableType (atype);
1516 // First, check the `class' and `struct' constraints.
1518 if (gc.HasReferenceTypeConstraint && !is_class) {
1519 Report.Error (452, loc, "The type `{0}' must be " +
1520 "a reference type in order to use it " +
1521 "as type parameter `{1}' in the " +
1522 "generic type or method `{2}'.",
1523 TypeManager.CSharpName (atype),
1524 TypeManager.CSharpName (ptype),
1525 GetSignatureForError ());
1527 } else if (gc.HasValueTypeConstraint && !is_struct) {
1528 Report.Error (453, loc, "The type `{0}' must be a " +
1529 "non-nullable value type in order to use it " +
1530 "as type parameter `{1}' in the " +
1531 "generic type or method `{2}'.",
1532 TypeManager.CSharpName (atype),
1533 TypeManager.CSharpName (ptype),
1534 GetSignatureForError ());
1539 // The class constraint comes next.
1541 if (gc.HasClassConstraint) {
1542 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint))
1547 // Now, check the interface constraints.
1549 if (gc.InterfaceConstraints != null) {
1550 foreach (Type it in gc.InterfaceConstraints) {
1551 if (!CheckConstraint (ec, ptype, aexpr, it))
1557 // Finally, check the constructor constraint.
1560 if (!gc.HasConstructorConstraint)
1563 if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
1566 if (HasDefaultConstructor (ec.DeclContainer.TypeBuilder, atype))
1569 Report_SymbolRelatedToPreviousError ();
1570 Report.SymbolRelatedToPreviousError (atype);
1571 Report.Error (310, loc, "The type `{0}' must have a public " +
1572 "parameterless constructor in order to use it " +
1573 "as parameter `{1}' in the generic type or " +
1575 TypeManager.CSharpName (atype),
1576 TypeManager.CSharpName (ptype),
1577 GetSignatureForError ());
1581 protected bool CheckConstraint (IResolveContext ec, Type ptype, Expression expr,
1584 if (TypeManager.HasGenericArguments (ctype)) {
1585 Type[] types = TypeManager.GetTypeArguments (ctype);
1587 TypeArguments new_args = new TypeArguments (loc);
1589 for (int i = 0; i < types.Length; i++) {
1592 if (t.IsGenericParameter) {
1593 int pos = t.GenericParameterPosition;
1596 new_args.Add (new TypeExpression (t, loc));
1599 TypeExpr ct = new ConstructedType (ctype, new_args, loc);
1600 if (ct.ResolveAsTypeStep (ec, false) == null)
1603 } else if (ctype.IsGenericParameter) {
1604 int pos = ctype.GenericParameterPosition;
1605 ctype = atypes [pos];
1608 if (Convert.ImplicitStandardConversionExists (expr, ctype))
1611 Error_TypeMustBeConvertible (expr.Type, ctype, ptype);
1615 bool HasDefaultConstructor (Type containerType, Type atype)
1617 if (atype.IsAbstract)
1621 atype = TypeManager.DropGenericTypeArguments (atype);
1622 if (atype is TypeBuilder) {
1623 TypeContainer tc = TypeManager.LookupTypeContainer (atype);
1624 if (tc.InstanceConstructors == null) {
1625 atype = atype.BaseType;
1629 foreach (Constructor c in tc.InstanceConstructors) {
1630 if ((c.ModFlags & Modifiers.PUBLIC) == 0)
1632 if ((c.Parameters.FixedParameters != null) &&
1633 (c.Parameters.FixedParameters.Length != 0))
1635 if (c.Parameters.HasArglist || c.Parameters.HasParams)
1642 TypeParameter tparam = TypeManager.LookupTypeParameter (atype);
1644 return tparam.HasConstructorConstraint;
1646 MemberList list = TypeManager.FindMembers (
1647 atype, MemberTypes.Constructor,
1648 BindingFlags.Public | BindingFlags.Instance |
1649 BindingFlags.DeclaredOnly, null, null);
1651 if (atype.IsAbstract || (list == null))
1654 foreach (MethodBase mb in list) {
1655 ParameterData pd = TypeManager.GetParameterData (mb);
1656 if ((pd.Count == 0) && mb.IsPublic && !mb.IsStatic)
1663 protected abstract string GetSignatureForError ();
1664 protected abstract void Report_SymbolRelatedToPreviousError ();
1666 void Error_TypeMustBeConvertible (Type atype, Type gc, Type ptype)
1668 Report_SymbolRelatedToPreviousError ();
1669 Report.SymbolRelatedToPreviousError (atype);
1670 Report.Error (309, loc,
1671 "The type `{0}' must be convertible to `{1}' in order to " +
1672 "use it as parameter `{2}' in the generic type or method `{3}'",
1673 TypeManager.CSharpName (atype), TypeManager.CSharpName (gc),
1674 TypeManager.CSharpName (ptype), GetSignatureForError ());
1677 public static bool CheckConstraints (EmitContext ec, MethodBase definition,
1678 MethodBase instantiated, Location loc)
1680 MethodConstraintChecker checker = new MethodConstraintChecker (
1681 definition, definition.GetGenericArguments (),
1682 instantiated.GetGenericArguments (), loc);
1684 return checker.CheckConstraints (ec);
1687 public static bool CheckConstraints (IResolveContext ec, Type gt, Type[] gen_params,
1688 Type[] atypes, Location loc)
1690 TypeConstraintChecker checker = new TypeConstraintChecker (
1691 gt, gen_params, atypes, loc);
1693 return checker.CheckConstraints (ec);
1696 protected class MethodConstraintChecker : ConstraintChecker
1698 MethodBase definition;
1700 public MethodConstraintChecker (MethodBase definition, Type[] gen_params,
1701 Type[] atypes, Location loc)
1702 : base (gen_params, atypes, loc)
1704 this.definition = definition;
1707 protected override string GetSignatureForError ()
1709 return TypeManager.CSharpSignature (definition);
1712 protected override void Report_SymbolRelatedToPreviousError ()
1714 Report.SymbolRelatedToPreviousError (definition);
1718 protected class TypeConstraintChecker : ConstraintChecker
1722 public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
1724 : base (gen_params, atypes, loc)
1729 protected override string GetSignatureForError ()
1731 return TypeManager.CSharpName (gt);
1734 protected override void Report_SymbolRelatedToPreviousError ()
1736 Report.SymbolRelatedToPreviousError (gt);
1742 /// A generic method definition.
1744 public class GenericMethod : DeclSpace
1746 Expression return_type;
1747 Parameters parameters;
1749 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
1750 Expression return_type, Parameters parameters)
1751 : base (ns, parent, name, null)
1753 this.return_type = return_type;
1754 this.parameters = parameters;
1757 public override TypeBuilder DefineType ()
1759 throw new Exception ();
1762 public override bool Define ()
1764 for (int i = 0; i < TypeParameters.Length; i++)
1765 if (!TypeParameters [i].Resolve (this))
1772 /// Define and resolve the type parameters.
1773 /// We're called from Method.Define().
1775 public bool Define (MethodBuilder mb, ToplevelBlock block)
1777 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1778 string[] snames = new string [names.Length];
1779 for (int i = 0; i < names.Length; i++) {
1780 string type_argument_name = names[i].Name;
1781 Parameter p = parameters.GetParameterByName (type_argument_name);
1783 Error_ParameterNameCollision (p.Location, type_argument_name, "method parameter");
1786 if (block != null) {
1787 LocalInfo li = (LocalInfo)block.Variables[type_argument_name];
1789 Error_ParameterNameCollision (li.Location, type_argument_name, "local variable");
1793 snames[i] = type_argument_name;
1796 GenericTypeParameterBuilder[] gen_params = mb.DefineGenericParameters (snames);
1797 for (int i = 0; i < TypeParameters.Length; i++)
1798 TypeParameters [i].Define (gen_params [i]);
1803 for (int i = 0; i < TypeParameters.Length; i++) {
1804 if (!TypeParameters [i].ResolveType (this))
1811 static void Error_ParameterNameCollision (Location loc, string name, string collisionWith)
1813 Report.Error (412, loc, "The type parameter name `{0}' is the same as `{1}'",
1814 name, collisionWith);
1818 /// We're called from MethodData.Define() after creating the MethodBuilder.
1820 public bool DefineType (EmitContext ec, MethodBuilder mb,
1821 MethodInfo implementing, bool is_override)
1823 for (int i = 0; i < TypeParameters.Length; i++)
1824 if (!TypeParameters [i].DefineType (
1825 ec, mb, implementing, is_override))
1829 foreach (Parameter p in parameters.FixedParameters){
1830 if (!p.Resolve (ec))
1833 if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec, false) == null))
1839 public void EmitAttributes ()
1841 for (int i = 0; i < TypeParameters.Length; i++)
1842 TypeParameters [i].EmitAttributes ();
1844 if (OptAttributes != null)
1845 OptAttributes.Emit ();
1848 public override bool DefineMembers ()
1853 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1854 MemberFilter filter, object criteria)
1856 throw new Exception ();
1859 public override MemberCache MemberCache {
1865 public override AttributeTargets AttributeTargets {
1867 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1871 public override string DocCommentHeader {
1872 get { return "M:"; }
1876 public class DefaultValueExpression : Expression
1880 public DefaultValueExpression (Expression expr, Location loc)
1886 public override Expression DoResolve (EmitContext ec)
1888 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
1894 eclass = ExprClass.Variable;
1898 public override void Emit (EmitContext ec)
1900 if (type.IsGenericParameter || TypeManager.IsValueType (type)) {
1901 LocalTemporary temp_storage = new LocalTemporary (type);
1903 temp_storage.AddressOf (ec, AddressOp.LoadStore);
1904 ec.ig.Emit (OpCodes.Initobj, type);
1905 temp_storage.Emit (ec);
1907 ec.ig.Emit (OpCodes.Ldnull);
1911 public class NullableType : TypeExpr
1913 Expression underlying;
1915 public NullableType (Expression underlying, Location l)
1917 this.underlying = underlying;
1920 eclass = ExprClass.Type;
1923 public NullableType (Type type, Location loc)
1924 : this (new TypeExpression (type, loc), loc)
1927 public override string Name {
1928 get { return underlying.ToString () + "?"; }
1931 public override string FullName {
1932 get { return underlying.ToString () + "?"; }
1935 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1937 TypeArguments args = new TypeArguments (loc);
1938 args.Add (underlying);
1940 ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
1941 return ctype.ResolveAsTypeTerminal (ec, false);
1945 public partial class TypeManager
1948 // A list of core types that the compiler requires or uses
1950 static public Type activator_type;
1951 static public Type generic_ilist_type;
1952 static public Type generic_icollection_type;
1953 static public Type generic_ienumerator_type;
1954 static public Type generic_ienumerable_type;
1955 static public Type generic_nullable_type;
1958 // Tracks the generic parameters.
1960 static PtrHashtable builder_to_type_param;
1963 // These methods are called by code generated by the compiler
1965 static public MethodInfo activator_create_instance;
1967 static void InitGenerics ()
1969 builder_to_type_param = new PtrHashtable ();
1972 static void CleanUpGenerics ()
1974 builder_to_type_param = null;
1977 static void InitGenericCoreTypes ()
1979 activator_type = CoreLookupType ("System", "Activator");
1981 generic_ilist_type = CoreLookupType (
1982 "System.Collections.Generic", "IList", 1);
1983 generic_icollection_type = CoreLookupType (
1984 "System.Collections.Generic", "ICollection", 1);
1985 generic_ienumerator_type = CoreLookupType (
1986 "System.Collections.Generic", "IEnumerator", 1);
1987 generic_ienumerable_type = CoreLookupType (
1988 "System.Collections.Generic", "IEnumerable", 1);
1989 generic_nullable_type = CoreLookupType (
1990 "System", "Nullable", 1);
1993 static void InitGenericCodeHelpers ()
1996 Type [] type_arg = { type_type };
1997 activator_create_instance = GetMethod (
1998 activator_type, "CreateInstance", type_arg);
2001 static Type CoreLookupType (string ns, string name, int arity)
2003 return CoreLookupType (ns, MemberName.MakeName (name, arity));
2006 public static void AddTypeParameter (Type t, TypeParameter tparam)
2008 if (!builder_to_type_param.Contains (t))
2009 builder_to_type_param.Add (t, tparam);
2012 public static TypeContainer LookupGenericTypeContainer (Type t)
2014 t = DropGenericTypeArguments (t);
2015 return LookupTypeContainer (t);
2018 public static TypeParameter LookupTypeParameter (Type t)
2020 return (TypeParameter) builder_to_type_param [t];
2023 public static GenericConstraints GetTypeParameterConstraints (Type t)
2025 if (!t.IsGenericParameter)
2026 throw new InvalidOperationException ();
2028 TypeParameter tparam = LookupTypeParameter (t);
2030 return tparam.GenericConstraints;
2032 return ReflectionConstraints.GetConstraints (t);
2035 public static bool HasGenericArguments (Type t)
2037 return GetNumberOfTypeArguments (t) > 0;
2040 public static int GetNumberOfTypeArguments (Type t)
2042 if (t.IsGenericParameter)
2044 DeclSpace tc = LookupDeclSpace (t);
2046 return tc.IsGeneric ? tc.CountTypeParameters : 0;
2048 return t.IsGenericType ? t.GetGenericArguments ().Length : 0;
2051 public static Type[] GetTypeArguments (Type t)
2053 DeclSpace tc = LookupDeclSpace (t);
2056 return Type.EmptyTypes;
2058 TypeParameter[] tparam = tc.TypeParameters;
2059 Type[] ret = new Type [tparam.Length];
2060 for (int i = 0; i < tparam.Length; i++) {
2061 ret [i] = tparam [i].Type;
2062 if (ret [i] == null)
2063 throw new InternalErrorException ();
2068 return t.GetGenericArguments ();
2071 public static Type DropGenericTypeArguments (Type t)
2073 if (!t.IsGenericType)
2075 // Micro-optimization: a generic typebuilder is always a generic type definition
2076 if (t is TypeBuilder)
2078 return t.GetGenericTypeDefinition ();
2081 public static MethodBase DropGenericMethodArguments (MethodBase m)
2083 if (m.IsGenericMethodDefinition)
2085 if (m.IsGenericMethod)
2086 return ((MethodInfo) m).GetGenericMethodDefinition ();
2087 if (!m.DeclaringType.IsGenericType)
2090 Type t = m.DeclaringType.GetGenericTypeDefinition ();
2091 BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
2092 BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
2094 if (m is ConstructorInfo) {
2095 foreach (ConstructorInfo c in t.GetConstructors (bf))
2096 if (c.MetadataToken == m.MetadataToken)
2099 foreach (MethodBase mb in t.GetMethods (bf))
2100 if (mb.MetadataToken == m.MetadataToken)
2107 public static FieldInfo GetGenericFieldDefinition (FieldInfo fi)
2109 if (fi.DeclaringType.IsGenericTypeDefinition ||
2110 !fi.DeclaringType.IsGenericType)
2113 Type t = fi.DeclaringType.GetGenericTypeDefinition ();
2114 BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
2115 BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
2117 foreach (FieldInfo f in t.GetFields (bf))
2118 if (f.MetadataToken == fi.MetadataToken)
2124 public static bool IsEqual (Type a, Type b)
2129 if (a.IsGenericParameter && b.IsGenericParameter) {
2130 if (a.DeclaringMethod != b.DeclaringMethod &&
2131 (a.DeclaringMethod == null || b.DeclaringMethod == null))
2133 return a.GenericParameterPosition == b.GenericParameterPosition;
2136 if (a.IsArray && b.IsArray) {
2137 if (a.GetArrayRank () != b.GetArrayRank ())
2139 return IsEqual (a.GetElementType (), b.GetElementType ());
2142 if (a.IsByRef && b.IsByRef)
2143 return IsEqual (a.GetElementType (), b.GetElementType ());
2145 if (a.IsGenericType && b.IsGenericType) {
2146 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2149 Type[] aargs = a.GetGenericArguments ();
2150 Type[] bargs = b.GetGenericArguments ();
2152 if (aargs.Length != bargs.Length)
2155 for (int i = 0; i < aargs.Length; i++) {
2156 if (!IsEqual (aargs [i], bargs [i]))
2164 // This is to build with the broken circular dependencies between
2165 // System and System.Configuration in the 2.x profile where we
2166 // end up with a situation where:
2168 // System on the second build is referencing the System.Configuration
2169 // that has references to the first System build.
2171 // Point in case: NameValueCollection built on the first pass, vs
2172 // NameValueCollection build on the second one. The problem is that
2173 // we need to override some methods sometimes, or we need to
2175 if (RootContext.BrokenCircularDeps){
2176 if (a.Name == b.Name && a.Namespace == b.Namespace){
2177 Console.WriteLine ("GonziMatch: {0}.{1}", a.Namespace, a.Name);
2185 /// Check whether `a' and `b' may become equal generic types.
2186 /// The algorithm to do that is a little bit complicated.
2188 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_infered,
2189 Type[] method_infered)
2191 if (a.IsGenericParameter) {
2193 // If a is an array of a's type, they may never
2197 b = b.GetElementType ();
2203 // If b is a generic parameter or an actual type,
2204 // they may become equal:
2206 // class X<T,U> : I<T>, I<U>
2207 // class X<T> : I<T>, I<float>
2209 if (b.IsGenericParameter || !b.IsGenericType) {
2210 int pos = a.GenericParameterPosition;
2211 Type[] args = a.DeclaringMethod != null ? method_infered : class_infered;
2212 if (args [pos] == null) {
2217 return args [pos] == a;
2221 // We're now comparing a type parameter with a
2222 // generic instance. They may become equal unless
2223 // the type parameter appears anywhere in the
2224 // generic instance:
2226 // class X<T,U> : I<T>, I<X<U>>
2227 // -> error because you could instanciate it as
2230 // class X<T> : I<T>, I<X<T>> -> ok
2233 Type[] bargs = GetTypeArguments (b);
2234 for (int i = 0; i < bargs.Length; i++) {
2235 if (a.Equals (bargs [i]))
2242 if (b.IsGenericParameter)
2243 return MayBecomeEqualGenericTypes (b, a, class_infered, method_infered);
2246 // At this point, neither a nor b are a type parameter.
2248 // If one of them is a generic instance, let
2249 // MayBecomeEqualGenericInstances() compare them (if the
2250 // other one is not a generic instance, they can never
2254 if (a.IsGenericType || b.IsGenericType)
2255 return MayBecomeEqualGenericInstances (a, b, class_infered, method_infered);
2258 // If both of them are arrays.
2261 if (a.IsArray && b.IsArray) {
2262 if (a.GetArrayRank () != b.GetArrayRank ())
2265 a = a.GetElementType ();
2266 b = b.GetElementType ();
2268 return MayBecomeEqualGenericTypes (a, b, class_infered, method_infered);
2272 // Ok, two ordinary types.
2275 return a.Equals (b);
2279 // Checks whether two generic instances may become equal for some
2280 // particular instantiation (26.3.1).
2282 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
2283 Type[] class_infered,
2284 Type[] method_infered)
2286 if (!a.IsGenericType || !b.IsGenericType)
2288 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2291 return MayBecomeEqualGenericInstances (
2292 GetTypeArguments (a), GetTypeArguments (b), class_infered, method_infered);
2295 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
2296 Type[] class_infered,
2297 Type[] method_infered)
2299 if (aargs.Length != bargs.Length)
2302 for (int i = 0; i < aargs.Length; i++) {
2303 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_infered, method_infered))
2311 /// Check whether `type' and `parent' are both instantiations of the same
2312 /// generic type. Note that we do not check the type parameters here.
2314 public static bool IsInstantiationOfSameGenericType (Type type, Type parent)
2316 int tcount = GetNumberOfTypeArguments (type);
2317 int pcount = GetNumberOfTypeArguments (parent);
2319 if (tcount != pcount)
2322 type = DropGenericTypeArguments (type);
2323 parent = DropGenericTypeArguments (parent);
2325 return type.Equals (parent);
2329 /// Whether `mb' is a generic method definition.
2331 public static bool IsGenericMethodDefinition (MethodBase mb)
2333 if (mb.DeclaringType is TypeBuilder) {
2334 IMethodData method = (IMethodData) builder_to_method [mb];
2338 return method.GenericMethod != null;
2341 return mb.IsGenericMethodDefinition;
2345 /// Whether `mb' is a generic method definition.
2347 public static bool IsGenericMethod (MethodBase mb)
2349 if (mb.DeclaringType is TypeBuilder) {
2350 IMethodData method = (IMethodData) builder_to_method [mb];
2354 return method.GenericMethod != null;
2357 return mb.IsGenericMethod;
2364 static bool InferType (Type pt, Type at, Type[] infered)
2366 if (pt.IsGenericParameter) {
2367 if (pt.DeclaringMethod == null)
2370 int pos = pt.GenericParameterPosition;
2372 if (infered [pos] == null) {
2377 if (infered [pos] != at)
2383 if (!pt.ContainsGenericParameters) {
2384 if (at.ContainsGenericParameters)
2385 return InferType (at, pt, infered);
2392 if (at.GetArrayRank () != pt.GetArrayRank ())
2395 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2398 if (!pt.IsGenericType)
2401 Type gt = pt.GetGenericTypeDefinition ();
2402 if ((gt != generic_ilist_type) && (gt != generic_icollection_type) &&
2403 (gt != generic_ienumerable_type))
2406 Type[] args = GetTypeArguments (pt);
2407 return InferType (args [0], at.GetElementType (), infered);
2412 (pt.GetArrayRank () != at.GetArrayRank ()))
2415 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2418 if (pt.IsByRef && at.IsByRef)
2419 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2420 ArrayList list = new ArrayList ();
2421 if (at.IsGenericType)
2423 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
2426 list.AddRange (TypeManager.GetInterfaces (at));
2428 bool found_one = false;
2430 foreach (Type type in list) {
2431 if (!type.IsGenericType)
2434 Type[] infered_types = new Type [infered.Length];
2436 if (!InferGenericInstance (pt, type, infered_types))
2439 for (int i = 0; i < infered_types.Length; i++) {
2440 if (infered [i] == null) {
2441 infered [i] = infered_types [i];
2445 if (infered [i] != infered_types [i])
2455 static bool InferGenericInstance (Type pt, Type at, Type[] infered_types)
2457 Type[] at_args = at.GetGenericArguments ();
2458 Type[] pt_args = pt.GetGenericArguments ();
2460 if (at_args.Length != pt_args.Length)
2463 for (int i = 0; i < at_args.Length; i++) {
2464 if (!InferType (pt_args [i], at_args [i], infered_types))
2468 for (int i = 0; i < infered_types.Length; i++) {
2469 if (infered_types [i] == null)
2477 /// Type inference. Try to infer the type arguments from the params method
2478 /// `method', which is invoked with the arguments `arguments'. This is used
2479 /// when resolving an Invocation or a DelegateInvocation and the user
2480 /// did not explicitly specify type arguments.
2482 public static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
2483 ref MethodBase method)
2485 if (!TypeManager.IsGenericMethod (method))
2488 // if there are no arguments, there's no way to infer the type-arguments
2489 if (arguments == null || arguments.Count == 0)
2492 ParameterData pd = TypeManager.GetParameterData (method);
2493 int pd_count = pd.Count;
2494 int arg_count = arguments.Count;
2499 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2502 if (pd_count - 1 > arg_count)
2505 Type[] method_args = method.GetGenericArguments ();
2506 Type[] infered_types = new Type [method_args.Length];
2509 // If we have come this far, the case which
2510 // remains is when the number of parameters is
2511 // less than or equal to the argument count.
2513 for (int i = 0; i < pd_count - 1; ++i) {
2514 Argument a = (Argument) arguments [i];
2516 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2519 Type pt = pd.ParameterType (i);
2522 if (!InferType (pt, at, infered_types))
2526 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
2528 for (int i = pd_count - 1; i < arg_count; i++) {
2529 Argument a = (Argument) arguments [i];
2531 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2534 if (!InferType (element_type, a.Type, infered_types))
2538 for (int i = 0; i < infered_types.Length; i++)
2539 if (infered_types [i] == null)
2542 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2546 static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
2547 Type[] infered_types)
2549 if (infered_types == null)
2552 for (int i = 0; i < arg_types.Length; i++) {
2553 if (arg_types [i] == null)
2556 if (!InferType (param_types [i], arg_types [i], infered_types))
2560 for (int i = 0; i < infered_types.Length; i++)
2561 if (infered_types [i] == null)
2568 /// Type inference. Try to infer the type arguments from `method',
2569 /// which is invoked with the arguments `arguments'. This is used
2570 /// when resolving an Invocation or a DelegateInvocation and the user
2571 /// did not explicitly specify type arguments.
2573 public static bool InferTypeArguments (ArrayList arguments,
2574 ref MethodBase method)
2576 if (!TypeManager.IsGenericMethod (method))
2580 if (arguments != null)
2581 arg_count = arguments.Count;
2585 ParameterData pd = TypeManager.GetParameterData (method);
2586 if (arg_count != pd.Count)
2589 Type[] method_args = method.GetGenericArguments ();
2591 bool is_open = false;
2592 for (int i = 0; i < method_args.Length; i++) {
2593 if (method_args [i].IsGenericParameter) {
2599 // If none of the method parameters mention a generic parameter, we can't infer the generic parameters
2601 return !TypeManager.IsGenericMethodDefinition (method);
2603 Type[] infered_types = new Type [method_args.Length];
2605 Type[] param_types = new Type [pd.Count];
2606 Type[] arg_types = new Type [pd.Count];
2608 for (int i = 0; i < arg_count; i++) {
2609 param_types [i] = pd.ParameterType (i);
2611 Argument a = (Argument) arguments [i];
2612 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr) ||
2613 (a.Expr is AnonymousMethodExpression))
2616 arg_types [i] = a.Type;
2619 if (!InferTypeArguments (param_types, arg_types, infered_types))
2622 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2629 public static bool InferTypeArguments (ParameterData apd,
2630 ref MethodBase method)
2632 if (!TypeManager.IsGenericMethod (method))
2635 ParameterData pd = TypeManager.GetParameterData (method);
2636 if (apd.Count != pd.Count)
2639 Type[] method_args = method.GetGenericArguments ();
2640 Type[] infered_types = new Type [method_args.Length];
2642 Type[] param_types = new Type [pd.Count];
2643 Type[] arg_types = new Type [pd.Count];
2645 for (int i = 0; i < apd.Count; i++) {
2646 param_types [i] = pd.ParameterType (i);
2647 arg_types [i] = apd.ParameterType (i);
2650 if (!InferTypeArguments (param_types, arg_types, infered_types))
2653 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2657 public static bool IsNullableType (Type t)
2659 return generic_nullable_type == DropGenericTypeArguments (t);
2662 public static bool IsNullableTypeOf (Type t, Type nullable)
2664 if (!IsNullableType (t))
2667 return GetTypeArguments (t) [0] == nullable;
2670 public static bool IsNullableValueType (Type t)
2672 if (!IsNullableType (t))
2675 return GetTypeArguments (t) [0].IsValueType;
2679 public abstract class Nullable
2681 public sealed class NullableInfo
2683 public readonly Type Type;
2684 public readonly Type UnderlyingType;
2685 public readonly MethodInfo HasValue;
2686 public readonly MethodInfo Value;
2687 public readonly ConstructorInfo Constructor;
2689 public NullableInfo (Type type)
2692 UnderlyingType = TypeManager.GetTypeArguments (type) [0];
2694 PropertyInfo has_value_pi = TypeManager.GetProperty (type, "HasValue");
2695 PropertyInfo value_pi = TypeManager.GetProperty (type, "Value");
2697 HasValue = has_value_pi.GetGetMethod (false);
2698 Value = value_pi.GetGetMethod (false);
2699 Constructor = type.GetConstructor (new Type[] { UnderlyingType });
2703 public class Unwrap : Expression, IMemoryLocation, IAssignMethod
2708 LocalTemporary temp;
2711 protected Unwrap (Expression expr)
2714 this.loc = expr.Location;
2717 public static Unwrap Create (Expression expr, EmitContext ec)
2719 return new Unwrap (expr).Resolve (ec) as Unwrap;
2722 public override Expression DoResolve (EmitContext ec)
2724 expr = expr.Resolve (ec);
2728 temp = new LocalTemporary (expr.Type);
2730 info = new NullableInfo (expr.Type);
2731 type = info.UnderlyingType;
2732 eclass = expr.eclass;
2736 public override void Emit (EmitContext ec)
2738 AddressOf (ec, AddressOp.LoadStore);
2739 ec.ig.EmitCall (OpCodes.Call, info.Value, null);
2742 public void EmitCheck (EmitContext ec)
2744 AddressOf (ec, AddressOp.LoadStore);
2745 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
2748 public void Store (EmitContext ec)
2753 void create_temp (EmitContext ec)
2755 if ((temp != null) && !has_temp) {
2762 public void AddressOf (EmitContext ec, AddressOp mode)
2766 temp.AddressOf (ec, AddressOp.LoadStore);
2768 ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
2771 public void Emit (EmitContext ec, bool leave_copy)
2784 public void EmitAssign (EmitContext ec, Expression source,
2785 bool leave_copy, bool prepare_for_load)
2787 InternalWrap wrap = new InternalWrap (source, info, loc);
2788 ((IAssignMethod) expr).EmitAssign (ec, wrap, leave_copy, false);
2791 protected class InternalWrap : Expression
2793 public Expression expr;
2794 public NullableInfo info;
2796 public InternalWrap (Expression expr, NullableInfo info, Location loc)
2803 eclass = ExprClass.Value;
2806 public override Expression DoResolve (EmitContext ec)
2811 public override void Emit (EmitContext ec)
2814 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2819 public class Wrap : Expression
2824 protected Wrap (Expression expr)
2827 this.loc = expr.Location;
2830 public static Wrap Create (Expression expr, EmitContext ec)
2832 return new Wrap (expr).Resolve (ec) as Wrap;
2835 public override Expression DoResolve (EmitContext ec)
2837 expr = expr.Resolve (ec);
2841 TypeExpr target_type = new NullableType (expr.Type, loc);
2842 target_type = target_type.ResolveAsTypeTerminal (ec, false);
2843 if (target_type == null)
2846 type = target_type.Type;
2847 info = new NullableInfo (type);
2848 eclass = ExprClass.Value;
2852 public override void Emit (EmitContext ec)
2855 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2859 public class NullableLiteral : NullLiteral, IMemoryLocation {
2860 public NullableLiteral (Type target_type, Location loc)
2863 this.type = target_type;
2865 eclass = ExprClass.Value;
2868 public override Expression DoResolve (EmitContext ec)
2873 public override void Emit (EmitContext ec)
2875 LocalTemporary value_target = new LocalTemporary (type);
2877 value_target.AddressOf (ec, AddressOp.Store);
2878 ec.ig.Emit (OpCodes.Initobj, type);
2879 value_target.Emit (ec);
2882 public void AddressOf (EmitContext ec, AddressOp Mode)
2884 LocalTemporary value_target = new LocalTemporary (type);
2886 value_target.AddressOf (ec, AddressOp.Store);
2887 ec.ig.Emit (OpCodes.Initobj, type);
2888 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
2892 public abstract class Lifted : Expression, IMemoryLocation
2894 Expression expr, underlying, wrap, null_value;
2897 protected Lifted (Expression expr, Location loc)
2903 public override Expression DoResolve (EmitContext ec)
2905 expr = expr.Resolve (ec);
2909 unwrap = Unwrap.Create (expr, ec);
2913 underlying = ResolveUnderlying (unwrap, ec);
2914 if (underlying == null)
2917 wrap = Wrap.Create (underlying, ec);
2921 null_value = new NullableLiteral (wrap.Type, loc).Resolve (ec);
2922 if (null_value == null)
2926 eclass = ExprClass.Value;
2930 protected abstract Expression ResolveUnderlying (Expression unwrap, EmitContext ec);
2932 public override void Emit (EmitContext ec)
2934 ILGenerator ig = ec.ig;
2935 Label is_null_label = ig.DefineLabel ();
2936 Label end_label = ig.DefineLabel ();
2938 unwrap.EmitCheck (ec);
2939 ig.Emit (OpCodes.Brfalse, is_null_label);
2942 ig.Emit (OpCodes.Br, end_label);
2944 ig.MarkLabel (is_null_label);
2945 null_value.Emit (ec);
2947 ig.MarkLabel (end_label);
2950 public void AddressOf (EmitContext ec, AddressOp mode)
2952 unwrap.AddressOf (ec, mode);
2956 public class LiftedConversion : Lifted
2958 public readonly bool IsUser;
2959 public readonly bool IsExplicit;
2960 public readonly Type TargetType;
2962 public LiftedConversion (Expression expr, Type target_type, bool is_user,
2963 bool is_explicit, Location loc)
2966 this.IsUser = is_user;
2967 this.IsExplicit = is_explicit;
2968 this.TargetType = target_type;
2971 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2973 Type type = TypeManager.GetTypeArguments (TargetType) [0];
2976 return Convert.UserDefinedConversion (ec, unwrap, type, loc, IsExplicit);
2979 return Convert.ExplicitConversion (ec, unwrap, type, loc);
2981 return Convert.ImplicitConversion (ec, unwrap, type, loc);
2986 public class LiftedUnaryOperator : Lifted
2988 public readonly Unary.Operator Oper;
2990 public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
2996 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2998 return new Unary (Oper, unwrap, loc);
3002 public class LiftedConditional : Lifted
3004 Expression true_expr, false_expr;
3006 public LiftedConditional (Expression expr, Expression true_expr, Expression false_expr,
3010 this.true_expr = true_expr;
3011 this.false_expr = false_expr;
3014 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
3016 return new Conditional (unwrap, true_expr, false_expr);
3020 public class LiftedBinaryOperator : Expression
3022 public readonly Binary.Operator Oper;
3024 Expression left, right, original_left, original_right;
3025 Expression underlying, null_value, bool_wrap;
3026 Unwrap left_unwrap, right_unwrap;
3027 bool is_equality, is_comparision, is_boolean;
3029 public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
3033 this.left = original_left = left;
3034 this.right = original_right = right;
3038 public override Expression DoResolve (EmitContext ec)
3040 if (TypeManager.IsNullableType (left.Type)) {
3041 left = left_unwrap = Unwrap.Create (left, ec);
3046 if (TypeManager.IsNullableType (right.Type)) {
3047 right = right_unwrap = Unwrap.Create (right, ec);
3052 if ((Oper == Binary.Operator.LogicalAnd) ||
3053 (Oper == Binary.Operator.LogicalOr)) {
3054 Binary.Error_OperatorCannotBeApplied (
3055 loc, Binary.OperName (Oper),
3056 original_left.GetSignatureForError (),
3057 original_right.GetSignatureForError ());
3061 if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr)) &&
3062 ((left.Type == TypeManager.bool_type) && (right.Type == TypeManager.bool_type))) {
3063 Expression empty = new EmptyExpression (TypeManager.bool_type);
3064 bool_wrap = Wrap.Create (empty, ec);
3065 null_value = new NullableLiteral (bool_wrap.Type, loc).Resolve (ec);
3067 type = bool_wrap.Type;
3069 } else if ((Oper == Binary.Operator.Equality) || (Oper == Binary.Operator.Inequality)) {
3070 if (!(left is NullLiteral) && !(right is NullLiteral)) {
3071 underlying = new Binary (Oper, left, right).Resolve (ec);
3072 if (underlying == null)
3076 type = TypeManager.bool_type;
3078 } else if ((Oper == Binary.Operator.LessThan) ||
3079 (Oper == Binary.Operator.GreaterThan) ||
3080 (Oper == Binary.Operator.LessThanOrEqual) ||
3081 (Oper == Binary.Operator.GreaterThanOrEqual)) {
3082 underlying = new Binary (Oper, left, right).Resolve (ec);
3083 if (underlying == null)
3086 type = TypeManager.bool_type;
3087 is_comparision = true;
3089 underlying = new Binary (Oper, left, right).Resolve (ec);
3090 if (underlying == null)
3093 underlying = Wrap.Create (underlying, ec);
3094 if (underlying == null)
3097 type = underlying.Type;
3098 null_value = new NullableLiteral (type, loc).Resolve (ec);
3101 eclass = ExprClass.Value;
3105 void EmitBoolean (EmitContext ec)
3107 ILGenerator ig = ec.ig;
3109 Label left_is_null_label = ig.DefineLabel ();
3110 Label right_is_null_label = ig.DefineLabel ();
3111 Label is_null_label = ig.DefineLabel ();
3112 Label wrap_label = ig.DefineLabel ();
3113 Label end_label = ig.DefineLabel ();
3115 if (left_unwrap != null) {
3116 left_unwrap.EmitCheck (ec);
3117 ig.Emit (OpCodes.Brfalse, left_is_null_label);
3121 ig.Emit (OpCodes.Dup);
3122 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3123 ig.Emit (OpCodes.Brtrue, wrap_label);
3125 ig.Emit (OpCodes.Brfalse, wrap_label);
3127 if (right_unwrap != null) {
3128 right_unwrap.EmitCheck (ec);
3129 ig.Emit (OpCodes.Brfalse, right_is_null_label);
3132 if ((Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr))
3133 ig.Emit (OpCodes.Pop);
3136 if (Oper == Binary.Operator.BitwiseOr)
3137 ig.Emit (OpCodes.Or);
3138 else if (Oper == Binary.Operator.BitwiseAnd)
3139 ig.Emit (OpCodes.And);
3140 ig.Emit (OpCodes.Br, wrap_label);
3142 ig.MarkLabel (left_is_null_label);
3143 if (right_unwrap != null) {
3144 right_unwrap.EmitCheck (ec);
3145 ig.Emit (OpCodes.Brfalse, is_null_label);
3149 ig.Emit (OpCodes.Dup);
3150 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3151 ig.Emit (OpCodes.Brtrue, wrap_label);
3153 ig.Emit (OpCodes.Brfalse, wrap_label);
3155 ig.MarkLabel (right_is_null_label);
3156 ig.Emit (OpCodes.Pop);
3157 ig.MarkLabel (is_null_label);
3158 null_value.Emit (ec);
3159 ig.Emit (OpCodes.Br, end_label);
3161 ig.MarkLabel (wrap_label);
3162 ig.Emit (OpCodes.Nop);
3163 bool_wrap.Emit (ec);
3164 ig.Emit (OpCodes.Nop);
3166 ig.MarkLabel (end_label);
3169 void EmitEquality (EmitContext ec)
3171 ILGenerator ig = ec.ig;
3173 // Given 'X? x;' for any value type X: 'x != null' is the same as 'x.HasValue'
3174 if (left is NullLiteral) {
3175 if (right_unwrap == null)
3176 throw new InternalErrorException ();
3177 right_unwrap.EmitCheck (ec);
3178 if (Oper == Binary.Operator.Equality) {
3179 ig.Emit (OpCodes.Ldc_I4_0);
3180 ig.Emit (OpCodes.Ceq);
3185 if (right is NullLiteral) {
3186 if (left_unwrap == null)
3187 throw new InternalErrorException ();
3188 left_unwrap.EmitCheck (ec);
3189 if (Oper == Binary.Operator.Equality) {
3190 ig.Emit (OpCodes.Ldc_I4_0);
3191 ig.Emit (OpCodes.Ceq);
3196 Label both_have_value_label = ig.DefineLabel ();
3197 Label end_label = ig.DefineLabel ();
3199 if (left_unwrap != null && right_unwrap != null) {
3200 Label dissimilar_label = ig.DefineLabel ();
3202 left_unwrap.EmitCheck (ec);
3203 ig.Emit (OpCodes.Dup);
3204 right_unwrap.EmitCheck (ec);
3205 ig.Emit (OpCodes.Bne_Un, dissimilar_label);
3207 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3210 if (Oper == Binary.Operator.Equality)
3211 ig.Emit (OpCodes.Ldc_I4_1);
3213 ig.Emit (OpCodes.Ldc_I4_0);
3214 ig.Emit (OpCodes.Br, end_label);
3216 ig.MarkLabel (dissimilar_label);
3217 ig.Emit (OpCodes.Pop);
3218 } else if (left_unwrap != null) {
3219 left_unwrap.EmitCheck (ec);
3220 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3221 } else if (right_unwrap != null) {
3222 right_unwrap.EmitCheck (ec);
3223 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3225 throw new InternalErrorException ("shouldn't get here");
3228 // one is null while the other isn't
3229 if (Oper == Binary.Operator.Equality)
3230 ig.Emit (OpCodes.Ldc_I4_0);
3232 ig.Emit (OpCodes.Ldc_I4_1);
3233 ig.Emit (OpCodes.Br, end_label);
3235 ig.MarkLabel (both_have_value_label);
3236 underlying.Emit (ec);
3238 ig.MarkLabel (end_label);
3241 void EmitComparision (EmitContext ec)
3243 ILGenerator ig = ec.ig;
3245 Label is_null_label = ig.DefineLabel ();
3246 Label end_label = ig.DefineLabel ();
3248 if (left_unwrap != null) {
3249 left_unwrap.EmitCheck (ec);
3250 ig.Emit (OpCodes.Brfalse, is_null_label);
3253 if (right_unwrap != null) {
3254 right_unwrap.EmitCheck (ec);
3255 ig.Emit (OpCodes.Brfalse, is_null_label);
3258 underlying.Emit (ec);
3259 ig.Emit (OpCodes.Br, end_label);
3261 ig.MarkLabel (is_null_label);
3262 ig.Emit (OpCodes.Ldc_I4_0);
3264 ig.MarkLabel (end_label);
3267 public override void Emit (EmitContext ec)
3269 if (left_unwrap != null)
3270 left_unwrap.Store (ec);
3271 if (right_unwrap != null)
3272 right_unwrap.Store (ec);
3277 } else if (is_equality) {
3280 } else if (is_comparision) {
3281 EmitComparision (ec);
3285 ILGenerator ig = ec.ig;
3287 Label is_null_label = ig.DefineLabel ();
3288 Label end_label = ig.DefineLabel ();
3290 if (left_unwrap != null) {
3291 left_unwrap.EmitCheck (ec);
3292 ig.Emit (OpCodes.Brfalse, is_null_label);
3295 if (right_unwrap != null) {
3296 right_unwrap.EmitCheck (ec);
3297 ig.Emit (OpCodes.Brfalse, is_null_label);
3300 underlying.Emit (ec);
3301 ig.Emit (OpCodes.Br, end_label);
3303 ig.MarkLabel (is_null_label);
3304 null_value.Emit (ec);
3306 ig.MarkLabel (end_label);
3310 public class OperatorTrueOrFalse : Expression
3312 public readonly bool IsTrue;
3317 public OperatorTrueOrFalse (Expression expr, bool is_true, Location loc)
3319 this.IsTrue = is_true;
3324 public override Expression DoResolve (EmitContext ec)
3326 unwrap = Unwrap.Create (expr, ec);
3330 if (unwrap.Type != TypeManager.bool_type)
3333 type = TypeManager.bool_type;
3334 eclass = ExprClass.Value;
3338 public override void Emit (EmitContext ec)
3340 ILGenerator ig = ec.ig;
3342 Label is_null_label = ig.DefineLabel ();
3343 Label end_label = ig.DefineLabel ();
3345 unwrap.EmitCheck (ec);
3346 ig.Emit (OpCodes.Brfalse, is_null_label);
3350 ig.Emit (OpCodes.Ldc_I4_0);
3351 ig.Emit (OpCodes.Ceq);
3353 ig.Emit (OpCodes.Br, end_label);
3355 ig.MarkLabel (is_null_label);
3356 ig.Emit (OpCodes.Ldc_I4_0);
3358 ig.MarkLabel (end_label);
3362 public class NullCoalescingOperator : Expression
3364 Expression left, right;
3368 public NullCoalescingOperator (Expression left, Expression right, Location loc)
3374 eclass = ExprClass.Value;
3377 public override Expression DoResolve (EmitContext ec)
3382 left = left.Resolve (ec);
3386 right = right.Resolve (ec);
3390 Type ltype = left.Type, rtype = right.Type;
3392 if (!TypeManager.IsNullableType (ltype) && ltype.IsValueType) {
3393 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3397 if (TypeManager.IsNullableType (ltype)) {
3398 NullableInfo info = new NullableInfo (ltype);
3400 unwrap = Unwrap.Create (left, ec);
3404 expr = Convert.ImplicitConversion (ec, right, info.UnderlyingType, loc);
3412 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
3418 if (unwrap != null) {
3419 expr = Convert.ImplicitConversion (ec, unwrap, rtype, loc);
3428 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3432 public override void Emit (EmitContext ec)
3434 ILGenerator ig = ec.ig;
3436 Label is_null_label = ig.DefineLabel ();
3437 Label end_label = ig.DefineLabel ();
3439 if (unwrap != null) {
3440 unwrap.EmitCheck (ec);
3441 ig.Emit (OpCodes.Brfalse, is_null_label);
3444 ig.Emit (OpCodes.Br, end_label);
3446 ig.MarkLabel (is_null_label);
3449 ig.MarkLabel (end_label);
3452 ig.Emit (OpCodes.Dup);
3453 ig.Emit (OpCodes.Brtrue, end_label);
3455 ig.MarkLabel (is_null_label);
3457 ig.Emit (OpCodes.Pop);
3460 ig.MarkLabel (end_label);
3465 public class LiftedUnaryMutator : ExpressionStatement
3467 public readonly UnaryMutator.Mode Mode;
3468 Expression expr, null_value;
3469 UnaryMutator underlying;
3472 public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
3478 eclass = ExprClass.Value;
3481 public override Expression DoResolve (EmitContext ec)
3483 expr = expr.Resolve (ec);
3487 unwrap = Unwrap.Create (expr, ec);
3491 underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
3492 if (underlying == null)
3495 null_value = new NullableLiteral (expr.Type, loc).Resolve (ec);
3496 if (null_value == null)
3503 void DoEmit (EmitContext ec, bool is_expr)
3505 ILGenerator ig = ec.ig;
3506 Label is_null_label = ig.DefineLabel ();
3507 Label end_label = ig.DefineLabel ();
3509 unwrap.EmitCheck (ec);
3510 ig.Emit (OpCodes.Brfalse, is_null_label);
3513 underlying.Emit (ec);
3515 underlying.EmitStatement (ec);
3516 ig.Emit (OpCodes.Br, end_label);
3518 ig.MarkLabel (is_null_label);
3520 null_value.Emit (ec);
3522 ig.MarkLabel (end_label);
3525 public override void Emit (EmitContext ec)
3530 public override void EmitStatement (EmitContext ec)