2 // generic.cs: Generics support
4 // Authors: Martin Baulig (martin@ximian.com)
5 // Miguel de Icaza (miguel@ximian.com)
7 // Licensed under the terms of the GNU GPL
9 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
10 // (C) 2004 Novell, Inc
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.Globalization;
16 using System.Collections;
18 using System.Text.RegularExpressions;
20 namespace Mono.CSharp {
23 /// Abstract base class for type parameter constraints.
24 /// The type parameter can come from a generic type definition or from reflection.
26 public abstract class GenericConstraints {
27 public abstract string TypeParameter {
31 public abstract GenericParameterAttributes Attributes {
35 public bool HasConstructorConstraint {
36 get { return (Attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0; }
39 public bool HasReferenceTypeConstraint {
40 get { return (Attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0; }
43 public bool HasValueTypeConstraint {
44 get { return (Attributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0; }
47 public virtual bool HasClassConstraint {
48 get { return ClassConstraint != null; }
51 public abstract Type ClassConstraint {
55 public abstract Type[] InterfaceConstraints {
59 public abstract Type EffectiveBaseClass {
64 // Returns whether the type parameter is "known to be a reference type".
66 public virtual bool IsReferenceType {
68 if (HasReferenceTypeConstraint)
70 if (HasValueTypeConstraint)
73 if (ClassConstraint != null) {
74 if (ClassConstraint.IsValueType)
77 if (ClassConstraint != TypeManager.object_type)
81 foreach (Type t in InterfaceConstraints) {
82 if (!t.IsGenericParameter)
85 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
86 if ((gc != null) && gc.IsReferenceType)
95 // Returns whether the type parameter is "known to be a value type".
97 public virtual bool IsValueType {
99 if (HasValueTypeConstraint)
101 if (HasReferenceTypeConstraint)
104 if (ClassConstraint != null) {
105 if (!ClassConstraint.IsValueType)
108 if (ClassConstraint != TypeManager.value_type)
112 foreach (Type t in InterfaceConstraints) {
113 if (!t.IsGenericParameter)
116 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
117 if ((gc != null) && gc.IsValueType)
126 public enum SpecialConstraint
134 /// Tracks the constraints for a type parameter from a generic type definition.
136 public class Constraints : GenericConstraints {
138 ArrayList constraints;
142 // name is the identifier, constraints is an arraylist of
143 // Expressions (with types) or `true' for the constructor constraint.
145 public Constraints (string name, ArrayList constraints,
149 this.constraints = constraints;
153 public override string TypeParameter {
159 GenericParameterAttributes attrs;
160 TypeExpr class_constraint;
161 ArrayList iface_constraints;
162 ArrayList type_param_constraints;
164 Type class_constraint_type;
165 Type[] iface_constraint_types;
166 Type effective_base_type;
171 /// Resolve the constraints - but only resolve things into Expression's, not
172 /// into actual types.
174 public bool Resolve (IResolveContext ec)
179 iface_constraints = new ArrayList ();
180 type_param_constraints = new ArrayList ();
182 foreach (object obj in constraints) {
183 if (HasConstructorConstraint) {
184 Report.Error (401, loc,
185 "The new() constraint must be the last constraint specified");
189 if (obj is SpecialConstraint) {
190 SpecialConstraint sc = (SpecialConstraint) obj;
192 if (sc == SpecialConstraint.Constructor) {
193 if (!HasValueTypeConstraint) {
194 attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
198 Report.Error (451, loc, "The `new()' constraint " +
199 "cannot be used with the `struct' constraint");
203 if ((num_constraints > 0) || HasReferenceTypeConstraint || HasValueTypeConstraint) {
204 Report.Error (449, loc, "The `class' or `struct' " +
205 "constraint must be the first constraint specified");
209 if (sc == SpecialConstraint.ReferenceType)
210 attrs |= GenericParameterAttributes.ReferenceTypeConstraint;
212 attrs |= GenericParameterAttributes.NotNullableValueTypeConstraint;
216 int errors = Report.Errors;
217 FullNamedExpression fn = ((Expression) obj).ResolveAsTypeStep (ec, false);
220 if (errors != Report.Errors)
223 NamespaceEntry.Error_NamespaceNotFound (loc, ((Expression)obj).GetSignatureForError ());
228 ConstructedType cexpr = fn as ConstructedType;
230 if (!cexpr.ResolveConstructedType (ec))
235 expr = ((Expression) obj).ResolveAsTypeTerminal (ec, false);
237 if ((expr == null) || (expr.Type == null))
240 // TODO: It's aleady done in ResolveAsBaseTerminal
241 if (!ec.GenericDeclContainer.AsAccessible (fn.Type, ec.GenericDeclContainer.ModFlags)) {
242 Report.SymbolRelatedToPreviousError (fn.Type);
243 Report.Error (703, loc,
244 "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
245 fn.GetSignatureForError (), ec.GenericDeclContainer.GetSignatureForError ());
249 TypeParameterExpr texpr = expr as TypeParameterExpr;
251 type_param_constraints.Add (expr);
252 else if (expr.IsInterface)
253 iface_constraints.Add (expr);
254 else if (class_constraint != null) {
255 Report.Error (406, loc,
256 "`{0}': the class constraint for `{1}' " +
257 "must come before any other constraints.",
260 } else if (HasReferenceTypeConstraint || HasValueTypeConstraint) {
261 Report.Error (450, loc, "`{0}': cannot specify both " +
262 "a constraint class and the `class' " +
263 "or `struct' constraint", expr.GetSignatureForError ());
266 class_constraint = expr;
271 ArrayList list = new ArrayList ();
272 foreach (TypeExpr iface_constraint in iface_constraints) {
273 foreach (Type type in list) {
274 if (!type.Equals (iface_constraint.Type))
277 Report.Error (405, loc,
278 "Duplicate constraint `{0}' for type " +
279 "parameter `{1}'.", iface_constraint.GetSignatureForError (),
284 list.Add (iface_constraint.Type);
287 foreach (TypeParameterExpr expr in type_param_constraints) {
288 foreach (Type type in list) {
289 if (!type.Equals (expr.Type))
292 Report.Error (405, loc,
293 "Duplicate constraint `{0}' for type " +
294 "parameter `{1}'.", expr.GetSignatureForError (), name);
298 list.Add (expr.Type);
301 iface_constraint_types = new Type [list.Count];
302 list.CopyTo (iface_constraint_types, 0);
304 if (class_constraint != null) {
305 class_constraint_type = class_constraint.Type;
306 if (class_constraint_type == null)
309 if (class_constraint_type.IsSealed) {
310 if (class_constraint_type.IsAbstract)
312 Report.Error (717, loc, "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
313 TypeManager.CSharpName (class_constraint_type));
317 Report.Error (701, loc, "`{0}' is not a valid constraint. A constraint must be an interface, " +
318 "a non-sealed class or a type parameter", TypeManager.CSharpName(class_constraint_type));
323 if ((class_constraint_type == TypeManager.array_type) ||
324 (class_constraint_type == TypeManager.delegate_type) ||
325 (class_constraint_type == TypeManager.enum_type) ||
326 (class_constraint_type == TypeManager.value_type) ||
327 (class_constraint_type == TypeManager.object_type)) {
328 Report.Error (702, loc,
329 "Bound cannot be special class `{0}'",
330 TypeManager.CSharpName (class_constraint_type));
335 if (class_constraint_type != null)
336 effective_base_type = class_constraint_type;
337 else if (HasValueTypeConstraint)
338 effective_base_type = TypeManager.value_type;
340 effective_base_type = TypeManager.object_type;
346 bool CheckTypeParameterConstraints (TypeParameter tparam, Hashtable seen)
348 seen.Add (tparam, true);
350 Constraints constraints = tparam.Constraints;
351 if (constraints == null)
354 if (constraints.HasValueTypeConstraint) {
355 Report.Error (456, loc, "Type parameter `{0}' has " +
356 "the `struct' constraint, so it cannot " +
357 "be used as a constraint for `{1}'",
362 if (constraints.type_param_constraints == null)
365 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
366 if (seen.Contains (expr.TypeParameter)) {
367 Report.Error (454, loc, "Circular constraint " +
368 "dependency involving `{0}' and `{1}'",
369 tparam.Name, expr.Name);
373 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
381 /// Resolve the constraints into actual types.
383 public bool ResolveTypes (IResolveContext ec)
388 resolved_types = true;
390 foreach (object obj in constraints) {
391 ConstructedType cexpr = obj as ConstructedType;
395 if (!cexpr.CheckConstraints (ec))
399 foreach (TypeParameterExpr expr in type_param_constraints) {
400 Hashtable seen = new Hashtable ();
401 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
405 for (int i = 0; i < iface_constraints.Count; ++i) {
406 TypeExpr iface_constraint = (TypeExpr) iface_constraints [i];
407 iface_constraint = iface_constraint.ResolveAsTypeTerminal (ec, false);
408 if (iface_constraint == null)
410 iface_constraints [i] = iface_constraint;
413 if (class_constraint != null) {
414 class_constraint = class_constraint.ResolveAsTypeTerminal (ec, false);
415 if (class_constraint == null)
423 /// Check whether there are no conflicts in our type parameter constraints.
425 /// This is an example:
429 /// where U : T, struct
431 public bool CheckDependencies ()
433 foreach (TypeParameterExpr expr in type_param_constraints) {
434 if (!CheckDependencies (expr.TypeParameter))
441 bool CheckDependencies (TypeParameter tparam)
443 Constraints constraints = tparam.Constraints;
444 if (constraints == null)
447 if (HasValueTypeConstraint && constraints.HasClassConstraint) {
448 Report.Error (455, loc, "Type parameter `{0}' inherits " +
449 "conflicting constraints `{1}' and `{2}'",
450 name, TypeManager.CSharpName (constraints.ClassConstraint),
455 if (HasClassConstraint && constraints.HasClassConstraint) {
456 Type t1 = ClassConstraint;
457 TypeExpr e1 = class_constraint;
458 Type t2 = constraints.ClassConstraint;
459 TypeExpr e2 = constraints.class_constraint;
461 if (!Convert.ImplicitReferenceConversionExists (e1, t2) &&
462 !Convert.ImplicitReferenceConversionExists (e2, t1)) {
463 Report.Error (455, loc,
464 "Type parameter `{0}' inherits " +
465 "conflicting constraints `{1}' and `{2}'",
466 name, TypeManager.CSharpName (t1), TypeManager.CSharpName (t2));
471 if (constraints.type_param_constraints == null)
474 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
475 if (!CheckDependencies (expr.TypeParameter))
482 public override GenericParameterAttributes Attributes {
483 get { return attrs; }
486 public override bool HasClassConstraint {
487 get { return class_constraint != null; }
490 public override Type ClassConstraint {
491 get { return class_constraint_type; }
494 public override Type[] InterfaceConstraints {
495 get { return iface_constraint_types; }
498 public override Type EffectiveBaseClass {
499 get { return effective_base_type; }
502 public bool IsSubclassOf (Type t)
504 if ((class_constraint_type != null) &&
505 class_constraint_type.IsSubclassOf (t))
508 if (iface_constraint_types == null)
511 foreach (Type iface in iface_constraint_types) {
512 if (TypeManager.IsSubclassOf (iface, t))
519 public Location Location {
526 /// This is used when we're implementing a generic interface method.
527 /// Each method type parameter in implementing method must have the same
528 /// constraints than the corresponding type parameter in the interface
529 /// method. To do that, we're called on each of the implementing method's
532 public bool CheckInterfaceMethod (GenericConstraints gc)
534 if (gc.Attributes != attrs)
537 if (HasClassConstraint != gc.HasClassConstraint)
539 if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
542 int gc_icount = gc.InterfaceConstraints != null ?
543 gc.InterfaceConstraints.Length : 0;
544 int icount = InterfaceConstraints != null ?
545 InterfaceConstraints.Length : 0;
547 if (gc_icount != icount)
550 foreach (Type iface in gc.InterfaceConstraints) {
552 foreach (Type check in InterfaceConstraints) {
553 if (TypeManager.IsEqual (iface, check)) {
568 /// A type parameter from a generic type definition.
570 public class TypeParameter : MemberCore, IMemberContainer {
573 GenericConstraints gc;
574 Constraints constraints;
576 GenericTypeParameterBuilder type;
578 public TypeParameter (DeclSpace parent, DeclSpace decl, string name,
579 Constraints constraints, Attributes attrs, Location loc)
580 : base (parent, new MemberName (name, loc), attrs)
584 this.constraints = constraints;
588 public GenericConstraints GenericConstraints {
589 get { return gc != null ? gc : constraints; }
592 public Constraints Constraints {
593 get { return constraints; }
596 public bool HasConstructorConstraint {
597 get { return constraints != null && constraints.HasConstructorConstraint; }
600 public DeclSpace DeclSpace {
609 /// This is the first method which is called during the resolving
610 /// process; we're called immediately after creating the type parameters
611 /// with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
614 /// We're either called from TypeContainer.DefineType() or from
615 /// GenericMethod.Define() (called from Method.Define()).
617 public void Define (GenericTypeParameterBuilder type)
619 if (this.type != null)
620 throw new InvalidOperationException ();
623 TypeManager.AddTypeParameter (type, this);
627 /// This is the second method which is called during the resolving
628 /// process - in case of class type parameters, we're called from
629 /// TypeContainer.ResolveType() - after it resolved the class'es
630 /// base class and interfaces. For method type parameters, we're
631 /// called immediately after Define().
633 /// We're just resolving the constraints into expressions here, we
634 /// don't resolve them into actual types.
636 /// Note that in the special case of partial generic classes, we may be
637 /// called _before_ Define() and we may also be called multiple types.
639 public bool Resolve (DeclSpace ds)
641 if (constraints != null) {
642 if (!constraints.Resolve (ds)) {
652 /// This is the third method which is called during the resolving
653 /// process. We're called immediately after calling DefineConstraints()
654 /// on all of the current class'es type parameters.
656 /// Our job is to resolve the constraints to actual types.
658 /// Note that we may have circular dependencies on type parameters - this
659 /// is why Resolve() and ResolveType() are separate.
661 public bool ResolveType (IResolveContext ec)
663 if (constraints != null) {
664 if (!constraints.ResolveTypes (ec)) {
674 /// This is the fourth and last method which is called during the resolving
675 /// process. We're called after everything is fully resolved and actually
676 /// register the constraints with SRE and the TypeManager.
678 public bool DefineType (IResolveContext ec)
680 return DefineType (ec, null, null, false);
684 /// This is the fith and last method which is called during the resolving
685 /// process. We're called after everything is fully resolved and actually
686 /// register the constraints with SRE and the TypeManager.
688 /// The `builder', `implementing' and `is_override' arguments are only
689 /// applicable to method type parameters.
691 public bool DefineType (IResolveContext ec, MethodBuilder builder,
692 MethodInfo implementing, bool is_override)
694 if (!ResolveType (ec))
697 if (implementing != null) {
698 if (is_override && (constraints != null)) {
699 Report.Error (460, loc,
700 "`{0}': Cannot specify constraints for overrides or explicit interface implementation methods",
701 TypeManager.CSharpSignature (builder));
705 MethodBase mb = TypeManager.DropGenericMethodArguments (implementing);
707 int pos = type.GenericParameterPosition;
708 Type mparam = mb.GetGenericArguments () [pos];
709 GenericConstraints temp_gc = ReflectionConstraints.GetConstraints (mparam);
712 gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
713 else if (constraints != null)
714 gc = new InflatedConstraints (constraints, implementing.DeclaringType);
717 if (constraints != null) {
720 else if (!constraints.CheckInterfaceMethod (gc))
723 if (!is_override && (temp_gc != null))
728 Report.SymbolRelatedToPreviousError (implementing);
731 425, loc, "The constraints for type " +
732 "parameter `{0}' of method `{1}' must match " +
733 "the constraints for type parameter `{2}' " +
734 "of interface method `{3}'. Consider using " +
735 "an explicit interface implementation instead",
736 Name, TypeManager.CSharpSignature (builder),
737 TypeManager.CSharpName (mparam), TypeManager.CSharpSignature (mb));
740 } else if (DeclSpace is Iterator) {
741 TypeParameter[] tparams = DeclSpace.TypeParameters;
742 Type[] types = new Type [tparams.Length];
743 for (int i = 0; i < tparams.Length; i++)
744 types [i] = tparams [i].Type;
746 if (constraints != null)
747 gc = new InflatedConstraints (constraints, types);
749 gc = (GenericConstraints) constraints;
755 if (gc.HasClassConstraint)
756 type.SetBaseTypeConstraint (gc.ClassConstraint);
758 type.SetInterfaceConstraints (gc.InterfaceConstraints);
759 type.SetGenericParameterAttributes (gc.Attributes);
760 TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
766 /// Check whether there are no conflicts in our type parameter constraints.
768 /// This is an example:
772 /// where U : T, struct
774 public bool CheckDependencies ()
776 if (constraints != null)
777 return constraints.CheckDependencies ();
783 /// This is called for each part of a partial generic type definition.
785 /// If `new_constraints' is not null and we don't already have constraints,
786 /// they become our constraints. If we already have constraints, we must
787 /// check that they're the same.
790 public bool UpdateConstraints (IResolveContext ec, Constraints new_constraints)
793 throw new InvalidOperationException ();
795 if (new_constraints == null)
798 if (!new_constraints.Resolve (ec))
800 if (!new_constraints.ResolveTypes (ec))
803 if (constraints != null)
804 return constraints.CheckInterfaceMethod (new_constraints);
806 constraints = new_constraints;
810 public void EmitAttributes ()
812 if (OptAttributes != null)
813 OptAttributes.Emit ();
816 public override string DocCommentHeader {
818 throw new InvalidOperationException (
819 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
827 public override bool Define ()
832 public override void ApplyAttributeBuilder (Attribute a,
833 CustomAttributeBuilder cb)
835 type.SetCustomAttribute (cb);
838 public override AttributeTargets AttributeTargets {
840 return (AttributeTargets) AttributeTargets.GenericParameter;
844 public override string[] ValidAttributeTargets {
846 return new string [] { "type parameter" };
854 string IMemberContainer.Name {
858 MemberCache IMemberContainer.BaseCache {
862 bool IMemberContainer.IsInterface {
866 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
868 return FindMembers (mt, bf, null, null);
871 MemberCache IMemberContainer.MemberCache {
875 public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
876 MemberFilter filter, object criteria)
878 if (constraints == null)
879 return MemberList.Empty;
881 ArrayList members = new ArrayList ();
883 if (gc.HasClassConstraint) {
884 MemberList list = TypeManager.FindMembers (
885 gc.ClassConstraint, mt, bf, filter, criteria);
887 members.AddRange (list);
890 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
891 foreach (Type t in ifaces) {
892 MemberList list = TypeManager.FindMembers (
893 t, mt, bf, filter, criteria);
895 members.AddRange (list);
898 return new MemberList (members);
901 public bool IsSubclassOf (Type t)
906 if (constraints != null)
907 return constraints.IsSubclassOf (t);
912 public override string ToString ()
914 return "TypeParameter[" + name + "]";
917 public static string GetSignatureForError (TypeParameter[] tp)
919 if (tp == null || tp.Length == 0)
922 StringBuilder sb = new StringBuilder ("<");
923 for (int i = 0; i < tp.Length; ++i) {
926 sb.Append (tp[i].GetSignatureForError ());
929 return sb.ToString ();
932 public void InflateConstraints (Type declaring)
934 if (constraints != null)
935 gc = new InflatedConstraints (constraints, declaring);
938 protected class InflatedConstraints : GenericConstraints
940 GenericConstraints gc;
942 Type class_constraint;
943 Type[] iface_constraints;
946 public InflatedConstraints (GenericConstraints gc, Type declaring)
947 : this (gc, TypeManager.GetTypeArguments (declaring))
950 public InflatedConstraints (GenericConstraints gc, Type[] dargs)
955 ArrayList list = new ArrayList ();
956 if (gc.HasClassConstraint)
957 list.Add (inflate (gc.ClassConstraint));
958 foreach (Type iface in gc.InterfaceConstraints)
959 list.Add (inflate (iface));
961 bool has_class_constr = false;
962 if (list.Count > 0) {
963 Type first = (Type) list [0];
964 has_class_constr = !first.IsInterface && !first.IsGenericParameter;
967 if ((list.Count > 0) && has_class_constr) {
968 class_constraint = (Type) list [0];
969 iface_constraints = new Type [list.Count - 1];
970 list.CopyTo (1, iface_constraints, 0, list.Count - 1);
972 iface_constraints = new Type [list.Count];
973 list.CopyTo (iface_constraints, 0);
976 if (HasValueTypeConstraint)
977 base_type = TypeManager.value_type;
978 else if (class_constraint != null)
979 base_type = class_constraint;
981 base_type = TypeManager.object_type;
984 Type inflate (Type t)
988 if (t.IsGenericParameter)
989 return dargs [t.GenericParameterPosition];
990 if (t.IsGenericType) {
991 Type[] args = t.GetGenericArguments ();
992 Type[] inflated = new Type [args.Length];
994 for (int i = 0; i < args.Length; i++)
995 inflated [i] = inflate (args [i]);
997 t = t.GetGenericTypeDefinition ();
998 t = t.MakeGenericType (inflated);
1004 public override string TypeParameter {
1005 get { return gc.TypeParameter; }
1008 public override GenericParameterAttributes Attributes {
1009 get { return gc.Attributes; }
1012 public override Type ClassConstraint {
1013 get { return class_constraint; }
1016 public override Type EffectiveBaseClass {
1017 get { return base_type; }
1020 public override Type[] InterfaceConstraints {
1021 get { return iface_constraints; }
1027 /// A TypeExpr which already resolved to a type parameter.
1029 public class TypeParameterExpr : TypeExpr {
1030 TypeParameter type_parameter;
1032 public override string Name {
1034 return type_parameter.Name;
1038 public override string FullName {
1040 return type_parameter.Name;
1044 public TypeParameter TypeParameter {
1046 return type_parameter;
1050 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1052 this.type_parameter = type_parameter;
1056 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1058 type = type_parameter.Type;
1063 public override bool IsInterface {
1064 get { return false; }
1067 public override bool CheckAccessLevel (DeclSpace ds)
1072 public void Error_CannotUseAsUnmanagedType (Location loc)
1074 Report.Error (-203, loc, "Can not use type parameter as unmanaged type");
1079 /// Tracks the type arguments when instantiating a generic type. We're used in
1080 /// ConstructedType.
1082 public class TypeArguments {
1083 public readonly Location Location;
1090 public TypeArguments (Location loc)
1092 args = new ArrayList ();
1093 this.Location = loc;
1096 public TypeArguments (int dimension, Location loc)
1098 this.dimension = dimension;
1099 this.Location = loc;
1102 public void Add (Expression type)
1105 throw new InvalidOperationException ();
1110 public void Add (TypeArguments new_args)
1113 throw new InvalidOperationException ();
1115 args.AddRange (new_args.args);
1119 /// We're used during the parsing process: the parser can't distinguish
1120 /// between type parameters and type arguments. Because of that, the
1121 /// parser creates a `MemberName' with `TypeArguments' for both cases and
1122 /// in case of a generic type definition, we call GetDeclarations().
1124 public TypeParameterName[] GetDeclarations ()
1126 TypeParameterName[] ret = new TypeParameterName [args.Count];
1127 for (int i = 0; i < args.Count; i++) {
1128 TypeParameterName name = args [i] as TypeParameterName;
1133 SimpleName sn = args [i] as SimpleName;
1135 ret [i] = new TypeParameterName (sn.Name, null, sn.Location);
1139 Report.Error (81, Location, "Type parameter declaration " +
1140 "must be an identifier not a type");
1147 /// We may only be used after Resolve() is called and return the fully
1150 public Type[] Arguments {
1156 public bool HasTypeArguments {
1158 return has_type_args;
1171 public bool IsUnbound {
1173 return dimension > 0;
1177 public override string ToString ()
1179 StringBuilder s = new StringBuilder ();
1182 for (int i = 0; i < count; i++){
1184 // FIXME: Use TypeManager.CSharpname once we have the type
1187 s.Append (args [i].ToString ());
1191 return s.ToString ();
1194 public string GetSignatureForError()
1196 StringBuilder sb = new StringBuilder();
1197 for (int i = 0; i < Count; ++i)
1199 Expression expr = (Expression)args [i];
1200 sb.Append(expr.GetSignatureForError());
1204 return sb.ToString();
1208 /// Resolve the type arguments.
1210 public bool Resolve (IResolveContext ec)
1212 int count = args.Count;
1215 atypes = new Type [count];
1217 for (int i = 0; i < count; i++){
1218 TypeExpr te = ((Expression) args [i]).ResolveAsTypeTerminal (ec, false);
1223 if (te is TypeParameterExpr)
1224 has_type_args = true;
1226 if (te.Type.IsSealed && te.Type.IsAbstract) {
1227 Report.Error (718, Location, "`{0}': static classes cannot be used as generic arguments",
1228 te.GetSignatureForError ());
1231 if (te.Type.IsPointer) {
1232 Report.Error (306, Location, "The type `{0}' may not be used " +
1233 "as a type argument", TypeManager.CSharpName (te.Type));
1237 if (te.Type == TypeManager.void_type) {
1238 Expression.Error_VoidInvalidInTheContext (Location);
1242 atypes [i] = te.Type;
1248 public class TypeParameterName : SimpleName
1250 Attributes attributes;
1252 public TypeParameterName (string name, Attributes attrs, Location loc)
1258 public Attributes OptAttributes {
1266 /// An instantiation of a generic type.
1268 public class ConstructedType : TypeExpr {
1270 FullNamedExpression name;
1272 Type[] gen_params, atypes;
1276 /// Instantiate the generic type `fname' with the type arguments `args'.
1278 public ConstructedType (FullNamedExpression fname, TypeArguments args, Location l)
1284 eclass = ExprClass.Type;
1285 full_name = name + "<" + args.ToString () + ">";
1288 protected ConstructedType (TypeArguments args, Location l)
1293 eclass = ExprClass.Type;
1296 protected ConstructedType (TypeParameter[] type_params, Location l)
1300 args = new TypeArguments (l);
1301 foreach (TypeParameter type_param in type_params)
1302 args.Add (new TypeParameterExpr (type_param, l));
1304 eclass = ExprClass.Type;
1308 /// This is used to construct the `this' type inside a generic type definition.
1310 public ConstructedType (Type t, TypeParameter[] type_params, Location l)
1311 : this (type_params, l)
1313 gt = t.GetGenericTypeDefinition ();
1315 this.name = new TypeExpression (gt, l);
1316 full_name = gt.FullName + "<" + args.ToString () + ">";
1320 /// Instantiate the generic type `t' with the type arguments `args'.
1321 /// Use this constructor if you already know the fully resolved
1324 public ConstructedType (Type t, TypeArguments args, Location l)
1327 gt = t.GetGenericTypeDefinition ();
1329 this.name = new TypeExpression (gt, l);
1330 full_name = gt.FullName + "<" + args.ToString () + ">";
1333 public TypeArguments TypeArguments {
1334 get { return args; }
1337 public override string GetSignatureForError ()
1339 return TypeManager.RemoveGenericArity (gt.FullName) + "<" + args.GetSignatureForError () + ">";
1342 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1344 if (!ResolveConstructedType (ec))
1351 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1352 /// after fully resolving the constructed type.
1354 public bool CheckConstraints (IResolveContext ec)
1356 return ConstraintChecker.CheckConstraints (ec, gt, gen_params, atypes, loc);
1360 /// Resolve the constructed type, but don't check the constraints.
1362 public bool ResolveConstructedType (IResolveContext ec)
1366 // If we already know the fully resolved generic type.
1368 return DoResolveType (ec);
1374 Report.Error (246, loc, "Cannot find type `{0}'<...>", Name);
1378 num_args = TypeManager.GetNumberOfTypeArguments (t);
1379 if (num_args == 0) {
1380 Report.Error (308, loc,
1381 "The non-generic type `{0}' cannot " +
1382 "be used with type arguments.",
1383 TypeManager.CSharpName (t));
1387 gt = t.GetGenericTypeDefinition ();
1388 return DoResolveType (ec);
1391 bool DoResolveType (IResolveContext ec)
1394 // Resolve the arguments.
1396 if (args.Resolve (ec) == false)
1399 gen_params = gt.GetGenericArguments ();
1400 atypes = args.Arguments;
1402 if (atypes.Length != gen_params.Length) {
1403 Report.Error (305, loc,
1404 "Using the generic type `{0}' " +
1405 "requires {1} type arguments",
1406 TypeManager.CSharpName (gt),
1407 gen_params.Length.ToString ());
1412 // Now bind the parameters.
1414 type = gt.MakeGenericType (atypes);
1418 public Expression GetSimpleName (EmitContext ec)
1423 public override bool CheckAccessLevel (DeclSpace ds)
1425 return ds.CheckAccessLevel (gt);
1428 public override bool AsAccessible (DeclSpace ds, int flags)
1430 return ds.AsAccessible (gt, flags);
1433 public override bool IsClass {
1434 get { return gt.IsClass; }
1437 public override bool IsValueType {
1438 get { return gt.IsValueType; }
1441 public override bool IsInterface {
1442 get { return gt.IsInterface; }
1445 public override bool IsSealed {
1446 get { return gt.IsSealed; }
1449 public override bool Equals (object obj)
1451 ConstructedType cobj = obj as ConstructedType;
1455 if ((type == null) || (cobj.type == null))
1458 return type == cobj.type;
1461 public override int GetHashCode ()
1463 return base.GetHashCode ();
1466 public override string Name {
1473 public override string FullName {
1480 public abstract class ConstraintChecker
1482 protected readonly Type[] gen_params;
1483 protected readonly Type[] atypes;
1484 protected readonly Location loc;
1486 protected ConstraintChecker (Type[] gen_params, Type[] atypes, Location loc)
1488 this.gen_params = gen_params;
1489 this.atypes = atypes;
1494 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1495 /// after fully resolving the constructed type.
1497 public bool CheckConstraints (IResolveContext ec)
1499 for (int i = 0; i < gen_params.Length; i++) {
1500 if (!CheckConstraints (ec, i))
1507 protected bool CheckConstraints (IResolveContext ec, int index)
1509 Type atype = atypes [index];
1510 Type ptype = gen_params [index];
1515 Expression aexpr = new EmptyExpression (atype);
1517 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1521 bool is_class, is_struct;
1522 if (atype.IsGenericParameter) {
1523 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1525 if (agc is Constraints)
1526 ((Constraints) agc).Resolve (ec);
1527 is_class = agc.HasReferenceTypeConstraint;
1528 is_struct = agc.HasValueTypeConstraint;
1530 is_class = is_struct = false;
1535 if (!atype.IsGenericType)
1537 is_class = atype.IsClass || atype.IsInterface;
1538 is_struct = atype.IsValueType && !TypeManager.IsNullableType (atype);
1542 // First, check the `class' and `struct' constraints.
1544 if (gc.HasReferenceTypeConstraint && !is_class) {
1545 Report.Error (452, loc, "The type `{0}' must be " +
1546 "a reference type in order to use it " +
1547 "as type parameter `{1}' in the " +
1548 "generic type or method `{2}'.",
1549 TypeManager.CSharpName (atype),
1550 TypeManager.CSharpName (ptype),
1551 GetSignatureForError ());
1553 } else if (gc.HasValueTypeConstraint && !is_struct) {
1554 Report.Error (453, loc, "The type `{0}' must be a " +
1555 "non-nullable value type in order to use it " +
1556 "as type parameter `{1}' in the " +
1557 "generic type or method `{2}'.",
1558 TypeManager.CSharpName (atype),
1559 TypeManager.CSharpName (ptype),
1560 GetSignatureForError ());
1565 // The class constraint comes next.
1567 if (gc.HasClassConstraint) {
1568 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint))
1573 // Now, check the interface constraints.
1575 if (gc.InterfaceConstraints != null) {
1576 foreach (Type it in gc.InterfaceConstraints) {
1577 if (!CheckConstraint (ec, ptype, aexpr, it))
1583 // Finally, check the constructor constraint.
1586 if (!gc.HasConstructorConstraint)
1589 if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
1592 if (HasDefaultConstructor (ec.DeclContainer.TypeBuilder, atype))
1595 Report_SymbolRelatedToPreviousError ();
1596 Report.SymbolRelatedToPreviousError (atype);
1597 Report.Error (310, loc, "The type `{0}' must have a public " +
1598 "parameterless constructor in order to use it " +
1599 "as parameter `{1}' in the generic type or " +
1601 TypeManager.CSharpName (atype),
1602 TypeManager.CSharpName (ptype),
1603 GetSignatureForError ());
1607 protected bool CheckConstraint (IResolveContext ec, Type ptype, Expression expr,
1610 if (TypeManager.HasGenericArguments (ctype)) {
1611 Type[] types = TypeManager.GetTypeArguments (ctype);
1613 TypeArguments new_args = new TypeArguments (loc);
1615 for (int i = 0; i < types.Length; i++) {
1618 if (t.IsGenericParameter) {
1619 int pos = t.GenericParameterPosition;
1622 new_args.Add (new TypeExpression (t, loc));
1625 TypeExpr ct = new ConstructedType (ctype, new_args, loc);
1626 if (ct.ResolveAsTypeStep (ec, false) == null)
1629 } else if (ctype.IsGenericParameter) {
1630 int pos = ctype.GenericParameterPosition;
1631 ctype = atypes [pos];
1634 if (Convert.ImplicitStandardConversionExists (expr, ctype))
1637 Error_TypeMustBeConvertible (expr.Type, ctype, ptype);
1641 bool HasDefaultConstructor (Type containerType, Type atype)
1643 if (atype.IsAbstract)
1647 atype = TypeManager.DropGenericTypeArguments (atype);
1648 if (atype is TypeBuilder) {
1649 TypeContainer tc = TypeManager.LookupTypeContainer (atype);
1650 if (tc.InstanceConstructors == null) {
1651 atype = atype.BaseType;
1655 foreach (Constructor c in tc.InstanceConstructors) {
1656 if ((c.ModFlags & Modifiers.PUBLIC) == 0)
1658 if ((c.Parameters.FixedParameters != null) &&
1659 (c.Parameters.FixedParameters.Length != 0))
1661 if (c.Parameters.HasArglist || c.Parameters.HasParams)
1668 TypeParameter tparam = TypeManager.LookupTypeParameter (atype);
1670 return tparam.HasConstructorConstraint;
1672 MemberList list = TypeManager.FindMembers (
1673 atype, MemberTypes.Constructor,
1674 BindingFlags.Public | BindingFlags.Instance |
1675 BindingFlags.DeclaredOnly, null, null);
1677 if (atype.IsAbstract || (list == null))
1680 foreach (MethodBase mb in list) {
1681 ParameterData pd = TypeManager.GetParameterData (mb);
1682 if ((pd.Count == 0) && mb.IsPublic && !mb.IsStatic)
1689 protected abstract string GetSignatureForError ();
1690 protected abstract void Report_SymbolRelatedToPreviousError ();
1692 void Error_TypeMustBeConvertible (Type atype, Type gc, Type ptype)
1694 Report_SymbolRelatedToPreviousError ();
1695 Report.SymbolRelatedToPreviousError (atype);
1696 Report.Error (309, loc,
1697 "The type `{0}' must be convertible to `{1}' in order to " +
1698 "use it as parameter `{2}' in the generic type or method `{3}'",
1699 TypeManager.CSharpName (atype), TypeManager.CSharpName (gc),
1700 TypeManager.CSharpName (ptype), GetSignatureForError ());
1703 public static bool CheckConstraints (EmitContext ec, MethodBase definition,
1704 MethodBase instantiated, Location loc)
1706 MethodConstraintChecker checker = new MethodConstraintChecker (
1707 definition, definition.GetGenericArguments (),
1708 instantiated.GetGenericArguments (), loc);
1710 return checker.CheckConstraints (ec);
1713 public static bool CheckConstraints (IResolveContext ec, Type gt, Type[] gen_params,
1714 Type[] atypes, Location loc)
1716 TypeConstraintChecker checker = new TypeConstraintChecker (
1717 gt, gen_params, atypes, loc);
1719 return checker.CheckConstraints (ec);
1722 protected class MethodConstraintChecker : ConstraintChecker
1724 MethodBase definition;
1726 public MethodConstraintChecker (MethodBase definition, Type[] gen_params,
1727 Type[] atypes, Location loc)
1728 : base (gen_params, atypes, loc)
1730 this.definition = definition;
1733 protected override string GetSignatureForError ()
1735 return TypeManager.CSharpSignature (definition);
1738 protected override void Report_SymbolRelatedToPreviousError ()
1740 Report.SymbolRelatedToPreviousError (definition);
1744 protected class TypeConstraintChecker : ConstraintChecker
1748 public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
1750 : base (gen_params, atypes, loc)
1755 protected override string GetSignatureForError ()
1757 return TypeManager.CSharpName (gt);
1760 protected override void Report_SymbolRelatedToPreviousError ()
1762 Report.SymbolRelatedToPreviousError (gt);
1768 /// A generic method definition.
1770 public class GenericMethod : DeclSpace
1772 Expression return_type;
1773 Parameters parameters;
1775 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
1776 Expression return_type, Parameters parameters)
1777 : base (ns, parent, name, null)
1779 this.return_type = return_type;
1780 this.parameters = parameters;
1783 public override TypeBuilder DefineType ()
1785 throw new Exception ();
1788 public override bool Define ()
1790 for (int i = 0; i < TypeParameters.Length; i++)
1791 if (!TypeParameters [i].Resolve (this))
1798 /// Define and resolve the type parameters.
1799 /// We're called from Method.Define().
1801 public bool Define (MethodBuilder mb, ToplevelBlock block)
1803 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1804 string[] snames = new string [names.Length];
1805 for (int i = 0; i < names.Length; i++) {
1806 string type_argument_name = names[i].Name;
1807 Parameter p = parameters.GetParameterByName (type_argument_name);
1809 Error_ParameterNameCollision (p.Location, type_argument_name, "method parameter");
1812 if (block != null) {
1813 LocalInfo li = (LocalInfo)block.Variables[type_argument_name];
1815 Error_ParameterNameCollision (li.Location, type_argument_name, "local variable");
1819 snames[i] = type_argument_name;
1822 GenericTypeParameterBuilder[] gen_params = mb.DefineGenericParameters (snames);
1823 for (int i = 0; i < TypeParameters.Length; i++)
1824 TypeParameters [i].Define (gen_params [i]);
1829 for (int i = 0; i < TypeParameters.Length; i++) {
1830 if (!TypeParameters [i].ResolveType (this))
1837 static void Error_ParameterNameCollision (Location loc, string name, string collisionWith)
1839 Report.Error (412, loc, "The type parameter name `{0}' is the same as `{1}'",
1840 name, collisionWith);
1844 /// We're called from MethodData.Define() after creating the MethodBuilder.
1846 public bool DefineType (EmitContext ec, MethodBuilder mb,
1847 MethodInfo implementing, bool is_override)
1849 for (int i = 0; i < TypeParameters.Length; i++)
1850 if (!TypeParameters [i].DefineType (
1851 ec, mb, implementing, is_override))
1855 foreach (Parameter p in parameters.FixedParameters){
1856 if (!p.Resolve (ec))
1859 if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec, false) == null))
1865 public void EmitAttributes ()
1867 for (int i = 0; i < TypeParameters.Length; i++)
1868 TypeParameters [i].EmitAttributes ();
1870 if (OptAttributes != null)
1871 OptAttributes.Emit ();
1874 public override bool DefineMembers ()
1879 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1880 MemberFilter filter, object criteria)
1882 throw new Exception ();
1885 public override MemberCache MemberCache {
1891 public override AttributeTargets AttributeTargets {
1893 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1897 public override string DocCommentHeader {
1898 get { return "M:"; }
1902 public class DefaultValueExpression : Expression
1906 public DefaultValueExpression (Expression expr, Location loc)
1912 public override Expression DoResolve (EmitContext ec)
1914 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
1920 eclass = ExprClass.Variable;
1924 public override void Emit (EmitContext ec)
1926 if (type.IsGenericParameter || TypeManager.IsValueType (type)) {
1927 LocalTemporary temp_storage = new LocalTemporary (type);
1929 temp_storage.AddressOf (ec, AddressOp.LoadStore);
1930 ec.ig.Emit (OpCodes.Initobj, type);
1931 temp_storage.Emit (ec);
1933 ec.ig.Emit (OpCodes.Ldnull);
1937 public class NullableType : TypeExpr
1939 Expression underlying;
1941 public NullableType (Expression underlying, Location l)
1943 this.underlying = underlying;
1946 eclass = ExprClass.Type;
1949 public NullableType (Type type, Location loc)
1950 : this (new TypeExpression (type, loc), loc)
1953 public override string Name {
1954 get { return underlying.ToString () + "?"; }
1957 public override string FullName {
1958 get { return underlying.ToString () + "?"; }
1961 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1963 TypeArguments args = new TypeArguments (loc);
1964 args.Add (underlying);
1966 ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
1967 return ctype.ResolveAsTypeTerminal (ec, false);
1971 public partial class TypeManager
1974 // A list of core types that the compiler requires or uses
1976 static public Type activator_type;
1977 static public Type generic_ilist_type;
1978 static public Type generic_icollection_type;
1979 static public Type generic_ienumerator_type;
1980 static public Type generic_ienumerable_type;
1981 static public Type generic_nullable_type;
1984 // Tracks the generic parameters.
1986 static PtrHashtable builder_to_type_param;
1989 // These methods are called by code generated by the compiler
1991 static public MethodInfo activator_create_instance;
1993 static void InitGenerics ()
1995 builder_to_type_param = new PtrHashtable ();
1998 static void CleanUpGenerics ()
2000 builder_to_type_param = null;
2003 static void InitGenericCoreTypes ()
2005 activator_type = CoreLookupType ("System", "Activator");
2007 generic_ilist_type = CoreLookupType (
2008 "System.Collections.Generic", "IList", 1);
2009 generic_icollection_type = CoreLookupType (
2010 "System.Collections.Generic", "ICollection", 1);
2011 generic_ienumerator_type = CoreLookupType (
2012 "System.Collections.Generic", "IEnumerator", 1);
2013 generic_ienumerable_type = CoreLookupType (
2014 "System.Collections.Generic", "IEnumerable", 1);
2015 generic_nullable_type = CoreLookupType (
2016 "System", "Nullable", 1);
2019 static void InitGenericCodeHelpers ()
2022 Type [] type_arg = { type_type };
2023 activator_create_instance = GetMethod (
2024 activator_type, "CreateInstance", type_arg);
2027 static Type CoreLookupType (string ns, string name, int arity)
2029 return CoreLookupType (ns, MemberName.MakeName (name, arity));
2032 public static void AddTypeParameter (Type t, TypeParameter tparam)
2034 if (!builder_to_type_param.Contains (t))
2035 builder_to_type_param.Add (t, tparam);
2038 public static TypeContainer LookupGenericTypeContainer (Type t)
2040 t = DropGenericTypeArguments (t);
2041 return LookupTypeContainer (t);
2044 public static TypeParameter LookupTypeParameter (Type t)
2046 return (TypeParameter) builder_to_type_param [t];
2049 public static GenericConstraints GetTypeParameterConstraints (Type t)
2051 if (!t.IsGenericParameter)
2052 throw new InvalidOperationException ();
2054 TypeParameter tparam = LookupTypeParameter (t);
2056 return tparam.GenericConstraints;
2058 return ReflectionConstraints.GetConstraints (t);
2061 public static bool HasGenericArguments (Type t)
2063 return GetNumberOfTypeArguments (t) > 0;
2066 public static Type[] GetTypeArguments (Type t)
2068 DeclSpace tc = LookupDeclSpace (t);
2071 return Type.EmptyTypes;
2073 TypeParameter[] tparam = tc.TypeParameters;
2074 Type[] ret = new Type [tparam.Length];
2075 for (int i = 0; i < tparam.Length; i++) {
2076 ret [i] = tparam [i].Type;
2077 if (ret [i] == null)
2078 throw new InternalErrorException ();
2083 return t.GetGenericArguments ();
2086 public static Type DropGenericTypeArguments (Type t)
2088 if (!t.IsGenericType)
2090 // Micro-optimization: a generic typebuilder is always a generic type definition
2091 if (t is TypeBuilder)
2093 return t.GetGenericTypeDefinition ();
2096 public static MethodBase DropGenericMethodArguments (MethodBase m)
2098 if (m.IsGenericMethodDefinition)
2100 if (m.IsGenericMethod)
2101 return ((MethodInfo) m).GetGenericMethodDefinition ();
2102 if (!m.DeclaringType.IsGenericType)
2105 Type t = m.DeclaringType.GetGenericTypeDefinition ();
2106 BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
2107 BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
2109 if (m is ConstructorInfo) {
2110 foreach (ConstructorInfo c in t.GetConstructors (bf))
2111 if (c.MetadataToken == m.MetadataToken)
2114 foreach (MethodBase mb in t.GetMethods (bf))
2115 if (mb.MetadataToken == m.MetadataToken)
2122 public static FieldInfo GetGenericFieldDefinition (FieldInfo fi)
2124 if (fi.DeclaringType.IsGenericTypeDefinition ||
2125 !fi.DeclaringType.IsGenericType)
2128 Type t = fi.DeclaringType.GetGenericTypeDefinition ();
2129 BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
2130 BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
2132 foreach (FieldInfo f in t.GetFields (bf))
2133 if (f.MetadataToken == fi.MetadataToken)
2139 public static bool IsEqual (Type a, Type b)
2144 if (a.IsGenericParameter && b.IsGenericParameter) {
2145 if (a.DeclaringMethod != b.DeclaringMethod &&
2146 (a.DeclaringMethod == null || b.DeclaringMethod == null))
2148 return a.GenericParameterPosition == b.GenericParameterPosition;
2151 if (a.IsArray && b.IsArray) {
2152 if (a.GetArrayRank () != b.GetArrayRank ())
2154 return IsEqual (a.GetElementType (), b.GetElementType ());
2157 if (a.IsByRef && b.IsByRef)
2158 return IsEqual (a.GetElementType (), b.GetElementType ());
2160 if (a.IsGenericType && b.IsGenericType) {
2161 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2164 Type[] aargs = a.GetGenericArguments ();
2165 Type[] bargs = b.GetGenericArguments ();
2167 if (aargs.Length != bargs.Length)
2170 for (int i = 0; i < aargs.Length; i++) {
2171 if (!IsEqual (aargs [i], bargs [i]))
2182 /// Check whether `a' and `b' may become equal generic types.
2183 /// The algorithm to do that is a little bit complicated.
2185 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_infered,
2186 Type[] method_infered)
2188 if (a.IsGenericParameter) {
2190 // If a is an array of a's type, they may never
2194 b = b.GetElementType ();
2200 // If b is a generic parameter or an actual type,
2201 // they may become equal:
2203 // class X<T,U> : I<T>, I<U>
2204 // class X<T> : I<T>, I<float>
2206 if (b.IsGenericParameter || !b.IsGenericType) {
2207 int pos = a.GenericParameterPosition;
2208 Type[] args = a.DeclaringMethod != null ? method_infered : class_infered;
2209 if (args [pos] == null) {
2214 return args [pos] == a;
2218 // We're now comparing a type parameter with a
2219 // generic instance. They may become equal unless
2220 // the type parameter appears anywhere in the
2221 // generic instance:
2223 // class X<T,U> : I<T>, I<X<U>>
2224 // -> error because you could instanciate it as
2227 // class X<T> : I<T>, I<X<T>> -> ok
2230 Type[] bargs = GetTypeArguments (b);
2231 for (int i = 0; i < bargs.Length; i++) {
2232 if (a.Equals (bargs [i]))
2239 if (b.IsGenericParameter)
2240 return MayBecomeEqualGenericTypes (b, a, class_infered, method_infered);
2243 // At this point, neither a nor b are a type parameter.
2245 // If one of them is a generic instance, let
2246 // MayBecomeEqualGenericInstances() compare them (if the
2247 // other one is not a generic instance, they can never
2251 if (a.IsGenericType || b.IsGenericType)
2252 return MayBecomeEqualGenericInstances (a, b, class_infered, method_infered);
2255 // If both of them are arrays.
2258 if (a.IsArray && b.IsArray) {
2259 if (a.GetArrayRank () != b.GetArrayRank ())
2262 a = a.GetElementType ();
2263 b = b.GetElementType ();
2265 return MayBecomeEqualGenericTypes (a, b, class_infered, method_infered);
2269 // Ok, two ordinary types.
2272 return a.Equals (b);
2276 // Checks whether two generic instances may become equal for some
2277 // particular instantiation (26.3.1).
2279 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
2280 Type[] class_infered,
2281 Type[] method_infered)
2283 if (!a.IsGenericType || !b.IsGenericType)
2285 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2288 return MayBecomeEqualGenericInstances (
2289 GetTypeArguments (a), GetTypeArguments (b), class_infered, method_infered);
2292 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
2293 Type[] class_infered,
2294 Type[] method_infered)
2296 if (aargs.Length != bargs.Length)
2299 for (int i = 0; i < aargs.Length; i++) {
2300 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_infered, method_infered))
2308 /// Whether `mb' is a generic method definition.
2310 public static bool IsGenericMethodDefinition (MethodBase mb)
2312 if (mb.DeclaringType is TypeBuilder) {
2313 IMethodData method = (IMethodData) builder_to_method [mb];
2317 return method.GenericMethod != null;
2320 return mb.IsGenericMethodDefinition;
2324 /// Whether `mb' is a generic method definition.
2326 public static bool IsGenericMethod (MethodBase mb)
2328 if (mb.DeclaringType is TypeBuilder) {
2329 IMethodData method = (IMethodData) builder_to_method [mb];
2333 return method.GenericMethod != null;
2336 return mb.IsGenericMethod;
2343 static bool InferType (Type pt, Type at, Type[] infered)
2345 if (pt.IsGenericParameter) {
2346 if (pt.DeclaringMethod == null)
2349 int pos = pt.GenericParameterPosition;
2351 if (infered [pos] == null) {
2356 if (infered [pos] != at)
2362 if (!pt.ContainsGenericParameters) {
2363 if (at.ContainsGenericParameters)
2364 return InferType (at, pt, infered);
2371 if (at.GetArrayRank () != pt.GetArrayRank ())
2374 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2377 if (!pt.IsGenericType)
2380 Type gt = pt.GetGenericTypeDefinition ();
2381 if ((gt != generic_ilist_type) && (gt != generic_icollection_type) &&
2382 (gt != generic_ienumerable_type))
2385 Type[] args = GetTypeArguments (pt);
2386 return InferType (args [0], at.GetElementType (), infered);
2391 (pt.GetArrayRank () != at.GetArrayRank ()))
2394 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2397 if (pt.IsByRef && at.IsByRef)
2398 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2399 ArrayList list = new ArrayList ();
2400 if (at.IsGenericType)
2402 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
2405 list.AddRange (TypeManager.GetInterfaces (at));
2407 bool found_one = false;
2409 foreach (Type type in list) {
2410 if (!type.IsGenericType)
2413 Type[] infered_types = new Type [infered.Length];
2415 if (!InferGenericInstance (pt, type, infered_types))
2418 for (int i = 0; i < infered_types.Length; i++) {
2419 if (infered [i] == null) {
2420 infered [i] = infered_types [i];
2424 if (infered [i] != infered_types [i])
2434 static bool InferGenericInstance (Type pt, Type at, Type[] infered_types)
2436 Type[] at_args = at.GetGenericArguments ();
2437 Type[] pt_args = pt.GetGenericArguments ();
2439 if (at_args.Length != pt_args.Length)
2442 for (int i = 0; i < at_args.Length; i++) {
2443 if (!InferType (pt_args [i], at_args [i], infered_types))
2447 for (int i = 0; i < infered_types.Length; i++) {
2448 if (infered_types [i] == null)
2456 /// Type inference. Try to infer the type arguments from the params method
2457 /// `method', which is invoked with the arguments `arguments'. This is used
2458 /// when resolving an Invocation or a DelegateInvocation and the user
2459 /// did not explicitly specify type arguments.
2461 public static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
2462 ref MethodBase method)
2464 if (!TypeManager.IsGenericMethod (method))
2467 // if there are no arguments, there's no way to infer the type-arguments
2468 if (arguments == null || arguments.Count == 0)
2471 ParameterData pd = TypeManager.GetParameterData (method);
2472 int pd_count = pd.Count;
2473 int arg_count = arguments.Count;
2478 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2481 if (pd_count - 1 > arg_count)
2484 Type[] method_args = method.GetGenericArguments ();
2485 Type[] infered_types = new Type [method_args.Length];
2488 // If we have come this far, the case which
2489 // remains is when the number of parameters is
2490 // less than or equal to the argument count.
2492 for (int i = 0; i < pd_count - 1; ++i) {
2493 Argument a = (Argument) arguments [i];
2495 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2498 Type pt = pd.ParameterType (i);
2501 if (!InferType (pt, at, infered_types))
2505 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
2507 for (int i = pd_count - 1; i < arg_count; i++) {
2508 Argument a = (Argument) arguments [i];
2510 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2513 if (!InferType (element_type, a.Type, infered_types))
2517 for (int i = 0; i < infered_types.Length; i++)
2518 if (infered_types [i] == null)
2521 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2525 static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
2526 Type[] infered_types)
2528 if (infered_types == null)
2531 for (int i = 0; i < arg_types.Length; i++) {
2532 if (arg_types [i] == null)
2535 if (!InferType (param_types [i], arg_types [i], infered_types))
2539 for (int i = 0; i < infered_types.Length; i++)
2540 if (infered_types [i] == null)
2547 /// Type inference. Try to infer the type arguments from `method',
2548 /// which is invoked with the arguments `arguments'. This is used
2549 /// when resolving an Invocation or a DelegateInvocation and the user
2550 /// did not explicitly specify type arguments.
2552 public static bool InferTypeArguments (ArrayList arguments,
2553 ref MethodBase method)
2555 if (!TypeManager.IsGenericMethod (method))
2559 if (arguments != null)
2560 arg_count = arguments.Count;
2564 ParameterData pd = TypeManager.GetParameterData (method);
2565 if (arg_count != pd.Count)
2568 Type[] method_args = method.GetGenericArguments ();
2570 bool is_open = false;
2571 for (int i = 0; i < method_args.Length; i++) {
2572 if (method_args [i].IsGenericParameter) {
2578 // If none of the method parameters mention a generic parameter, we can't infer the generic parameters
2580 return !TypeManager.IsGenericMethodDefinition (method);
2582 Type[] infered_types = new Type [method_args.Length];
2584 Type[] param_types = new Type [pd.Count];
2585 Type[] arg_types = new Type [pd.Count];
2587 for (int i = 0; i < arg_count; i++) {
2588 param_types [i] = pd.ParameterType (i);
2590 Argument a = (Argument) arguments [i];
2591 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr) ||
2592 (a.Expr is AnonymousMethod))
2595 arg_types [i] = a.Type;
2598 if (!InferTypeArguments (param_types, arg_types, infered_types))
2601 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2608 public static bool InferTypeArguments (ParameterData apd,
2609 ref MethodBase method)
2611 if (!TypeManager.IsGenericMethod (method))
2614 ParameterData pd = TypeManager.GetParameterData (method);
2615 if (apd.Count != pd.Count)
2618 Type[] method_args = method.GetGenericArguments ();
2619 Type[] infered_types = new Type [method_args.Length];
2621 Type[] param_types = new Type [pd.Count];
2622 Type[] arg_types = new Type [pd.Count];
2624 for (int i = 0; i < apd.Count; i++) {
2625 param_types [i] = pd.ParameterType (i);
2626 arg_types [i] = apd.ParameterType (i);
2629 if (!InferTypeArguments (param_types, arg_types, infered_types))
2632 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2636 public static bool IsNullableType (Type t)
2638 return generic_nullable_type == DropGenericTypeArguments (t);
2641 public static bool IsNullableTypeOf (Type t, Type nullable)
2643 if (!IsNullableType (t))
2646 return GetTypeArguments (t) [0] == nullable;
2649 public static bool IsNullableValueType (Type t)
2651 if (!IsNullableType (t))
2654 return GetTypeArguments (t) [0].IsValueType;
2658 public abstract class Nullable
2660 public sealed class NullableInfo
2662 public readonly Type Type;
2663 public readonly Type UnderlyingType;
2664 public readonly MethodInfo HasValue;
2665 public readonly MethodInfo Value;
2666 public readonly ConstructorInfo Constructor;
2668 public NullableInfo (Type type)
2671 UnderlyingType = TypeManager.GetTypeArguments (type) [0];
2673 PropertyInfo has_value_pi = TypeManager.GetProperty (type, "HasValue");
2674 PropertyInfo value_pi = TypeManager.GetProperty (type, "Value");
2676 HasValue = has_value_pi.GetGetMethod (false);
2677 Value = value_pi.GetGetMethod (false);
2678 Constructor = type.GetConstructor (new Type[] { UnderlyingType });
2682 public class Unwrap : Expression, IMemoryLocation, IAssignMethod
2687 LocalTemporary temp;
2690 protected Unwrap (Expression expr)
2693 this.loc = expr.Location;
2696 public static Unwrap Create (Expression expr, EmitContext ec)
2698 return new Unwrap (expr).Resolve (ec) as Unwrap;
2701 public override Expression DoResolve (EmitContext ec)
2703 expr = expr.Resolve (ec);
2707 temp = new LocalTemporary (expr.Type);
2709 info = new NullableInfo (expr.Type);
2710 type = info.UnderlyingType;
2711 eclass = expr.eclass;
2715 public override void Emit (EmitContext ec)
2717 AddressOf (ec, AddressOp.LoadStore);
2718 ec.ig.EmitCall (OpCodes.Call, info.Value, null);
2721 public void EmitCheck (EmitContext ec)
2723 AddressOf (ec, AddressOp.LoadStore);
2724 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
2727 public void Store (EmitContext ec)
2732 void create_temp (EmitContext ec)
2734 if ((temp != null) && !has_temp) {
2741 public void AddressOf (EmitContext ec, AddressOp mode)
2745 temp.AddressOf (ec, AddressOp.LoadStore);
2747 ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
2750 public void Emit (EmitContext ec, bool leave_copy)
2763 public void EmitAssign (EmitContext ec, Expression source,
2764 bool leave_copy, bool prepare_for_load)
2766 InternalWrap wrap = new InternalWrap (source, info, loc);
2767 ((IAssignMethod) expr).EmitAssign (ec, wrap, leave_copy, false);
2770 protected class InternalWrap : Expression
2772 public Expression expr;
2773 public NullableInfo info;
2775 public InternalWrap (Expression expr, NullableInfo info, Location loc)
2782 eclass = ExprClass.Value;
2785 public override Expression DoResolve (EmitContext ec)
2790 public override void Emit (EmitContext ec)
2793 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2798 public class Wrap : Expression
2803 protected Wrap (Expression expr)
2806 this.loc = expr.Location;
2809 public static Wrap Create (Expression expr, EmitContext ec)
2811 return new Wrap (expr).Resolve (ec) as Wrap;
2814 public override Expression DoResolve (EmitContext ec)
2816 expr = expr.Resolve (ec);
2820 TypeExpr target_type = new NullableType (expr.Type, loc);
2821 target_type = target_type.ResolveAsTypeTerminal (ec, false);
2822 if (target_type == null)
2825 type = target_type.Type;
2826 info = new NullableInfo (type);
2827 eclass = ExprClass.Value;
2831 public override void Emit (EmitContext ec)
2834 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2838 public class NullableLiteral : NullLiteral, IMemoryLocation {
2839 public NullableLiteral (Type target_type, Location loc)
2842 this.type = target_type;
2844 eclass = ExprClass.Value;
2847 public override Expression DoResolve (EmitContext ec)
2852 public override void Emit (EmitContext ec)
2854 LocalTemporary value_target = new LocalTemporary (type);
2856 value_target.AddressOf (ec, AddressOp.Store);
2857 ec.ig.Emit (OpCodes.Initobj, type);
2858 value_target.Emit (ec);
2861 public void AddressOf (EmitContext ec, AddressOp Mode)
2863 LocalTemporary value_target = new LocalTemporary (type);
2865 value_target.AddressOf (ec, AddressOp.Store);
2866 ec.ig.Emit (OpCodes.Initobj, type);
2867 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
2871 public abstract class Lifted : Expression, IMemoryLocation
2873 Expression expr, underlying, wrap, null_value;
2876 protected Lifted (Expression expr, Location loc)
2882 public override Expression DoResolve (EmitContext ec)
2884 expr = expr.Resolve (ec);
2888 unwrap = Unwrap.Create (expr, ec);
2892 underlying = ResolveUnderlying (unwrap, ec);
2893 if (underlying == null)
2896 wrap = Wrap.Create (underlying, ec);
2900 null_value = new NullableLiteral (wrap.Type, loc).Resolve (ec);
2901 if (null_value == null)
2905 eclass = ExprClass.Value;
2909 protected abstract Expression ResolveUnderlying (Expression unwrap, EmitContext ec);
2911 public override void Emit (EmitContext ec)
2913 ILGenerator ig = ec.ig;
2914 Label is_null_label = ig.DefineLabel ();
2915 Label end_label = ig.DefineLabel ();
2917 unwrap.EmitCheck (ec);
2918 ig.Emit (OpCodes.Brfalse, is_null_label);
2921 ig.Emit (OpCodes.Br, end_label);
2923 ig.MarkLabel (is_null_label);
2924 null_value.Emit (ec);
2926 ig.MarkLabel (end_label);
2929 public void AddressOf (EmitContext ec, AddressOp mode)
2931 unwrap.AddressOf (ec, mode);
2935 public class LiftedConversion : Lifted
2937 public readonly bool IsUser;
2938 public readonly bool IsExplicit;
2939 public readonly Type TargetType;
2941 public LiftedConversion (Expression expr, Type target_type, bool is_user,
2942 bool is_explicit, Location loc)
2945 this.IsUser = is_user;
2946 this.IsExplicit = is_explicit;
2947 this.TargetType = target_type;
2950 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2952 Type type = TypeManager.GetTypeArguments (TargetType) [0];
2955 return Convert.UserDefinedConversion (ec, unwrap, type, loc, IsExplicit);
2958 return Convert.ExplicitConversion (ec, unwrap, type, loc);
2960 return Convert.ImplicitConversion (ec, unwrap, type, loc);
2965 public class LiftedUnaryOperator : Lifted
2967 public readonly Unary.Operator Oper;
2969 public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
2975 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2977 return new Unary (Oper, unwrap, loc);
2981 public class LiftedConditional : Lifted
2983 Expression true_expr, false_expr;
2985 public LiftedConditional (Expression expr, Expression true_expr, Expression false_expr,
2989 this.true_expr = true_expr;
2990 this.false_expr = false_expr;
2993 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2995 return new Conditional (unwrap, true_expr, false_expr);
2999 public class LiftedBinaryOperator : Expression
3001 public readonly Binary.Operator Oper;
3003 Expression left, right, original_left, original_right;
3004 Expression underlying, null_value, bool_wrap;
3005 Unwrap left_unwrap, right_unwrap;
3006 bool is_equality, is_comparision, is_boolean;
3008 public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
3012 this.left = original_left = left;
3013 this.right = original_right = right;
3017 public override Expression DoResolve (EmitContext ec)
3019 if (TypeManager.IsNullableType (left.Type)) {
3020 left = left_unwrap = Unwrap.Create (left, ec);
3025 if (TypeManager.IsNullableType (right.Type)) {
3026 right = right_unwrap = Unwrap.Create (right, ec);
3031 if ((Oper == Binary.Operator.LogicalAnd) ||
3032 (Oper == Binary.Operator.LogicalOr)) {
3033 Binary.Error_OperatorCannotBeApplied (
3034 loc, Binary.OperName (Oper),
3035 original_left.GetSignatureForError (),
3036 original_right.GetSignatureForError ());
3040 if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr)) &&
3041 ((left.Type == TypeManager.bool_type) && (right.Type == TypeManager.bool_type))) {
3042 Expression empty = new EmptyExpression (TypeManager.bool_type);
3043 bool_wrap = Wrap.Create (empty, ec);
3044 null_value = new NullableLiteral (bool_wrap.Type, loc).Resolve (ec);
3046 type = bool_wrap.Type;
3048 } else if ((Oper == Binary.Operator.Equality) || (Oper == Binary.Operator.Inequality)) {
3049 if (!(left is NullLiteral) && !(right is NullLiteral)) {
3050 underlying = new Binary (Oper, left, right).Resolve (ec);
3051 if (underlying == null)
3055 type = TypeManager.bool_type;
3057 } else if ((Oper == Binary.Operator.LessThan) ||
3058 (Oper == Binary.Operator.GreaterThan) ||
3059 (Oper == Binary.Operator.LessThanOrEqual) ||
3060 (Oper == Binary.Operator.GreaterThanOrEqual)) {
3061 underlying = new Binary (Oper, left, right).Resolve (ec);
3062 if (underlying == null)
3065 type = TypeManager.bool_type;
3066 is_comparision = true;
3068 underlying = new Binary (Oper, left, right).Resolve (ec);
3069 if (underlying == null)
3072 underlying = Wrap.Create (underlying, ec);
3073 if (underlying == null)
3076 type = underlying.Type;
3077 null_value = new NullableLiteral (type, loc).Resolve (ec);
3080 eclass = ExprClass.Value;
3084 void EmitBoolean (EmitContext ec)
3086 ILGenerator ig = ec.ig;
3088 Label left_is_null_label = ig.DefineLabel ();
3089 Label right_is_null_label = ig.DefineLabel ();
3090 Label is_null_label = ig.DefineLabel ();
3091 Label wrap_label = ig.DefineLabel ();
3092 Label end_label = ig.DefineLabel ();
3094 if (left_unwrap != null) {
3095 left_unwrap.EmitCheck (ec);
3096 ig.Emit (OpCodes.Brfalse, left_is_null_label);
3100 ig.Emit (OpCodes.Dup);
3101 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3102 ig.Emit (OpCodes.Brtrue, wrap_label);
3104 ig.Emit (OpCodes.Brfalse, wrap_label);
3106 if (right_unwrap != null) {
3107 right_unwrap.EmitCheck (ec);
3108 ig.Emit (OpCodes.Brfalse, right_is_null_label);
3111 if ((Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr))
3112 ig.Emit (OpCodes.Pop);
3115 if (Oper == Binary.Operator.BitwiseOr)
3116 ig.Emit (OpCodes.Or);
3117 else if (Oper == Binary.Operator.BitwiseAnd)
3118 ig.Emit (OpCodes.And);
3119 ig.Emit (OpCodes.Br, wrap_label);
3121 ig.MarkLabel (left_is_null_label);
3122 if (right_unwrap != null) {
3123 right_unwrap.EmitCheck (ec);
3124 ig.Emit (OpCodes.Brfalse, is_null_label);
3128 ig.Emit (OpCodes.Dup);
3129 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3130 ig.Emit (OpCodes.Brtrue, wrap_label);
3132 ig.Emit (OpCodes.Brfalse, wrap_label);
3134 ig.MarkLabel (right_is_null_label);
3135 ig.Emit (OpCodes.Pop);
3136 ig.MarkLabel (is_null_label);
3137 null_value.Emit (ec);
3138 ig.Emit (OpCodes.Br, end_label);
3140 ig.MarkLabel (wrap_label);
3141 ig.Emit (OpCodes.Nop);
3142 bool_wrap.Emit (ec);
3143 ig.Emit (OpCodes.Nop);
3145 ig.MarkLabel (end_label);
3148 void EmitEquality (EmitContext ec)
3150 ILGenerator ig = ec.ig;
3152 // Given 'X? x;' for any value type X: 'x != null' is the same as 'x.HasValue'
3153 if (left is NullLiteral) {
3154 if (right_unwrap == null)
3155 throw new InternalErrorException ();
3156 right_unwrap.EmitCheck (ec);
3157 if (Oper == Binary.Operator.Equality) {
3158 ig.Emit (OpCodes.Ldc_I4_0);
3159 ig.Emit (OpCodes.Ceq);
3164 if (right is NullLiteral) {
3165 if (left_unwrap == null)
3166 throw new InternalErrorException ();
3167 left_unwrap.EmitCheck (ec);
3168 if (Oper == Binary.Operator.Equality) {
3169 ig.Emit (OpCodes.Ldc_I4_0);
3170 ig.Emit (OpCodes.Ceq);
3175 Label both_have_value_label = ig.DefineLabel ();
3176 Label end_label = ig.DefineLabel ();
3178 if (left_unwrap != null && right_unwrap != null) {
3179 Label dissimilar_label = ig.DefineLabel ();
3181 left_unwrap.EmitCheck (ec);
3182 ig.Emit (OpCodes.Dup);
3183 right_unwrap.EmitCheck (ec);
3184 ig.Emit (OpCodes.Bne_Un, dissimilar_label);
3186 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3189 if (Oper == Binary.Operator.Equality)
3190 ig.Emit (OpCodes.Ldc_I4_1);
3192 ig.Emit (OpCodes.Ldc_I4_0);
3193 ig.Emit (OpCodes.Br, end_label);
3195 ig.MarkLabel (dissimilar_label);
3196 ig.Emit (OpCodes.Pop);
3197 } else if (left_unwrap != null) {
3198 left_unwrap.EmitCheck (ec);
3199 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3200 } else if (right_unwrap != null) {
3201 right_unwrap.EmitCheck (ec);
3202 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3204 throw new InternalErrorException ("shouldn't get here");
3207 // one is null while the other isn't
3208 if (Oper == Binary.Operator.Equality)
3209 ig.Emit (OpCodes.Ldc_I4_0);
3211 ig.Emit (OpCodes.Ldc_I4_1);
3212 ig.Emit (OpCodes.Br, end_label);
3214 ig.MarkLabel (both_have_value_label);
3215 underlying.Emit (ec);
3217 ig.MarkLabel (end_label);
3220 void EmitComparision (EmitContext ec)
3222 ILGenerator ig = ec.ig;
3224 Label is_null_label = ig.DefineLabel ();
3225 Label end_label = ig.DefineLabel ();
3227 if (left_unwrap != null) {
3228 left_unwrap.EmitCheck (ec);
3229 ig.Emit (OpCodes.Brfalse, is_null_label);
3232 if (right_unwrap != null) {
3233 right_unwrap.EmitCheck (ec);
3234 ig.Emit (OpCodes.Brfalse, is_null_label);
3237 underlying.Emit (ec);
3238 ig.Emit (OpCodes.Br, end_label);
3240 ig.MarkLabel (is_null_label);
3241 ig.Emit (OpCodes.Ldc_I4_0);
3243 ig.MarkLabel (end_label);
3246 public override void Emit (EmitContext ec)
3248 if (left_unwrap != null)
3249 left_unwrap.Store (ec);
3250 if (right_unwrap != null)
3251 right_unwrap.Store (ec);
3256 } else if (is_equality) {
3259 } else if (is_comparision) {
3260 EmitComparision (ec);
3264 ILGenerator ig = ec.ig;
3266 Label is_null_label = ig.DefineLabel ();
3267 Label end_label = ig.DefineLabel ();
3269 if (left_unwrap != null) {
3270 left_unwrap.EmitCheck (ec);
3271 ig.Emit (OpCodes.Brfalse, is_null_label);
3274 if (right_unwrap != null) {
3275 right_unwrap.EmitCheck (ec);
3276 ig.Emit (OpCodes.Brfalse, is_null_label);
3279 underlying.Emit (ec);
3280 ig.Emit (OpCodes.Br, end_label);
3282 ig.MarkLabel (is_null_label);
3283 null_value.Emit (ec);
3285 ig.MarkLabel (end_label);
3289 public class OperatorTrueOrFalse : Expression
3291 public readonly bool IsTrue;
3296 public OperatorTrueOrFalse (Expression expr, bool is_true, Location loc)
3298 this.IsTrue = is_true;
3303 public override Expression DoResolve (EmitContext ec)
3305 unwrap = Unwrap.Create (expr, ec);
3309 if (unwrap.Type != TypeManager.bool_type)
3312 type = TypeManager.bool_type;
3313 eclass = ExprClass.Value;
3317 public override void Emit (EmitContext ec)
3319 ILGenerator ig = ec.ig;
3321 Label is_null_label = ig.DefineLabel ();
3322 Label end_label = ig.DefineLabel ();
3324 unwrap.EmitCheck (ec);
3325 ig.Emit (OpCodes.Brfalse, is_null_label);
3329 ig.Emit (OpCodes.Ldc_I4_0);
3330 ig.Emit (OpCodes.Ceq);
3332 ig.Emit (OpCodes.Br, end_label);
3334 ig.MarkLabel (is_null_label);
3335 ig.Emit (OpCodes.Ldc_I4_0);
3337 ig.MarkLabel (end_label);
3341 public class NullCoalescingOperator : Expression
3343 Expression left, right;
3347 public NullCoalescingOperator (Expression left, Expression right, Location loc)
3353 eclass = ExprClass.Value;
3356 public override Expression DoResolve (EmitContext ec)
3361 left = left.Resolve (ec);
3365 right = right.Resolve (ec);
3369 Type ltype = left.Type, rtype = right.Type;
3371 if (!TypeManager.IsNullableType (ltype) && ltype.IsValueType) {
3372 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3376 if (TypeManager.IsNullableType (ltype)) {
3377 NullableInfo info = new NullableInfo (ltype);
3379 unwrap = Unwrap.Create (left, ec);
3383 expr = Convert.ImplicitConversion (ec, right, info.UnderlyingType, loc);
3391 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
3397 if (unwrap != null) {
3398 expr = Convert.ImplicitConversion (ec, unwrap, rtype, loc);
3407 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3411 public override void Emit (EmitContext ec)
3413 ILGenerator ig = ec.ig;
3415 Label is_null_label = ig.DefineLabel ();
3416 Label end_label = ig.DefineLabel ();
3418 if (unwrap != null) {
3419 unwrap.EmitCheck (ec);
3420 ig.Emit (OpCodes.Brfalse, is_null_label);
3423 ig.Emit (OpCodes.Br, end_label);
3425 ig.MarkLabel (is_null_label);
3428 ig.MarkLabel (end_label);
3431 ig.Emit (OpCodes.Dup);
3432 ig.Emit (OpCodes.Brtrue, end_label);
3434 ig.MarkLabel (is_null_label);
3436 ig.Emit (OpCodes.Pop);
3439 ig.MarkLabel (end_label);
3444 public class LiftedUnaryMutator : ExpressionStatement
3446 public readonly UnaryMutator.Mode Mode;
3447 Expression expr, null_value;
3448 UnaryMutator underlying;
3451 public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
3457 eclass = ExprClass.Value;
3460 public override Expression DoResolve (EmitContext ec)
3462 expr = expr.Resolve (ec);
3466 unwrap = Unwrap.Create (expr, ec);
3470 underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
3471 if (underlying == null)
3474 null_value = new NullableLiteral (expr.Type, loc).Resolve (ec);
3475 if (null_value == null)
3482 void DoEmit (EmitContext ec, bool is_expr)
3484 ILGenerator ig = ec.ig;
3485 Label is_null_label = ig.DefineLabel ();
3486 Label end_label = ig.DefineLabel ();
3488 unwrap.EmitCheck (ec);
3489 ig.Emit (OpCodes.Brfalse, is_null_label);
3492 underlying.Emit (ec);
3494 underlying.EmitStatement (ec);
3495 ig.Emit (OpCodes.Br, end_label);
3497 ig.MarkLabel (is_null_label);
3499 null_value.Emit (ec);
3501 ig.MarkLabel (end_label);
3504 public override void Emit (EmitContext ec)
3509 public override void EmitStatement (EmitContext ec)