2 // generic.cs: Generics support
4 // Authors: Martin Baulig (martin@ximian.com)
5 // Miguel de Icaza (miguel@ximian.com)
7 // Licensed under the terms of the GNU GPL
9 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
10 // (C) 2004 Novell, Inc
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.Globalization;
16 using System.Collections;
18 using System.Text.RegularExpressions;
20 namespace Mono.CSharp {
23 /// Abstract base class for type parameter constraints.
24 /// The type parameter can come from a generic type definition or from reflection.
26 public abstract class GenericConstraints {
27 public abstract string TypeParameter {
31 public abstract GenericParameterAttributes Attributes {
35 public bool HasConstructorConstraint {
36 get { return (Attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0; }
39 public bool HasReferenceTypeConstraint {
40 get { return (Attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0; }
43 public bool HasValueTypeConstraint {
44 get { return (Attributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0; }
47 public virtual bool HasClassConstraint {
48 get { return ClassConstraint != null; }
51 public abstract Type ClassConstraint {
55 public abstract Type[] InterfaceConstraints {
59 public abstract Type EffectiveBaseClass {
64 // Returns whether the type parameter is "known to be a reference type".
66 public virtual bool IsReferenceType {
68 if (HasReferenceTypeConstraint)
70 if (HasValueTypeConstraint)
73 if (ClassConstraint != null) {
74 if (ClassConstraint.IsValueType)
77 if (ClassConstraint != TypeManager.object_type)
81 foreach (Type t in InterfaceConstraints) {
82 if (!t.IsGenericParameter)
85 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
86 if ((gc != null) && gc.IsReferenceType)
95 // Returns whether the type parameter is "known to be a value type".
97 public virtual bool IsValueType {
99 if (HasValueTypeConstraint)
101 if (HasReferenceTypeConstraint)
104 if (ClassConstraint != null) {
105 if (!ClassConstraint.IsValueType)
108 if (ClassConstraint != TypeManager.value_type)
112 foreach (Type t in InterfaceConstraints) {
113 if (!t.IsGenericParameter)
116 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
117 if ((gc != null) && gc.IsValueType)
126 public enum SpecialConstraint
134 /// Tracks the constraints for a type parameter from a generic type definition.
136 public class Constraints : GenericConstraints {
138 ArrayList constraints;
142 // name is the identifier, constraints is an arraylist of
143 // Expressions (with types) or `true' for the constructor constraint.
145 public Constraints (string name, ArrayList constraints,
149 this.constraints = constraints;
153 public override string TypeParameter {
159 GenericParameterAttributes attrs;
160 TypeExpr class_constraint;
161 ArrayList iface_constraints;
162 ArrayList type_param_constraints;
164 Type class_constraint_type;
165 Type[] iface_constraint_types;
166 Type effective_base_type;
171 /// Resolve the constraints - but only resolve things into Expression's, not
172 /// into actual types.
174 public bool Resolve (EmitContext ec)
179 iface_constraints = new ArrayList ();
180 type_param_constraints = new ArrayList ();
182 foreach (object obj in constraints) {
183 if (HasConstructorConstraint) {
184 Report.Error (401, loc,
185 "The new() constraint must be last.");
189 if (obj is SpecialConstraint) {
190 SpecialConstraint sc = (SpecialConstraint) obj;
192 if (sc == SpecialConstraint.Constructor) {
193 if (!HasValueTypeConstraint) {
194 attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
199 451, loc, "The new () constraint " +
200 "cannot be used with the `struct' " +
205 if ((num_constraints > 0) || HasReferenceTypeConstraint || HasValueTypeConstraint) {
206 Report.Error (449, loc,
207 "The `class' or `struct' " +
208 "constraint must be first");
212 if (sc == SpecialConstraint.ReferenceType)
213 attrs |= GenericParameterAttributes.ReferenceTypeConstraint;
215 attrs |= GenericParameterAttributes.NotNullableValueTypeConstraint;
219 int errors = Report.Errors;
220 FullNamedExpression fn = ((Expression) obj).ResolveAsTypeStep (ec);
223 if (errors != Report.Errors)
226 Report.Error (246, loc, "Cannot find type '{0}'", ((Expression) obj).GetSignatureForError ());
231 ConstructedType cexpr = fn as ConstructedType;
233 if (!cexpr.ResolveConstructedType (ec))
238 expr = fn.ResolveAsTypeTerminal (ec);
240 if ((expr == null) || (expr.Type == null))
243 TypeParameterExpr texpr = expr as TypeParameterExpr;
245 type_param_constraints.Add (expr);
246 else if (expr.IsInterface)
247 iface_constraints.Add (expr);
248 else if (class_constraint != null) {
249 Report.Error (406, loc,
250 "`{0}': the class constraint for `{1}' " +
251 "must come before any other constraints.",
254 } else if (HasReferenceTypeConstraint || HasValueTypeConstraint) {
255 Report.Error (450, loc, "`{0}': cannot specify both " +
256 "a constraint class and the `class' " +
257 "or `struct' constraint.", expr.Name);
260 class_constraint = expr;
265 ArrayList list = new ArrayList ();
266 foreach (TypeExpr iface_constraint in iface_constraints) {
267 foreach (Type type in list) {
268 if (!type.Equals (iface_constraint.Type))
271 Report.Error (405, loc,
272 "Duplicate constraint `{0}' for type " +
273 "parameter `{1}'.", iface_constraint.GetSignatureForError (),
278 list.Add (iface_constraint.Type);
281 foreach (TypeParameterExpr expr in type_param_constraints) {
282 foreach (Type type in list) {
283 if (!type.Equals (expr.Type))
286 Report.Error (405, loc,
287 "Duplicate constraint `{0}' for type " +
288 "parameter `{1}'.", expr.GetSignatureForError (), name);
292 list.Add (expr.Type);
295 iface_constraint_types = new Type [list.Count];
296 list.CopyTo (iface_constraint_types, 0);
298 if (class_constraint != null) {
299 class_constraint_type = class_constraint.Type;
300 if (class_constraint_type == null)
303 if (class_constraint_type.IsSealed) {
304 Report.Error (701, loc,
305 "`{0}' is not a valid bound. Bounds " +
306 "must be interfaces or non sealed " +
307 "classes", TypeManager.CSharpName (class_constraint_type));
311 if ((class_constraint_type == TypeManager.array_type) ||
312 (class_constraint_type == TypeManager.delegate_type) ||
313 (class_constraint_type == TypeManager.enum_type) ||
314 (class_constraint_type == TypeManager.value_type) ||
315 (class_constraint_type == TypeManager.object_type)) {
316 Report.Error (702, loc,
317 "Bound cannot be special class `{0}'",
318 TypeManager.CSharpName (class_constraint_type));
323 if (class_constraint_type != null)
324 effective_base_type = class_constraint_type;
325 else if (HasValueTypeConstraint)
326 effective_base_type = TypeManager.value_type;
328 effective_base_type = TypeManager.object_type;
334 bool CheckTypeParameterConstraints (TypeParameter tparam, Hashtable seen)
336 seen.Add (tparam, true);
338 Constraints constraints = tparam.Constraints;
339 if (constraints == null)
342 if (constraints.HasValueTypeConstraint) {
343 Report.Error (456, loc, "Type parameter `{0}' has " +
344 "the `struct' constraint, so it cannot " +
345 "be used as a constraint for `{1}'",
350 if (constraints.type_param_constraints == null)
353 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
354 if (seen.Contains (expr.TypeParameter)) {
355 Report.Error (454, loc, "Circular constraint " +
356 "dependency involving `{0}' and `{1}'",
357 tparam.Name, expr.Name);
361 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
369 /// Resolve the constraints into actual types.
371 public bool ResolveTypes (EmitContext ec)
376 resolved_types = true;
378 foreach (object obj in constraints) {
379 ConstructedType cexpr = obj as ConstructedType;
383 if (!cexpr.CheckConstraints (ec))
387 foreach (TypeParameterExpr expr in type_param_constraints) {
388 Hashtable seen = new Hashtable ();
389 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
393 foreach (TypeExpr iface_constraint in iface_constraints) {
394 if (iface_constraint.ResolveType (ec) == null)
398 if (class_constraint != null) {
399 if (class_constraint.ResolveType (ec) == null)
407 /// Check whether there are no conflicts in our type parameter constraints.
409 /// This is an example:
413 /// where U : T, struct
415 public bool CheckDependencies (EmitContext ec)
417 foreach (TypeParameterExpr expr in type_param_constraints) {
418 if (!CheckDependencies (expr.TypeParameter, ec))
425 bool CheckDependencies (TypeParameter tparam, EmitContext ec)
427 Constraints constraints = tparam.Constraints;
428 if (constraints == null)
431 if (HasValueTypeConstraint && constraints.HasClassConstraint) {
432 Report.Error (455, loc, "Type parameter `{0}' inherits " +
433 "conflicting constraints `{1}' and `{2}'",
434 name, TypeManager.CSharpName (constraints.ClassConstraint),
439 if (HasClassConstraint && constraints.HasClassConstraint) {
440 Type t1 = ClassConstraint;
441 TypeExpr e1 = class_constraint;
442 Type t2 = constraints.ClassConstraint;
443 TypeExpr e2 = constraints.class_constraint;
445 if (!Convert.ImplicitReferenceConversionExists (ec, e1, t2) &&
446 !Convert.ImplicitReferenceConversionExists (ec, e2, t1)) {
447 Report.Error (455, loc,
448 "Type parameter `{0}' inherits " +
449 "conflicting constraints `{1}' and `{2}'",
450 name, TypeManager.CSharpName (t1), TypeManager.CSharpName (t2));
455 if (constraints.type_param_constraints == null)
458 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
459 if (!CheckDependencies (expr.TypeParameter, ec))
466 public override GenericParameterAttributes Attributes {
467 get { return attrs; }
470 public override bool HasClassConstraint {
471 get { return class_constraint != null; }
474 public override Type ClassConstraint {
475 get { return class_constraint_type; }
478 public override Type[] InterfaceConstraints {
479 get { return iface_constraint_types; }
482 public override Type EffectiveBaseClass {
483 get { return effective_base_type; }
486 public bool IsSubclassOf (Type t)
488 if ((class_constraint_type != null) &&
489 class_constraint_type.IsSubclassOf (t))
492 if (iface_constraint_types == null)
495 foreach (Type iface in iface_constraint_types) {
496 if (TypeManager.IsSubclassOf (iface, t))
504 /// This is used when we're implementing a generic interface method.
505 /// Each method type parameter in implementing method must have the same
506 /// constraints than the corresponding type parameter in the interface
507 /// method. To do that, we're called on each of the implementing method's
510 public bool CheckInterfaceMethod (EmitContext ec, GenericConstraints gc)
512 if (gc.Attributes != attrs)
515 if (HasClassConstraint != gc.HasClassConstraint)
517 if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
520 int gc_icount = gc.InterfaceConstraints != null ?
521 gc.InterfaceConstraints.Length : 0;
522 int icount = InterfaceConstraints != null ?
523 InterfaceConstraints.Length : 0;
525 if (gc_icount != icount)
528 foreach (Type iface in gc.InterfaceConstraints) {
530 foreach (Type check in InterfaceConstraints) {
531 if (TypeManager.IsEqual (iface, check)) {
546 /// A type parameter from a generic type definition.
548 public class TypeParameter : MemberCore, IMemberContainer {
551 GenericConstraints gc;
552 Constraints constraints;
554 GenericTypeParameterBuilder type;
556 public TypeParameter (DeclSpace parent, DeclSpace decl, string name,
557 Constraints constraints, Attributes attrs, Location loc)
558 : base (parent, new MemberName (name, loc), attrs)
562 this.constraints = constraints;
566 public GenericConstraints GenericConstraints {
568 return gc != null ? gc : constraints;
572 public Constraints Constraints {
578 public bool HasConstructorConstraint {
580 if (constraints != null)
581 return constraints.HasConstructorConstraint;
587 public DeclSpace DeclSpace {
600 /// This is the first method which is called during the resolving
601 /// process; we're called immediately after creating the type parameters
602 /// with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
605 /// We're either called from TypeContainer.DefineType() or from
606 /// GenericMethod.Define() (called from Method.Define()).
608 public void Define (GenericTypeParameterBuilder type)
610 if (this.type != null)
611 throw new InvalidOperationException ();
614 TypeManager.AddTypeParameter (type, this);
618 /// This is the second method which is called during the resolving
619 /// process - in case of class type parameters, we're called from
620 /// TypeContainer.ResolveType() - after it resolved the class'es
621 /// base class and interfaces. For method type parameters, we're
622 /// called immediately after Define().
624 /// We're just resolving the constraints into expressions here, we
625 /// don't resolve them into actual types.
627 /// Note that in the special case of partial generic classes, we may be
628 /// called _before_ Define() and we may also be called multiple types.
630 public bool Resolve (DeclSpace ds)
632 if (constraints != null) {
633 if (!constraints.Resolve (ds.EmitContext)) {
643 /// This is the third method which is called during the resolving
644 /// process. We're called immediately after calling DefineConstraints()
645 /// on all of the current class'es type parameters.
647 /// Our job is to resolve the constraints to actual types.
649 /// Note that we may have circular dependencies on type parameters - this
650 /// is why Resolve() and ResolveType() are separate.
652 public bool ResolveType (EmitContext ec)
654 if (constraints != null) {
655 if (!constraints.ResolveTypes (ec)) {
665 /// This is the fourth and last method which is called during the resolving
666 /// process. We're called after everything is fully resolved and actually
667 /// register the constraints with SRE and the TypeManager.
669 public bool DefineType (EmitContext ec)
671 return DefineType (ec, null, null, false);
675 /// This is the fith and last method which is called during the resolving
676 /// process. We're called after everything is fully resolved and actually
677 /// register the constraints with SRE and the TypeManager.
679 /// The `builder', `implementing' and `is_override' arguments are only
680 /// applicable to method type parameters.
682 public bool DefineType (EmitContext ec, MethodBuilder builder,
683 MethodInfo implementing, bool is_override)
685 if (!ResolveType (ec))
688 if (implementing != null) {
689 if (is_override && (constraints != null)) {
691 460, loc, "Constraints for override and " +
692 "explicit interface implementation methods " +
693 "are inherited from the base method so they " +
694 "cannot be specified directly");
698 MethodBase mb = TypeManager.DropGenericMethodArguments (implementing);
700 int pos = type.GenericParameterPosition;
701 Type mparam = mb.GetGenericArguments () [pos];
702 GenericConstraints temp_gc = ReflectionConstraints.GetConstraints (mparam);
705 gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
706 else if (constraints != null)
707 gc = new InflatedConstraints (constraints, implementing.DeclaringType);
710 if (constraints != null) {
713 else if (!constraints.CheckInterfaceMethod (ec, gc))
716 if (!is_override && (temp_gc != null))
721 Report.SymbolRelatedToPreviousError (implementing);
724 425, loc, "The constraints for type " +
725 "parameter `{0}' of method `{1}' must match " +
726 "the constraints for type parameter `{2}' " +
727 "of interface method `{3}'. Consider using " +
728 "an explicit interface implementation instead",
729 Name, TypeManager.CSharpSignature (builder),
730 TypeManager.CSharpName (mparam), TypeManager.CSharpSignature (mb));
733 } else if (DeclSpace is Iterator) {
734 TypeParameter[] tparams = DeclSpace.TypeParameters;
735 Type[] types = new Type [tparams.Length];
736 for (int i = 0; i < tparams.Length; i++)
737 types [i] = tparams [i].Type;
739 if (constraints != null)
740 gc = new InflatedConstraints (constraints, types);
742 gc = (GenericConstraints) constraints;
748 if (gc.HasClassConstraint)
749 type.SetBaseTypeConstraint (gc.ClassConstraint);
751 type.SetInterfaceConstraints (gc.InterfaceConstraints);
752 type.SetGenericParameterAttributes (gc.Attributes);
753 TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
759 /// Check whether there are no conflicts in our type parameter constraints.
761 /// This is an example:
765 /// where U : T, struct
767 public bool CheckDependencies (EmitContext ec)
769 if (constraints != null)
770 return constraints.CheckDependencies (ec);
776 /// This is called for each part of a partial generic type definition.
778 /// If `new_constraints' is not null and we don't already have constraints,
779 /// they become our constraints. If we already have constraints, we must
780 /// check that they're the same.
783 public bool UpdateConstraints (EmitContext ec, Constraints new_constraints)
786 throw new InvalidOperationException ();
788 if (constraints == null) {
789 new_constraints = constraints;
791 } else if (new_constraints == null)
794 if (!new_constraints.Resolve (ec))
796 if (!new_constraints.ResolveTypes (ec))
799 return constraints.CheckInterfaceMethod (ec, new_constraints);
802 public void EmitAttributes (EmitContext ec)
804 if (OptAttributes != null)
805 OptAttributes.Emit (ec, this);
808 public override string DocCommentHeader {
810 throw new InvalidOperationException (
811 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
819 public override bool Define ()
824 public override void ApplyAttributeBuilder (Attribute a,
825 CustomAttributeBuilder cb)
827 type.SetCustomAttribute (cb);
830 public override AttributeTargets AttributeTargets {
832 return (AttributeTargets) AttributeTargets.GenericParameter;
836 public override string[] ValidAttributeTargets {
838 return new string [] { "type parameter" };
846 string IMemberContainer.Name {
850 MemberCache IMemberContainer.BaseCache {
854 bool IMemberContainer.IsInterface {
858 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
860 return FindMembers (mt, bf, null, null);
863 MemberCache IMemberContainer.MemberCache {
867 public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
868 MemberFilter filter, object criteria)
870 if (constraints == null)
871 return MemberList.Empty;
873 ArrayList members = new ArrayList ();
875 if (gc.HasClassConstraint) {
876 MemberList list = TypeManager.FindMembers (
877 gc.ClassConstraint, mt, bf, filter, criteria);
879 members.AddRange (list);
882 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
883 foreach (Type t in ifaces) {
884 MemberList list = TypeManager.FindMembers (
885 t, mt, bf, filter, criteria);
887 members.AddRange (list);
890 return new MemberList (members);
893 public bool IsSubclassOf (Type t)
898 if (constraints != null)
899 return constraints.IsSubclassOf (t);
904 public override string ToString ()
906 return "TypeParameter[" + name + "]";
909 public static string GetSignatureForError (TypeParameter[] tp)
911 if (tp == null || tp.Length == 0)
914 StringBuilder sb = new StringBuilder ("<");
915 for (int i = 0; i < tp.Length; ++i) {
918 sb.Append (tp[i].GetSignatureForError ());
921 return sb.ToString ();
924 public void InflateConstraints (Type declaring)
926 if (constraints != null)
927 gc = new InflatedConstraints (constraints, declaring);
930 protected class InflatedConstraints : GenericConstraints
932 GenericConstraints gc;
934 Type class_constraint;
935 Type[] iface_constraints;
938 public InflatedConstraints (GenericConstraints gc, Type declaring)
939 : this (gc, TypeManager.GetTypeArguments (declaring))
942 public InflatedConstraints (GenericConstraints gc, Type[] dargs)
947 ArrayList list = new ArrayList ();
948 if (gc.HasClassConstraint)
949 list.Add (inflate (gc.ClassConstraint));
950 foreach (Type iface in gc.InterfaceConstraints)
951 list.Add (inflate (iface));
953 bool has_class_constr = false;
954 if (list.Count > 0) {
955 Type first = (Type) list [0];
956 has_class_constr = !first.IsInterface && !first.IsGenericParameter;
959 if ((list.Count > 0) && has_class_constr) {
960 class_constraint = (Type) list [0];
961 iface_constraints = new Type [list.Count - 1];
962 list.CopyTo (1, iface_constraints, 0, list.Count - 1);
964 iface_constraints = new Type [list.Count];
965 list.CopyTo (iface_constraints, 0);
968 if (HasValueTypeConstraint)
969 base_type = TypeManager.value_type;
970 else if (class_constraint != null)
971 base_type = class_constraint;
973 base_type = TypeManager.object_type;
976 Type inflate (Type t)
980 if (t.IsGenericParameter)
981 return dargs [t.GenericParameterPosition];
982 if (t.IsGenericInstance) {
983 t = t.GetGenericTypeDefinition ();
984 t = t.MakeGenericType (dargs);
990 public override string TypeParameter {
991 get { return gc.TypeParameter; }
994 public override GenericParameterAttributes Attributes {
995 get { return gc.Attributes; }
998 public override Type ClassConstraint {
999 get { return class_constraint; }
1002 public override Type EffectiveBaseClass {
1003 get { return base_type; }
1006 public override Type[] InterfaceConstraints {
1007 get { return iface_constraints; }
1013 /// A TypeExpr which already resolved to a type parameter.
1015 public class TypeParameterExpr : TypeExpr {
1016 TypeParameter type_parameter;
1018 public override string Name {
1020 return type_parameter.Name;
1024 public override string FullName {
1026 return type_parameter.Name;
1030 public TypeParameter TypeParameter {
1032 return type_parameter;
1036 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1038 this.type_parameter = type_parameter;
1042 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
1044 type = type_parameter.Type;
1049 public override bool IsInterface {
1050 get { return false; }
1053 public override bool CheckAccessLevel (DeclSpace ds)
1058 public void Error_CannotUseAsUnmanagedType (Location loc)
1060 Report.Error (-203, loc, "Can not use type parameter as unamanged type");
1065 /// Tracks the type arguments when instantiating a generic type. We're used in
1066 /// ConstructedType.
1068 public class TypeArguments {
1069 public readonly Location Location;
1076 public TypeArguments (Location loc)
1078 args = new ArrayList ();
1079 this.Location = loc;
1082 public TypeArguments (int dimension, Location loc)
1084 this.dimension = dimension;
1085 this.Location = loc;
1088 public void Add (Expression type)
1091 throw new InvalidOperationException ();
1096 public void Add (TypeArguments new_args)
1099 throw new InvalidOperationException ();
1101 args.AddRange (new_args.args);
1105 /// We're used during the parsing process: the parser can't distinguish
1106 /// between type parameters and type arguments. Because of that, the
1107 /// parser creates a `MemberName' with `TypeArguments' for both cases and
1108 /// in case of a generic type definition, we call GetDeclarations().
1110 public TypeParameterName[] GetDeclarations ()
1112 TypeParameterName[] ret = new TypeParameterName [args.Count];
1113 for (int i = 0; i < args.Count; i++) {
1114 TypeParameterName name = args [i] as TypeParameterName;
1119 SimpleName sn = args [i] as SimpleName;
1121 ret [i] = new TypeParameterName (sn.Name, null, sn.Location);
1125 Report.Error (81, Location, "Type parameter declaration " +
1126 "must be an identifier not a type");
1133 /// We may only be used after Resolve() is called and return the fully
1136 public Type[] Arguments {
1142 public bool HasTypeArguments {
1144 return has_type_args;
1157 public bool IsUnbound {
1159 return dimension > 0;
1163 public override string ToString ()
1165 StringBuilder s = new StringBuilder ();
1168 for (int i = 0; i < count; i++){
1170 // FIXME: Use TypeManager.CSharpname once we have the type
1173 s.Append (args [i].ToString ());
1177 return s.ToString ();
1181 /// Resolve the type arguments.
1183 public bool Resolve (EmitContext ec)
1185 int count = args.Count;
1188 atypes = new Type [count];
1190 for (int i = 0; i < count; i++){
1191 TypeExpr te = ((Expression) args [i]).ResolveAsTypeTerminal (ec);
1196 if (te is TypeParameterExpr)
1197 has_type_args = true;
1199 if (te.Type.IsPointer) {
1200 Report.Error (306, Location, "The type `{0}' may not be used " +
1201 "as a type argument.", TypeManager.CSharpName (te.Type));
1203 } else if (te.Type == TypeManager.void_type) {
1204 Report.Error (1547, Location,
1205 "Keyword `void' cannot be used in this context");
1209 atypes [i] = te.Type;
1215 public class TypeParameterName : SimpleName
1217 Attributes attributes;
1219 public TypeParameterName (string name, Attributes attrs, Location loc)
1225 public Attributes OptAttributes {
1233 /// An instantiation of a generic type.
1235 public class ConstructedType : TypeExpr {
1237 FullNamedExpression name;
1239 Type[] gen_params, atypes;
1243 /// Instantiate the generic type `fname' with the type arguments `args'.
1245 public ConstructedType (FullNamedExpression fname, TypeArguments args, Location l)
1251 eclass = ExprClass.Type;
1252 full_name = name + "<" + args.ToString () + ">";
1255 protected ConstructedType (TypeArguments args, Location l)
1260 eclass = ExprClass.Type;
1263 protected ConstructedType (TypeParameter[] type_params, Location l)
1267 args = new TypeArguments (l);
1268 foreach (TypeParameter type_param in type_params)
1269 args.Add (new TypeParameterExpr (type_param, l));
1271 eclass = ExprClass.Type;
1275 /// This is used to construct the `this' type inside a generic type definition.
1277 public ConstructedType (Type t, TypeParameter[] type_params, Location l)
1278 : this (type_params, l)
1280 gt = t.GetGenericTypeDefinition ();
1282 this.name = new TypeExpression (gt, l);
1283 full_name = gt.FullName + "<" + args.ToString () + ">";
1287 /// Instantiate the generic type `t' with the type arguments `args'.
1288 /// Use this constructor if you already know the fully resolved
1291 public ConstructedType (Type t, TypeArguments args, Location l)
1294 gt = t.GetGenericTypeDefinition ();
1296 this.name = new TypeExpression (gt, l);
1297 full_name = gt.FullName + "<" + args.ToString () + ">";
1300 public TypeArguments TypeArguments {
1301 get { return args; }
1304 public override string GetSignatureForError ()
1306 return TypeManager.CSharpName (gt);
1309 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
1311 if (!ResolveConstructedType (ec))
1318 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1319 /// after fully resolving the constructed type.
1321 public bool CheckConstraints (EmitContext ec)
1323 return ConstraintChecker.CheckConstraints (ec, gt, gen_params, atypes, loc);
1327 /// Resolve the constructed type, but don't check the constraints.
1329 public bool ResolveConstructedType (EmitContext ec)
1333 // If we already know the fully resolved generic type.
1335 return DoResolveType (ec);
1341 Report.Error (246, loc, "Cannot find type `{0}'<...>", Name);
1345 num_args = TypeManager.GetNumberOfTypeArguments (t);
1346 if (num_args == 0) {
1347 Report.Error (308, loc,
1348 "The non-generic type `{0}' cannot " +
1349 "be used with type arguments.",
1350 TypeManager.CSharpName (t));
1354 gt = t.GetGenericTypeDefinition ();
1355 return DoResolveType (ec);
1358 bool DoResolveType (EmitContext ec)
1361 // Resolve the arguments.
1363 if (args.Resolve (ec) == false)
1366 gen_params = gt.GetGenericArguments ();
1367 atypes = args.Arguments;
1369 if (atypes.Length != gen_params.Length) {
1370 Report.Error (305, loc,
1371 "Using the generic type `{0}' " +
1372 "requires {1} type arguments",
1373 TypeManager.CSharpName (gt),
1374 gen_params.Length.ToString ());
1379 // Now bind the parameters.
1381 type = gt.MakeGenericType (atypes);
1385 public Expression GetSimpleName (EmitContext ec)
1390 public override bool CheckAccessLevel (DeclSpace ds)
1392 return ds.CheckAccessLevel (gt);
1395 public override bool AsAccessible (DeclSpace ds, int flags)
1397 return ds.AsAccessible (gt, flags);
1400 public override bool IsClass {
1401 get { return gt.IsClass; }
1404 public override bool IsValueType {
1405 get { return gt.IsValueType; }
1408 public override bool IsInterface {
1409 get { return gt.IsInterface; }
1412 public override bool IsSealed {
1413 get { return gt.IsSealed; }
1416 public override bool Equals (object obj)
1418 ConstructedType cobj = obj as ConstructedType;
1422 if ((type == null) || (cobj.type == null))
1425 return type == cobj.type;
1428 public override int GetHashCode ()
1430 return base.GetHashCode ();
1433 public override string Name {
1440 public override string FullName {
1447 public abstract class ConstraintChecker
1449 protected readonly Type[] gen_params;
1450 protected readonly Type[] atypes;
1451 protected readonly Location loc;
1453 protected ConstraintChecker (Type[] gen_params, Type[] atypes, Location loc)
1455 this.gen_params = gen_params;
1456 this.atypes = atypes;
1461 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1462 /// after fully resolving the constructed type.
1464 public bool CheckConstraints (EmitContext ec)
1466 for (int i = 0; i < gen_params.Length; i++) {
1467 if (!CheckConstraints (ec, i))
1474 protected bool CheckConstraints (EmitContext ec, int index)
1476 Type atype = atypes [index];
1477 Type ptype = gen_params [index];
1482 Expression aexpr = new EmptyExpression (atype);
1484 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1488 bool is_class, is_struct;
1489 if (atype.IsGenericParameter) {
1490 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1492 is_class = agc.HasReferenceTypeConstraint;
1493 is_struct = agc.HasValueTypeConstraint;
1495 is_class = is_struct = false;
1498 is_class = atype.IsClass || atype.IsInterface;
1499 is_struct = atype.IsValueType && !TypeManager.IsNullableType (atype);
1503 // First, check the `class' and `struct' constraints.
1505 if (gc.HasReferenceTypeConstraint && !is_class) {
1506 Report.Error (452, loc, "The type `{0}' must be " +
1507 "a reference type in order to use it " +
1508 "as type parameter `{1}' in the " +
1509 "generic type or method `{2}'.",
1510 TypeManager.CSharpName (atype),
1511 TypeManager.CSharpName (ptype),
1512 GetSignatureForError ());
1514 } else if (gc.HasValueTypeConstraint && !is_struct) {
1515 Report.Error (453, loc, "The type `{0}' must be a " +
1516 "non-nullable value type in order to use it " +
1517 "as type parameter `{1}' in the " +
1518 "generic type or method `{2}'.",
1519 TypeManager.CSharpName (atype),
1520 TypeManager.CSharpName (ptype),
1521 GetSignatureForError ());
1526 // The class constraint comes next.
1528 if (gc.HasClassConstraint) {
1529 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint))
1534 // Now, check the interface constraints.
1536 foreach (Type it in gc.InterfaceConstraints) {
1537 if (!CheckConstraint (ec, ptype, aexpr, it))
1542 // Finally, check the constructor constraint.
1545 if (!gc.HasConstructorConstraint)
1548 if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
1551 if (HasDefaultConstructor (ec, atype))
1554 Report_SymbolRelatedToPreviousError ();
1555 Report.SymbolRelatedToPreviousError (atype);
1556 Report.Error (310, loc, "The type `{0}' must have a public " +
1557 "parameterless constructor in order to use it " +
1558 "as parameter `{1}' in the generic type or " +
1560 TypeManager.CSharpName (atype),
1561 TypeManager.CSharpName (ptype),
1562 GetSignatureForError ());
1566 protected bool CheckConstraint (EmitContext ec, Type ptype, Expression expr,
1569 if (TypeManager.HasGenericArguments (ctype)) {
1570 Type[] types = TypeManager.GetTypeArguments (ctype);
1572 TypeArguments new_args = new TypeArguments (loc);
1574 for (int i = 0; i < types.Length; i++) {
1577 if (t.IsGenericParameter) {
1578 int pos = t.GenericParameterPosition;
1581 new_args.Add (new TypeExpression (t, loc));
1584 TypeExpr ct = new ConstructedType (ctype, new_args, loc);
1585 if (ct.ResolveAsTypeStep (ec) == null)
1588 } else if (ctype.IsGenericParameter) {
1589 int pos = ctype.GenericParameterPosition;
1590 ctype = atypes [pos];
1593 if (Convert.ImplicitStandardConversionExists (ec, expr, ctype))
1596 Error_TypeMustBeConvertible (expr.Type, ctype, ptype);
1600 bool HasDefaultConstructor (EmitContext ec, Type atype)
1602 if (atype is TypeBuilder) {
1603 if (atype.IsAbstract)
1606 TypeContainer tc = TypeManager.LookupTypeContainer (atype);
1607 foreach (Constructor c in tc.InstanceConstructors) {
1608 if ((c.ModFlags & Modifiers.PUBLIC) == 0)
1610 if ((c.Parameters.FixedParameters != null) &&
1611 (c.Parameters.FixedParameters.Length != 0))
1613 if (c.Parameters.HasArglist || c.Parameters.HasParams)
1620 MethodGroupExpr mg = Expression.MemberLookup (
1621 ec, atype, ".ctor", MemberTypes.Constructor,
1622 BindingFlags.Public | BindingFlags.Instance |
1623 BindingFlags.DeclaredOnly, loc)
1626 if (!atype.IsAbstract && (mg != null) && mg.IsInstance) {
1627 foreach (MethodBase mb in mg.Methods) {
1628 ParameterData pd = TypeManager.GetParameterData (mb);
1637 protected abstract string GetSignatureForError ();
1638 protected abstract void Report_SymbolRelatedToPreviousError ();
1640 void Error_TypeMustBeConvertible (Type atype, Type gc, Type ptype)
1642 Report_SymbolRelatedToPreviousError ();
1643 Report.SymbolRelatedToPreviousError (atype);
1644 Report.Error (309, loc,
1645 "The type `{0}' must be convertible to `{1}' in order to " +
1646 "use it as parameter `{2}' in the generic type or method `{3}'",
1647 TypeManager.CSharpName (atype), TypeManager.CSharpName (gc),
1648 TypeManager.CSharpName (ptype), GetSignatureForError ());
1651 public static bool CheckConstraints (EmitContext ec, MethodBase definition,
1652 MethodBase instantiated, Location loc)
1654 MethodConstraintChecker checker = new MethodConstraintChecker (
1655 definition, definition.GetGenericArguments (),
1656 instantiated.GetGenericArguments (), loc);
1658 return checker.CheckConstraints (ec);
1661 public static bool CheckConstraints (EmitContext ec, Type gt, Type[] gen_params,
1662 Type[] atypes, Location loc)
1664 TypeConstraintChecker checker = new TypeConstraintChecker (
1665 gt, gen_params, atypes, loc);
1667 return checker.CheckConstraints (ec);
1670 protected class MethodConstraintChecker : ConstraintChecker
1672 MethodBase definition;
1674 public MethodConstraintChecker (MethodBase definition, Type[] gen_params,
1675 Type[] atypes, Location loc)
1676 : base (gen_params, atypes, loc)
1678 this.definition = definition;
1681 protected override string GetSignatureForError ()
1683 return TypeManager.CSharpSignature (definition);
1686 protected override void Report_SymbolRelatedToPreviousError ()
1688 Report.SymbolRelatedToPreviousError (definition);
1692 protected class TypeConstraintChecker : ConstraintChecker
1696 public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
1698 : base (gen_params, atypes, loc)
1703 protected override string GetSignatureForError ()
1705 return TypeManager.CSharpName (gt);
1708 protected override void Report_SymbolRelatedToPreviousError ()
1710 Report.SymbolRelatedToPreviousError (gt);
1716 /// A generic method definition.
1718 public class GenericMethod : DeclSpace
1720 Expression return_type;
1721 Parameters parameters;
1723 public GenericMethod (NamespaceEntry ns, TypeContainer parent, MemberName name,
1724 Expression return_type, Parameters parameters)
1725 : base (ns, parent, name, null)
1727 this.return_type = return_type;
1728 this.parameters = parameters;
1731 public override TypeBuilder DefineType ()
1733 throw new Exception ();
1736 public override bool Define ()
1738 ec = new EmitContext (this, this, Location, null, null, ModFlags, false);
1740 for (int i = 0; i < TypeParameters.Length; i++)
1741 if (!TypeParameters [i].Resolve (this))
1748 /// Define and resolve the type parameters.
1749 /// We're called from Method.Define().
1751 public bool Define (MethodBuilder mb)
1753 GenericTypeParameterBuilder[] gen_params;
1754 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1755 string[] snames = new string [names.Length];
1756 for (int i = 0; i < names.Length; i++)
1757 snames [i] = names [i].Name;
1758 gen_params = mb.DefineGenericParameters (snames);
1759 for (int i = 0; i < TypeParameters.Length; i++)
1760 TypeParameters [i].Define (gen_params [i]);
1765 for (int i = 0; i < TypeParameters.Length; i++) {
1766 if (!TypeParameters [i].ResolveType (ec))
1774 /// We're called from MethodData.Define() after creating the MethodBuilder.
1776 public bool DefineType (EmitContext ec, MethodBuilder mb,
1777 MethodInfo implementing, bool is_override)
1779 for (int i = 0; i < TypeParameters.Length; i++)
1780 if (!TypeParameters [i].DefineType (
1781 ec, mb, implementing, is_override))
1785 foreach (Parameter p in parameters.FixedParameters){
1786 if (!p.Resolve (ec))
1789 if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec) == null))
1795 public void EmitAttributes (EmitContext ec)
1797 for (int i = 0; i < TypeParameters.Length; i++)
1798 TypeParameters [i].EmitAttributes (ec);
1800 if (OptAttributes != null)
1801 OptAttributes.Emit (ec, this);
1804 public override bool DefineMembers ()
1809 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1810 MemberFilter filter, object criteria)
1812 throw new Exception ();
1815 public override MemberCache MemberCache {
1821 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1823 base.ApplyAttributeBuilder (a, cb);
1826 public override AttributeTargets AttributeTargets {
1828 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1832 public override string DocCommentHeader {
1833 get { return "M:"; }
1837 public class DefaultValueExpression : Expression
1841 public DefaultValueExpression (Expression expr, Location loc)
1847 public override Expression DoResolve (EmitContext ec)
1849 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
1855 eclass = ExprClass.Variable;
1859 public override void Emit (EmitContext ec)
1861 if (type.IsGenericParameter || TypeManager.IsValueType (type)) {
1862 LocalTemporary temp_storage = new LocalTemporary (ec, type);
1864 temp_storage.AddressOf (ec, AddressOp.LoadStore);
1865 ec.ig.Emit (OpCodes.Initobj, type);
1866 temp_storage.Emit (ec);
1868 ec.ig.Emit (OpCodes.Ldnull);
1872 public class NullableType : TypeExpr
1874 Expression underlying;
1876 public NullableType (Expression underlying, Location l)
1878 this.underlying = underlying;
1881 eclass = ExprClass.Type;
1884 public NullableType (Type type, Location loc)
1885 : this (new TypeExpression (type, loc), loc)
1888 public override string Name {
1889 get { return underlying.ToString () + "?"; }
1892 public override string FullName {
1893 get { return underlying.ToString () + "?"; }
1896 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
1898 TypeArguments args = new TypeArguments (loc);
1899 args.Add (underlying);
1901 ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
1902 return ctype.ResolveAsTypeTerminal (ec);
1906 public partial class TypeManager
1909 // A list of core types that the compiler requires or uses
1911 static public Type activator_type;
1912 static public Type generic_ienumerator_type;
1913 static public Type generic_ienumerable_type;
1914 static public Type generic_nullable_type;
1917 // Tracks the generic parameters.
1919 static PtrHashtable builder_to_type_param;
1922 // These methods are called by code generated by the compiler
1924 static public MethodInfo activator_create_instance;
1926 static void InitGenerics ()
1928 builder_to_type_param = new PtrHashtable ();
1931 static void CleanUpGenerics ()
1933 builder_to_type_param = null;
1936 static void InitGenericCoreTypes ()
1938 activator_type = CoreLookupType ("System", "Activator");
1940 generic_ienumerator_type = CoreLookupType (
1941 "System.Collections.Generic", "IEnumerator", 1);
1942 generic_ienumerable_type = CoreLookupType (
1943 "System.Collections.Generic", "IEnumerable", 1);
1944 generic_nullable_type = CoreLookupType (
1945 "System", "Nullable", 1);
1948 static void InitGenericCodeHelpers ()
1951 Type [] type_arg = { type_type };
1952 activator_create_instance = GetMethod (
1953 activator_type, "CreateInstance", type_arg);
1956 static Type CoreLookupType (string ns, string name, int arity)
1958 return CoreLookupType (ns, MemberName.MakeName (name, arity));
1961 public static void AddTypeParameter (Type t, TypeParameter tparam)
1963 if (!builder_to_type_param.Contains (t))
1964 builder_to_type_param.Add (t, tparam);
1967 public static TypeContainer LookupGenericTypeContainer (Type t)
1969 t = DropGenericTypeArguments (t);
1970 return LookupTypeContainer (t);
1973 public static TypeParameter LookupTypeParameter (Type t)
1975 return (TypeParameter) builder_to_type_param [t];
1978 public static GenericConstraints GetTypeParameterConstraints (Type t)
1980 if (!t.IsGenericParameter)
1981 throw new InvalidOperationException ();
1983 TypeParameter tparam = LookupTypeParameter (t);
1985 return tparam.GenericConstraints;
1987 return ReflectionConstraints.GetConstraints (t);
1990 public static bool HasGenericArguments (Type t)
1992 return GetNumberOfTypeArguments (t) > 0;
1995 public static int GetNumberOfTypeArguments (Type t)
1997 if (t.IsGenericParameter)
1999 DeclSpace tc = LookupDeclSpace (t);
2001 return tc.IsGeneric ? tc.CountTypeParameters : 0;
2003 return t.IsGenericType ? t.GetGenericArguments ().Length : 0;
2006 public static Type[] GetTypeArguments (Type t)
2008 DeclSpace tc = LookupDeclSpace (t);
2011 return Type.EmptyTypes;
2013 TypeParameter[] tparam = tc.TypeParameters;
2014 Type[] ret = new Type [tparam.Length];
2015 for (int i = 0; i < tparam.Length; i++) {
2016 ret [i] = tparam [i].Type;
2017 if (ret [i] == null)
2018 throw new InternalErrorException ();
2023 return t.GetGenericArguments ();
2026 public static Type DropGenericTypeArguments (Type t)
2028 if (!t.IsGenericType)
2030 // Micro-optimization: a generic typebuilder is always a generic type definition
2031 if (t is TypeBuilder)
2033 return t.GetGenericTypeDefinition ();
2036 public static MethodBase DropGenericMethodArguments (MethodBase m)
2038 if (m.IsGenericMethodDefinition)
2040 if (m.IsGenericMethod)
2041 return m.GetGenericMethodDefinition ();
2042 if (!m.DeclaringType.IsGenericType)
2045 Type t = m.DeclaringType.GetGenericTypeDefinition ();
2046 BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
2047 BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
2049 if (m is ConstructorInfo) {
2050 foreach (ConstructorInfo c in t.GetConstructors (bf))
2051 if (c.MetadataToken == m.MetadataToken)
2054 foreach (MethodBase mb in t.GetMethods (bf))
2055 if (mb.MetadataToken == m.MetadataToken)
2063 // Whether `array' is an array of T and `enumerator' is `IEnumerable<T>'.
2064 // For instance "string[]" -> "IEnumerable<string>".
2066 public static bool IsIEnumerable (Type array, Type enumerator)
2068 if (!array.IsArray || !enumerator.IsGenericInstance)
2071 if (enumerator.GetGenericTypeDefinition () != generic_ienumerable_type)
2074 Type[] args = GetTypeArguments (enumerator);
2075 return args [0] == GetElementType (array);
2078 public static bool IsEqual (Type a, Type b)
2083 if (a.IsGenericParameter && b.IsGenericParameter) {
2084 if (a.DeclaringMethod != b.DeclaringMethod &&
2085 (a.DeclaringMethod == null || b.DeclaringMethod == null))
2087 return a.GenericParameterPosition == b.GenericParameterPosition;
2090 if (a.IsArray && b.IsArray) {
2091 if (a.GetArrayRank () != b.GetArrayRank ())
2093 return IsEqual (a.GetElementType (), b.GetElementType ());
2096 if (a.IsByRef && b.IsByRef)
2097 return IsEqual (a.GetElementType (), b.GetElementType ());
2099 if (a.IsGenericType && b.IsGenericType) {
2100 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2103 Type[] aargs = a.GetGenericArguments ();
2104 Type[] bargs = b.GetGenericArguments ();
2106 if (aargs.Length != bargs.Length)
2109 for (int i = 0; i < aargs.Length; i++) {
2110 if (!IsEqual (aargs [i], bargs [i]))
2118 // This is to build with the broken circular dependencies between
2119 // System and System.Configuration in the 2.x profile where we
2120 // end up with a situation where:
2122 // System on the second build is referencing the System.Configuration
2123 // that has references to the first System build.
2125 // Point in case: NameValueCollection built on the first pass, vs
2126 // NameValueCollection build on the second one. The problem is that
2127 // we need to override some methods sometimes, or we need to
2129 if (RootContext.BrokenCircularDeps){
2130 if (a.Name == b.Name && a.Namespace == b.Namespace){
2131 Console.WriteLine ("GonziMatch: {0}.{1}", a.Namespace, a.Name);
2139 /// Check whether `a' and `b' may become equal generic types.
2140 /// The algorithm to do that is a little bit complicated.
2142 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_infered,
2143 Type[] method_infered)
2145 if (a.IsGenericParameter) {
2147 // If a is an array of a's type, they may never
2151 b = b.GetElementType ();
2157 // If b is a generic parameter or an actual type,
2158 // they may become equal:
2160 // class X<T,U> : I<T>, I<U>
2161 // class X<T> : I<T>, I<float>
2163 if (b.IsGenericParameter || !b.IsGenericInstance) {
2164 int pos = a.GenericParameterPosition;
2165 Type[] args = a.DeclaringMethod != null ? method_infered : class_infered;
2166 if (args [pos] == null) {
2171 return args [pos] == a;
2175 // We're now comparing a type parameter with a
2176 // generic instance. They may become equal unless
2177 // the type parameter appears anywhere in the
2178 // generic instance:
2180 // class X<T,U> : I<T>, I<X<U>>
2181 // -> error because you could instanciate it as
2184 // class X<T> : I<T>, I<X<T>> -> ok
2187 Type[] bargs = GetTypeArguments (b);
2188 for (int i = 0; i < bargs.Length; i++) {
2189 if (a.Equals (bargs [i]))
2196 if (b.IsGenericParameter)
2197 return MayBecomeEqualGenericTypes (b, a, class_infered, method_infered);
2200 // At this point, neither a nor b are a type parameter.
2202 // If one of them is a generic instance, let
2203 // MayBecomeEqualGenericInstances() compare them (if the
2204 // other one is not a generic instance, they can never
2208 if (a.IsGenericInstance || b.IsGenericInstance)
2209 return MayBecomeEqualGenericInstances (a, b, class_infered, method_infered);
2212 // If both of them are arrays.
2215 if (a.IsArray && b.IsArray) {
2216 if (a.GetArrayRank () != b.GetArrayRank ())
2219 a = a.GetElementType ();
2220 b = b.GetElementType ();
2222 return MayBecomeEqualGenericTypes (a, b, class_infered, method_infered);
2226 // Ok, two ordinary types.
2229 return a.Equals (b);
2233 // Checks whether two generic instances may become equal for some
2234 // particular instantiation (26.3.1).
2236 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
2237 Type[] class_infered,
2238 Type[] method_infered)
2240 if (!a.IsGenericInstance || !b.IsGenericInstance)
2242 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2245 return MayBecomeEqualGenericInstances (
2246 GetTypeArguments (a), GetTypeArguments (b), class_infered, method_infered);
2249 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
2250 Type[] class_infered,
2251 Type[] method_infered)
2253 if (aargs.Length != bargs.Length)
2256 for (int i = 0; i < aargs.Length; i++) {
2257 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_infered, method_infered))
2265 /// Check whether `type' and `parent' are both instantiations of the same
2266 /// generic type. Note that we do not check the type parameters here.
2268 public static bool IsInstantiationOfSameGenericType (Type type, Type parent)
2270 int tcount = GetNumberOfTypeArguments (type);
2271 int pcount = GetNumberOfTypeArguments (parent);
2273 if (tcount != pcount)
2276 type = DropGenericTypeArguments (type);
2277 parent = DropGenericTypeArguments (parent);
2279 return type.Equals (parent);
2283 /// Whether `mb' is a generic method definition.
2285 public static bool IsGenericMethodDefinition (MethodBase mb)
2287 if (mb.DeclaringType is TypeBuilder) {
2288 IMethodData method = (IMethodData) builder_to_method [mb];
2292 return method.GenericMethod != null;
2295 return mb.IsGenericMethodDefinition;
2299 /// Whether `mb' is a generic method definition.
2301 public static bool IsGenericMethod (MethodBase mb)
2303 if (mb.DeclaringType is TypeBuilder) {
2304 IMethodData method = (IMethodData) builder_to_method [mb];
2308 return method.GenericMethod != null;
2311 return mb.IsGenericMethod;
2318 static bool InferType (Type pt, Type at, Type[] infered)
2320 if (pt.IsGenericParameter && (pt.DeclaringMethod != null)) {
2321 int pos = pt.GenericParameterPosition;
2323 if (infered [pos] == null) {
2325 while (check.IsArray)
2326 check = check.GetElementType ();
2335 if (infered [pos] != at)
2341 if (!pt.ContainsGenericParameters) {
2342 if (at.ContainsGenericParameters)
2343 return InferType (at, pt, infered);
2350 (at.GetArrayRank () != pt.GetArrayRank ()))
2353 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2358 (pt.GetArrayRank () != at.GetArrayRank ()))
2361 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2364 if (pt.IsByRef && at.IsByRef)
2365 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2366 ArrayList list = new ArrayList ();
2367 if (at.IsGenericInstance)
2369 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
2372 list.AddRange (TypeManager.GetInterfaces (at));
2374 bool found_one = false;
2376 foreach (Type type in list) {
2377 if (!type.IsGenericInstance)
2380 Type[] infered_types = new Type [infered.Length];
2382 if (!InferGenericInstance (pt, type, infered_types))
2385 for (int i = 0; i < infered_types.Length; i++) {
2386 if (infered [i] == null) {
2387 infered [i] = infered_types [i];
2391 if (infered [i] != infered_types [i])
2401 static bool InferGenericInstance (Type pt, Type at, Type[] infered_types)
2403 Type[] at_args = at.GetGenericArguments ();
2404 Type[] pt_args = pt.GetGenericArguments ();
2406 if (at_args.Length != pt_args.Length)
2409 for (int i = 0; i < at_args.Length; i++) {
2410 if (!InferType (pt_args [i], at_args [i], infered_types))
2414 for (int i = 0; i < infered_types.Length; i++) {
2415 if (infered_types [i] == null)
2423 /// Type inference. Try to infer the type arguments from the params method
2424 /// `method', which is invoked with the arguments `arguments'. This is used
2425 /// when resolving an Invocation or a DelegateInvocation and the user
2426 /// did not explicitly specify type arguments.
2428 public static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
2429 ref MethodBase method)
2431 if ((arguments == null) || !TypeManager.IsGenericMethod (method))
2436 if (arguments == null)
2439 arg_count = arguments.Count;
2441 ParameterData pd = TypeManager.GetParameterData (method);
2443 int pd_count = pd.Count;
2448 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2451 if (pd_count - 1 > arg_count)
2454 if (pd_count == 1 && arg_count == 0)
2457 Type[] method_args = method.GetGenericArguments ();
2458 Type[] infered_types = new Type [method_args.Length];
2461 // If we have come this far, the case which
2462 // remains is when the number of parameters is
2463 // less than or equal to the argument count.
2465 for (int i = 0; i < pd_count - 1; ++i) {
2466 Argument a = (Argument) arguments [i];
2468 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2471 Type pt = pd.ParameterType (i);
2474 if (!InferType (pt, at, infered_types))
2478 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
2480 for (int i = pd_count - 1; i < arg_count; i++) {
2481 Argument a = (Argument) arguments [i];
2483 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2486 if (!InferType (element_type, a.Type, infered_types))
2490 for (int i = 0; i < infered_types.Length; i++)
2491 if (infered_types [i] == null)
2494 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2498 static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
2499 Type[] infered_types)
2501 if (infered_types == null)
2504 for (int i = 0; i < arg_types.Length; i++) {
2505 if (arg_types [i] == null)
2508 if (!InferType (param_types [i], arg_types [i], infered_types))
2512 for (int i = 0; i < infered_types.Length; i++)
2513 if (infered_types [i] == null)
2520 /// Type inference. Try to infer the type arguments from `method',
2521 /// which is invoked with the arguments `arguments'. This is used
2522 /// when resolving an Invocation or a DelegateInvocation and the user
2523 /// did not explicitly specify type arguments.
2525 public static bool InferTypeArguments (EmitContext ec, ArrayList arguments,
2526 ref MethodBase method)
2528 if (!TypeManager.IsGenericMethod (method))
2532 if (arguments != null)
2533 arg_count = arguments.Count;
2537 ParameterData pd = TypeManager.GetParameterData (method);
2538 if (arg_count != pd.Count)
2541 Type[] method_args = method.GetGenericArguments ();
2543 bool is_open = false;
2544 for (int i = 0; i < method_args.Length; i++) {
2545 if (method_args [i].IsGenericParameter) {
2553 Type[] infered_types = new Type [method_args.Length];
2555 Type[] param_types = new Type [pd.Count];
2556 Type[] arg_types = new Type [pd.Count];
2558 for (int i = 0; i < arg_count; i++) {
2559 param_types [i] = pd.ParameterType (i);
2561 Argument a = (Argument) arguments [i];
2562 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr) ||
2563 (a.Expr is AnonymousMethod))
2566 arg_types [i] = a.Type;
2569 if (!InferTypeArguments (param_types, arg_types, infered_types))
2572 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2579 public static bool InferTypeArguments (EmitContext ec, ParameterData apd,
2580 ref MethodBase method)
2582 if (!TypeManager.IsGenericMethod (method))
2585 ParameterData pd = TypeManager.GetParameterData (method);
2586 if (apd.Count != pd.Count)
2589 Type[] method_args = method.GetGenericArguments ();
2590 Type[] infered_types = new Type [method_args.Length];
2592 Type[] param_types = new Type [pd.Count];
2593 Type[] arg_types = new Type [pd.Count];
2595 for (int i = 0; i < apd.Count; i++) {
2596 param_types [i] = pd.ParameterType (i);
2597 arg_types [i] = apd.ParameterType (i);
2600 if (!InferTypeArguments (param_types, arg_types, infered_types))
2603 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2607 public static bool IsNullableType (Type t)
2609 return generic_nullable_type == DropGenericTypeArguments (t);
2613 public abstract class Nullable
2615 protected sealed class NullableInfo
2617 public readonly Type Type;
2618 public readonly Type UnderlyingType;
2619 public readonly MethodInfo HasValue;
2620 public readonly MethodInfo Value;
2621 public readonly ConstructorInfo Constructor;
2623 public NullableInfo (Type type)
2626 UnderlyingType = TypeManager.GetTypeArguments (type) [0];
2628 PropertyInfo has_value_pi = TypeManager.GetProperty (type, "HasValue");
2629 PropertyInfo value_pi = TypeManager.GetProperty (type, "Value");
2631 HasValue = has_value_pi.GetGetMethod (false);
2632 Value = value_pi.GetGetMethod (false);
2633 Constructor = type.GetConstructor (new Type[] { UnderlyingType });
2637 protected class Unwrap : Expression, IMemoryLocation, IAssignMethod
2642 LocalTemporary temp;
2645 public Unwrap (Expression expr, Location loc)
2651 public override Expression DoResolve (EmitContext ec)
2653 expr = expr.Resolve (ec);
2657 if (!(expr is IMemoryLocation))
2658 temp = new LocalTemporary (ec, expr.Type);
2660 info = new NullableInfo (expr.Type);
2661 type = info.UnderlyingType;
2662 eclass = expr.eclass;
2666 public override void Emit (EmitContext ec)
2668 AddressOf (ec, AddressOp.LoadStore);
2669 ec.ig.EmitCall (OpCodes.Call, info.Value, null);
2672 public void EmitCheck (EmitContext ec)
2674 AddressOf (ec, AddressOp.LoadStore);
2675 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
2678 void create_temp (EmitContext ec)
2680 if ((temp != null) && !has_temp) {
2687 public void AddressOf (EmitContext ec, AddressOp mode)
2691 temp.AddressOf (ec, AddressOp.LoadStore);
2693 ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
2696 public void Emit (EmitContext ec, bool leave_copy)
2709 public void EmitAssign (EmitContext ec, Expression source,
2710 bool leave_copy, bool prepare_for_load)
2713 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2716 ec.ig.Emit (OpCodes.Dup);
2718 Expression empty = new EmptyExpression (expr.Type);
2719 ((IAssignMethod) expr).EmitAssign (ec, empty, false, prepare_for_load);
2723 protected class Wrap : Expression
2728 public Wrap (Expression expr, Location loc)
2734 public override Expression DoResolve (EmitContext ec)
2736 expr = expr.Resolve (ec);
2740 TypeExpr target_type = new NullableType (expr.Type, loc);
2741 target_type = target_type.ResolveAsTypeTerminal (ec);
2742 if (target_type == null)
2745 type = target_type.Type;
2746 info = new NullableInfo (type);
2747 eclass = ExprClass.Value;
2751 public override void Emit (EmitContext ec)
2754 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2758 public class NullableLiteral : Expression, IMemoryLocation {
2759 public NullableLiteral (Type target_type, Location loc)
2761 this.type = target_type;
2764 eclass = ExprClass.Value;
2767 public override Expression DoResolve (EmitContext ec)
2772 public override void Emit (EmitContext ec)
2774 LocalTemporary value_target = new LocalTemporary (ec, type);
2776 value_target.AddressOf (ec, AddressOp.Store);
2777 ec.ig.Emit (OpCodes.Initobj, type);
2778 value_target.Emit (ec);
2781 public void AddressOf (EmitContext ec, AddressOp Mode)
2783 LocalTemporary value_target = new LocalTemporary (ec, type);
2785 value_target.AddressOf (ec, AddressOp.Store);
2786 ec.ig.Emit (OpCodes.Initobj, type);
2787 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
2791 public abstract class Lifted : Expression, IMemoryLocation
2793 Expression expr, underlying, wrap, null_value;
2796 protected Lifted (Expression expr, Location loc)
2802 public override Expression DoResolve (EmitContext ec)
2804 expr = expr.Resolve (ec);
2808 unwrap = (Unwrap) new Unwrap (expr, loc).Resolve (ec);
2812 underlying = ResolveUnderlying (unwrap, ec);
2813 if (underlying == null)
2816 wrap = new Wrap (underlying, loc).Resolve (ec);
2820 null_value = new NullableLiteral (wrap.Type, loc).Resolve (ec);
2821 if (null_value == null)
2825 eclass = ExprClass.Value;
2829 protected abstract Expression ResolveUnderlying (Expression unwrap, EmitContext ec);
2831 public override void Emit (EmitContext ec)
2833 ILGenerator ig = ec.ig;
2834 Label is_null_label = ig.DefineLabel ();
2835 Label end_label = ig.DefineLabel ();
2837 unwrap.EmitCheck (ec);
2838 ig.Emit (OpCodes.Brfalse, is_null_label);
2841 ig.Emit (OpCodes.Br, end_label);
2843 ig.MarkLabel (is_null_label);
2844 null_value.Emit (ec);
2846 ig.MarkLabel (end_label);
2849 public void AddressOf (EmitContext ec, AddressOp mode)
2851 unwrap.AddressOf (ec, mode);
2855 public class LiftedConversion : Lifted
2857 public readonly bool IsUser;
2858 public readonly bool IsExplicit;
2859 public readonly Type TargetType;
2861 public LiftedConversion (Expression expr, Type target_type, bool is_user,
2862 bool is_explicit, Location loc)
2865 this.IsUser = is_user;
2866 this.IsExplicit = is_explicit;
2867 this.TargetType = target_type;
2870 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2872 Type type = TypeManager.GetTypeArguments (TargetType) [0];
2875 return Convert.UserDefinedConversion (ec, unwrap, type, loc, IsExplicit);
2878 return Convert.ExplicitConversion (ec, unwrap, type, loc);
2880 return Convert.ImplicitConversion (ec, unwrap, type, loc);
2885 public class LiftedUnaryOperator : Lifted
2887 public readonly Unary.Operator Oper;
2889 public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
2895 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2897 return new Unary (Oper, unwrap, loc);
2901 public class LiftedConditional : Lifted
2903 Expression true_expr, false_expr;
2905 public LiftedConditional (Expression expr, Expression true_expr, Expression false_expr,
2909 this.true_expr = true_expr;
2910 this.false_expr = false_expr;
2913 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2915 return new Conditional (unwrap, true_expr, false_expr);
2919 public class LiftedBinaryOperator : Expression
2921 public readonly Binary.Operator Oper;
2923 Expression left, right, underlying, null_value, bool_wrap;
2924 Unwrap left_unwrap, right_unwrap;
2925 bool is_equality, is_comparision, is_boolean;
2927 public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
2936 public override Expression DoResolve (EmitContext ec)
2938 if (TypeManager.IsNullableType (left.Type)) {
2939 left_unwrap = new Unwrap (left, loc);
2940 left = left_unwrap.Resolve (ec);
2945 if (TypeManager.IsNullableType (right.Type)) {
2946 right_unwrap = new Unwrap (right, loc);
2947 right = right_unwrap.Resolve (ec);
2952 if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr) ||
2953 (Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr)) &&
2954 ((left.Type == TypeManager.bool_type) && (right.Type == TypeManager.bool_type))) {
2955 Expression empty = new EmptyExpression (TypeManager.bool_type);
2956 bool_wrap = new Wrap (empty, loc).Resolve (ec);
2957 null_value = new NullableLiteral (bool_wrap.Type, loc).Resolve (ec);
2959 type = bool_wrap.Type;
2961 } else if ((Oper == Binary.Operator.Equality) || (Oper == Binary.Operator.Inequality)) {
2962 if (!(left is NullLiteral) && !(right is NullLiteral)) {
2963 underlying = new Binary (Oper, left, right).Resolve (ec);
2964 if (underlying == null)
2968 type = TypeManager.bool_type;
2970 } else if ((Oper == Binary.Operator.LessThan) ||
2971 (Oper == Binary.Operator.GreaterThan) ||
2972 (Oper == Binary.Operator.LessThanOrEqual) ||
2973 (Oper == Binary.Operator.GreaterThanOrEqual)) {
2974 underlying = new Binary (Oper, left, right).Resolve (ec);
2975 if (underlying == null)
2978 type = TypeManager.bool_type;
2979 is_comparision = true;
2981 underlying = new Binary (Oper, left, right).Resolve (ec);
2982 if (underlying == null)
2985 underlying = new Wrap (underlying, loc).Resolve (ec);
2986 if (underlying == null)
2989 type = underlying.Type;
2990 null_value = new NullableLiteral (type, loc).Resolve (ec);
2993 eclass = ExprClass.Value;
2997 void EmitBoolean (EmitContext ec)
2999 ILGenerator ig = ec.ig;
3001 Label left_is_null_label = ig.DefineLabel ();
3002 Label right_is_null_label = ig.DefineLabel ();
3003 Label is_null_label = ig.DefineLabel ();
3004 Label wrap_label = ig.DefineLabel ();
3005 Label end_label = ig.DefineLabel ();
3007 if (left_unwrap != null) {
3008 left_unwrap.EmitCheck (ec);
3009 ig.Emit (OpCodes.Brfalse, left_is_null_label);
3013 ig.Emit (OpCodes.Dup);
3014 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3015 ig.Emit (OpCodes.Brtrue, wrap_label);
3017 ig.Emit (OpCodes.Brfalse, wrap_label);
3019 if (right_unwrap != null) {
3020 right_unwrap.EmitCheck (ec);
3021 ig.Emit (OpCodes.Brfalse, right_is_null_label);
3024 if ((Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr))
3025 ig.Emit (OpCodes.Pop);
3028 if (Oper == Binary.Operator.BitwiseOr)
3029 ig.Emit (OpCodes.Or);
3030 else if (Oper == Binary.Operator.BitwiseAnd)
3031 ig.Emit (OpCodes.And);
3032 ig.Emit (OpCodes.Br, wrap_label);
3034 ig.MarkLabel (left_is_null_label);
3035 if (right_unwrap != null) {
3036 right_unwrap.EmitCheck (ec);
3037 ig.Emit (OpCodes.Brfalse, is_null_label);
3041 ig.Emit (OpCodes.Dup);
3042 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3043 ig.Emit (OpCodes.Brtrue, wrap_label);
3045 ig.Emit (OpCodes.Brfalse, wrap_label);
3047 ig.MarkLabel (right_is_null_label);
3048 ig.Emit (OpCodes.Pop);
3049 ig.MarkLabel (is_null_label);
3050 null_value.Emit (ec);
3051 ig.Emit (OpCodes.Br, end_label);
3053 ig.MarkLabel (wrap_label);
3054 ig.Emit (OpCodes.Nop);
3055 bool_wrap.Emit (ec);
3056 ig.Emit (OpCodes.Nop);
3058 ig.MarkLabel (end_label);
3061 void EmitEquality (EmitContext ec)
3063 ILGenerator ig = ec.ig;
3065 Label left_not_null_label = ig.DefineLabel ();
3066 Label false_label = ig.DefineLabel ();
3067 Label true_label = ig.DefineLabel ();
3068 Label end_label = ig.DefineLabel ();
3070 bool false_label_used = false;
3071 bool true_label_used = false;
3073 if (left_unwrap != null) {
3074 left_unwrap.EmitCheck (ec);
3075 if (right is NullLiteral) {
3076 if (Oper == Binary.Operator.Equality) {
3077 true_label_used = true;
3078 ig.Emit (OpCodes.Brfalse, true_label);
3080 false_label_used = true;
3081 ig.Emit (OpCodes.Brfalse, false_label);
3083 } else if (right_unwrap != null) {
3084 ig.Emit (OpCodes.Dup);
3085 ig.Emit (OpCodes.Brtrue, left_not_null_label);
3086 right_unwrap.EmitCheck (ec);
3087 ig.Emit (OpCodes.Ceq);
3088 if (Oper == Binary.Operator.Inequality) {
3089 ig.Emit (OpCodes.Ldc_I4_0);
3090 ig.Emit (OpCodes.Ceq);
3092 ig.Emit (OpCodes.Br, end_label);
3094 ig.MarkLabel (left_not_null_label);
3095 ig.Emit (OpCodes.Pop);
3097 if (Oper == Binary.Operator.Equality) {
3098 false_label_used = true;
3099 ig.Emit (OpCodes.Brfalse, false_label);
3101 true_label_used = true;
3102 ig.Emit (OpCodes.Brfalse, true_label);
3107 if (right_unwrap != null) {
3108 right_unwrap.EmitCheck (ec);
3109 if (left is NullLiteral) {
3110 if (Oper == Binary.Operator.Equality) {
3111 true_label_used = true;
3112 ig.Emit (OpCodes.Brfalse, true_label);
3114 false_label_used = true;
3115 ig.Emit (OpCodes.Brfalse, false_label);
3118 if (Oper == Binary.Operator.Equality) {
3119 false_label_used = true;
3120 ig.Emit (OpCodes.Brfalse, false_label);
3122 true_label_used = true;
3123 ig.Emit (OpCodes.Brfalse, true_label);
3128 bool left_is_null = left is NullLiteral;
3129 bool right_is_null = right is NullLiteral;
3130 if (left_is_null || right_is_null) {
3131 if (((Oper == Binary.Operator.Equality) && (left_is_null == right_is_null)) ||
3132 ((Oper == Binary.Operator.Inequality) && (left_is_null != right_is_null))) {
3133 true_label_used = true;
3134 ig.Emit (OpCodes.Br, true_label);
3136 false_label_used = true;
3137 ig.Emit (OpCodes.Br, false_label);
3140 underlying.Emit (ec);
3141 ig.Emit (OpCodes.Br, end_label);
3144 ig.MarkLabel (false_label);
3145 if (false_label_used) {
3146 ig.Emit (OpCodes.Ldc_I4_0);
3147 if (true_label_used)
3148 ig.Emit (OpCodes.Br, end_label);
3151 ig.MarkLabel (true_label);
3152 if (true_label_used)
3153 ig.Emit (OpCodes.Ldc_I4_1);
3155 ig.MarkLabel (end_label);
3158 void EmitComparision (EmitContext ec)
3160 ILGenerator ig = ec.ig;
3162 Label is_null_label = ig.DefineLabel ();
3163 Label end_label = ig.DefineLabel ();
3165 if (left_unwrap != null) {
3166 left_unwrap.EmitCheck (ec);
3167 ig.Emit (OpCodes.Brfalse, is_null_label);
3170 if (right_unwrap != null) {
3171 right_unwrap.EmitCheck (ec);
3172 ig.Emit (OpCodes.Brfalse, is_null_label);
3175 underlying.Emit (ec);
3176 ig.Emit (OpCodes.Br, end_label);
3178 ig.MarkLabel (is_null_label);
3179 ig.Emit (OpCodes.Ldc_I4_0);
3181 ig.MarkLabel (end_label);
3184 public override void Emit (EmitContext ec)
3189 } else if (is_equality) {
3192 } else if (is_comparision) {
3193 EmitComparision (ec);
3197 ILGenerator ig = ec.ig;
3199 Label is_null_label = ig.DefineLabel ();
3200 Label end_label = ig.DefineLabel ();
3202 if (left_unwrap != null) {
3203 left_unwrap.EmitCheck (ec);
3204 ig.Emit (OpCodes.Brfalse, is_null_label);
3207 if (right_unwrap != null) {
3208 right_unwrap.EmitCheck (ec);
3209 ig.Emit (OpCodes.Brfalse, is_null_label);
3212 underlying.Emit (ec);
3213 ig.Emit (OpCodes.Br, end_label);
3215 ig.MarkLabel (is_null_label);
3216 null_value.Emit (ec);
3218 ig.MarkLabel (end_label);
3222 public class OperatorTrueOrFalse : Expression
3224 public readonly bool IsTrue;
3229 public OperatorTrueOrFalse (Expression expr, bool is_true, Location loc)
3231 this.IsTrue = is_true;
3236 public override Expression DoResolve (EmitContext ec)
3238 unwrap = new Unwrap (expr, loc);
3239 expr = unwrap.Resolve (ec);
3243 if (unwrap.Type != TypeManager.bool_type)
3246 type = TypeManager.bool_type;
3247 eclass = ExprClass.Value;
3251 public override void Emit (EmitContext ec)
3253 ILGenerator ig = ec.ig;
3255 Label is_null_label = ig.DefineLabel ();
3256 Label end_label = ig.DefineLabel ();
3258 unwrap.EmitCheck (ec);
3259 ig.Emit (OpCodes.Brfalse, is_null_label);
3263 ig.Emit (OpCodes.Ldc_I4_0);
3264 ig.Emit (OpCodes.Ceq);
3266 ig.Emit (OpCodes.Br, end_label);
3268 ig.MarkLabel (is_null_label);
3269 ig.Emit (OpCodes.Ldc_I4_0);
3271 ig.MarkLabel (end_label);
3275 public class NullCoalescingOperator : Expression
3277 Expression left, right;
3281 public NullCoalescingOperator (Expression left, Expression right, Location loc)
3287 eclass = ExprClass.Value;
3290 public override Expression DoResolve (EmitContext ec)
3295 left = left.Resolve (ec);
3299 right = right.Resolve (ec);
3303 Type ltype = left.Type, rtype = right.Type;
3305 if (!TypeManager.IsNullableType (ltype) && ltype.IsValueType) {
3306 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3310 if (TypeManager.IsNullableType (ltype)) {
3311 NullableInfo info = new NullableInfo (ltype);
3313 unwrap = (Unwrap) new Unwrap (left, loc).Resolve (ec);
3317 expr = Convert.ImplicitConversion (ec, right, info.UnderlyingType, loc);
3325 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
3331 if (unwrap != null) {
3332 expr = Convert.ImplicitConversion (ec, unwrap, rtype, loc);
3341 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3345 public override void Emit (EmitContext ec)
3347 ILGenerator ig = ec.ig;
3349 Label is_null_label = ig.DefineLabel ();
3350 Label end_label = ig.DefineLabel ();
3352 if (unwrap != null) {
3353 unwrap.EmitCheck (ec);
3354 ig.Emit (OpCodes.Brfalse, is_null_label);
3357 ig.Emit (OpCodes.Br, end_label);
3359 ig.MarkLabel (is_null_label);
3362 ig.MarkLabel (end_label);
3365 ig.Emit (OpCodes.Dup);
3366 ig.Emit (OpCodes.Brtrue, end_label);
3368 ig.MarkLabel (is_null_label);
3370 ig.Emit (OpCodes.Pop);
3373 ig.MarkLabel (end_label);
3378 public class LiftedUnaryMutator : ExpressionStatement
3380 public readonly UnaryMutator.Mode Mode;
3381 Expression expr, null_value;
3382 UnaryMutator underlying;
3385 public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
3391 eclass = ExprClass.Value;
3394 public override Expression DoResolve (EmitContext ec)
3396 expr = expr.Resolve (ec);
3400 unwrap = (Unwrap) new Unwrap (expr, loc).Resolve (ec);
3404 underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
3405 if (underlying == null)
3408 null_value = new NullableLiteral (expr.Type, loc).Resolve (ec);
3409 if (null_value == null)
3416 void DoEmit (EmitContext ec, bool is_expr)
3418 ILGenerator ig = ec.ig;
3419 Label is_null_label = ig.DefineLabel ();
3420 Label end_label = ig.DefineLabel ();
3422 unwrap.EmitCheck (ec);
3423 ig.Emit (OpCodes.Brfalse, is_null_label);
3426 underlying.Emit (ec);
3428 underlying.EmitStatement (ec);
3429 ig.Emit (OpCodes.Br, end_label);
3431 ig.MarkLabel (is_null_label);
3433 null_value.Emit (ec);
3435 ig.MarkLabel (end_label);
3438 public override void Emit (EmitContext ec)
3443 public override void EmitStatement (EmitContext ec)