2 // generic.cs: Generics support
4 // Authors: Martin Baulig (martin@ximian.com)
5 // Miguel de Icaza (miguel@ximian.com)
7 // Licensed under the terms of the GNU GPL
9 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
10 // (C) 2004 Novell, Inc
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.Globalization;
16 using System.Collections;
18 using System.Text.RegularExpressions;
20 namespace Mono.CSharp {
23 /// Abstract base class for type parameter constraints.
24 /// The type parameter can come from a generic type definition or from reflection.
26 public abstract class GenericConstraints {
27 public abstract string TypeParameter {
31 public abstract GenericParameterAttributes Attributes {
35 public bool HasConstructorConstraint {
36 get { return (Attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0; }
39 public bool HasReferenceTypeConstraint {
40 get { return (Attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0; }
43 public bool HasValueTypeConstraint {
44 get { return (Attributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0; }
47 public virtual bool HasClassConstraint {
48 get { return ClassConstraint != null; }
51 public abstract Type ClassConstraint {
55 public abstract Type[] InterfaceConstraints {
59 public abstract Type EffectiveBaseClass {
64 // Returns whether the type parameter is "known to be a reference type".
66 public virtual bool IsReferenceType {
68 if (HasReferenceTypeConstraint)
70 if (HasValueTypeConstraint)
73 if (ClassConstraint != null) {
74 if (ClassConstraint.IsValueType)
77 if (ClassConstraint != TypeManager.object_type)
81 foreach (Type t in InterfaceConstraints) {
82 if (!t.IsGenericParameter)
85 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
86 if ((gc != null) && gc.IsReferenceType)
95 // Returns whether the type parameter is "known to be a value type".
97 public virtual bool IsValueType {
99 if (HasValueTypeConstraint)
101 if (HasReferenceTypeConstraint)
104 if (ClassConstraint != null) {
105 if (!ClassConstraint.IsValueType)
108 if (ClassConstraint != TypeManager.value_type)
112 foreach (Type t in InterfaceConstraints) {
113 if (!t.IsGenericParameter)
116 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
117 if ((gc != null) && gc.IsValueType)
126 public enum SpecialConstraint
134 /// Tracks the constraints for a type parameter from a generic type definition.
136 public class Constraints : GenericConstraints {
138 ArrayList constraints;
142 // name is the identifier, constraints is an arraylist of
143 // Expressions (with types) or `true' for the constructor constraint.
145 public Constraints (string name, ArrayList constraints,
149 this.constraints = constraints;
153 public override string TypeParameter {
159 GenericParameterAttributes attrs;
160 TypeExpr class_constraint;
161 ArrayList iface_constraints;
162 ArrayList type_param_constraints;
164 Type class_constraint_type;
165 Type[] iface_constraint_types;
166 Type effective_base_type;
171 /// Resolve the constraints - but only resolve things into Expression's, not
172 /// into actual types.
174 public bool Resolve (IResolveContext ec)
179 iface_constraints = new ArrayList ();
180 type_param_constraints = new ArrayList ();
182 foreach (object obj in constraints) {
183 if (HasConstructorConstraint) {
184 Report.Error (401, loc,
185 "The new() constraint must be last.");
189 if (obj is SpecialConstraint) {
190 SpecialConstraint sc = (SpecialConstraint) obj;
192 if (sc == SpecialConstraint.Constructor) {
193 if (!HasValueTypeConstraint) {
194 attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
199 451, loc, "The new () constraint " +
200 "cannot be used with the `struct' " +
205 if ((num_constraints > 0) || HasReferenceTypeConstraint || HasValueTypeConstraint) {
206 Report.Error (449, loc,
207 "The `class' or `struct' " +
208 "constraint must be first");
212 if (sc == SpecialConstraint.ReferenceType)
213 attrs |= GenericParameterAttributes.ReferenceTypeConstraint;
215 attrs |= GenericParameterAttributes.NotNullableValueTypeConstraint;
219 int errors = Report.Errors;
220 FullNamedExpression fn = ((Expression) obj).ResolveAsTypeStep (ec, false);
223 if (errors != Report.Errors)
226 Report.Error (246, loc, "Cannot find type '{0}'", ((Expression) obj).GetSignatureForError ());
231 ConstructedType cexpr = fn as ConstructedType;
233 if (!cexpr.ResolveConstructedType (ec))
238 expr = fn.ResolveAsTypeTerminal (ec, false);
240 if ((expr == null) || (expr.Type == null))
243 TypeParameterExpr texpr = expr as TypeParameterExpr;
245 type_param_constraints.Add (expr);
246 else if (expr.IsInterface)
247 iface_constraints.Add (expr);
248 else if (class_constraint != null) {
249 Report.Error (406, loc,
250 "`{0}': the class constraint for `{1}' " +
251 "must come before any other constraints.",
254 } else if (HasReferenceTypeConstraint || HasValueTypeConstraint) {
255 Report.Error (450, loc, "`{0}': cannot specify both " +
256 "a constraint class and the `class' " +
257 "or `struct' constraint.", expr.Name);
260 class_constraint = expr;
265 ArrayList list = new ArrayList ();
266 foreach (TypeExpr iface_constraint in iface_constraints) {
267 foreach (Type type in list) {
268 if (!type.Equals (iface_constraint.Type))
271 Report.Error (405, loc,
272 "Duplicate constraint `{0}' for type " +
273 "parameter `{1}'.", iface_constraint.GetSignatureForError (),
278 list.Add (iface_constraint.Type);
281 foreach (TypeParameterExpr expr in type_param_constraints) {
282 foreach (Type type in list) {
283 if (!type.Equals (expr.Type))
286 Report.Error (405, loc,
287 "Duplicate constraint `{0}' for type " +
288 "parameter `{1}'.", expr.GetSignatureForError (), name);
292 list.Add (expr.Type);
295 iface_constraint_types = new Type [list.Count];
296 list.CopyTo (iface_constraint_types, 0);
298 if (class_constraint != null) {
299 class_constraint_type = class_constraint.Type;
300 if (class_constraint_type == null)
303 if (class_constraint_type.IsSealed) {
304 Report.Error (701, loc,
305 "`{0}' is not a valid bound. Bounds " +
306 "must be interfaces or non sealed " +
307 "classes", TypeManager.CSharpName (class_constraint_type));
311 if ((class_constraint_type == TypeManager.array_type) ||
312 (class_constraint_type == TypeManager.delegate_type) ||
313 (class_constraint_type == TypeManager.enum_type) ||
314 (class_constraint_type == TypeManager.value_type) ||
315 (class_constraint_type == TypeManager.object_type)) {
316 Report.Error (702, loc,
317 "Bound cannot be special class `{0}'",
318 TypeManager.CSharpName (class_constraint_type));
323 if (class_constraint_type != null)
324 effective_base_type = class_constraint_type;
325 else if (HasValueTypeConstraint)
326 effective_base_type = TypeManager.value_type;
328 effective_base_type = TypeManager.object_type;
334 bool CheckTypeParameterConstraints (TypeParameter tparam, Hashtable seen)
336 seen.Add (tparam, true);
338 Constraints constraints = tparam.Constraints;
339 if (constraints == null)
342 if (constraints.HasValueTypeConstraint) {
343 Report.Error (456, loc, "Type parameter `{0}' has " +
344 "the `struct' constraint, so it cannot " +
345 "be used as a constraint for `{1}'",
350 if (constraints.type_param_constraints == null)
353 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
354 if (seen.Contains (expr.TypeParameter)) {
355 Report.Error (454, loc, "Circular constraint " +
356 "dependency involving `{0}' and `{1}'",
357 tparam.Name, expr.Name);
361 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
369 /// Resolve the constraints into actual types.
371 public bool ResolveTypes (IResolveContext 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 for (int i = 0; i < iface_constraints.Count; ++i) {
394 TypeExpr iface_constraint = (TypeExpr) iface_constraints [i];
395 iface_constraint = iface_constraint.ResolveAsTypeTerminal (ec, false);
396 if (iface_constraint == null)
398 iface_constraints [i] = iface_constraint;
401 if (class_constraint != null) {
402 class_constraint = class_constraint.ResolveAsTypeTerminal (ec, false);
403 if (class_constraint == null)
411 /// Check whether there are no conflicts in our type parameter constraints.
413 /// This is an example:
417 /// where U : T, struct
419 public bool CheckDependencies ()
421 foreach (TypeParameterExpr expr in type_param_constraints) {
422 if (!CheckDependencies (expr.TypeParameter))
429 bool CheckDependencies (TypeParameter tparam)
431 Constraints constraints = tparam.Constraints;
432 if (constraints == null)
435 if (HasValueTypeConstraint && constraints.HasClassConstraint) {
436 Report.Error (455, loc, "Type parameter `{0}' inherits " +
437 "conflicting constraints `{1}' and `{2}'",
438 name, TypeManager.CSharpName (constraints.ClassConstraint),
443 if (HasClassConstraint && constraints.HasClassConstraint) {
444 Type t1 = ClassConstraint;
445 TypeExpr e1 = class_constraint;
446 Type t2 = constraints.ClassConstraint;
447 TypeExpr e2 = constraints.class_constraint;
449 if (!Convert.ImplicitReferenceConversionExists (e1, t2) &&
450 !Convert.ImplicitReferenceConversionExists (e2, t1)) {
451 Report.Error (455, loc,
452 "Type parameter `{0}' inherits " +
453 "conflicting constraints `{1}' and `{2}'",
454 name, TypeManager.CSharpName (t1), TypeManager.CSharpName (t2));
459 if (constraints.type_param_constraints == null)
462 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
463 if (!CheckDependencies (expr.TypeParameter))
470 public override GenericParameterAttributes Attributes {
471 get { return attrs; }
474 public override bool HasClassConstraint {
475 get { return class_constraint != null; }
478 public override Type ClassConstraint {
479 get { return class_constraint_type; }
482 public override Type[] InterfaceConstraints {
483 get { return iface_constraint_types; }
486 public override Type EffectiveBaseClass {
487 get { return effective_base_type; }
490 public bool IsSubclassOf (Type t)
492 if ((class_constraint_type != null) &&
493 class_constraint_type.IsSubclassOf (t))
496 if (iface_constraint_types == null)
499 foreach (Type iface in iface_constraint_types) {
500 if (TypeManager.IsSubclassOf (iface, t))
507 public Location Location {
514 /// This is used when we're implementing a generic interface method.
515 /// Each method type parameter in implementing method must have the same
516 /// constraints than the corresponding type parameter in the interface
517 /// method. To do that, we're called on each of the implementing method's
520 public bool CheckInterfaceMethod (GenericConstraints gc)
522 if (gc.Attributes != attrs)
525 if (HasClassConstraint != gc.HasClassConstraint)
527 if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
530 int gc_icount = gc.InterfaceConstraints != null ?
531 gc.InterfaceConstraints.Length : 0;
532 int icount = InterfaceConstraints != null ?
533 InterfaceConstraints.Length : 0;
535 if (gc_icount != icount)
538 foreach (Type iface in gc.InterfaceConstraints) {
540 foreach (Type check in InterfaceConstraints) {
541 if (TypeManager.IsEqual (iface, check)) {
556 /// A type parameter from a generic type definition.
558 public class TypeParameter : MemberCore, IMemberContainer {
561 GenericConstraints gc;
562 Constraints constraints;
564 GenericTypeParameterBuilder type;
566 public TypeParameter (DeclSpace parent, DeclSpace decl, string name,
567 Constraints constraints, Attributes attrs, Location loc)
568 : base (parent, new MemberName (name, loc), attrs)
572 this.constraints = constraints;
576 public GenericConstraints GenericConstraints {
577 get { return gc != null ? gc : constraints; }
580 public Constraints Constraints {
581 get { return constraints; }
584 public bool HasConstructorConstraint {
585 get { return constraints != null && constraints.HasConstructorConstraint; }
588 public DeclSpace DeclSpace {
597 /// This is the first method which is called during the resolving
598 /// process; we're called immediately after creating the type parameters
599 /// with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
602 /// We're either called from TypeContainer.DefineType() or from
603 /// GenericMethod.Define() (called from Method.Define()).
605 public void Define (GenericTypeParameterBuilder type)
607 if (this.type != null)
608 throw new InvalidOperationException ();
611 TypeManager.AddTypeParameter (type, this);
615 /// This is the second method which is called during the resolving
616 /// process - in case of class type parameters, we're called from
617 /// TypeContainer.ResolveType() - after it resolved the class'es
618 /// base class and interfaces. For method type parameters, we're
619 /// called immediately after Define().
621 /// We're just resolving the constraints into expressions here, we
622 /// don't resolve them into actual types.
624 /// Note that in the special case of partial generic classes, we may be
625 /// called _before_ Define() and we may also be called multiple types.
627 public bool Resolve (DeclSpace ds)
629 if (constraints != null) {
630 if (!constraints.Resolve (ds)) {
640 /// This is the third method which is called during the resolving
641 /// process. We're called immediately after calling DefineConstraints()
642 /// on all of the current class'es type parameters.
644 /// Our job is to resolve the constraints to actual types.
646 /// Note that we may have circular dependencies on type parameters - this
647 /// is why Resolve() and ResolveType() are separate.
649 public bool ResolveType (IResolveContext ec)
651 if (constraints != null) {
652 if (!constraints.ResolveTypes (ec)) {
662 /// This is the fourth and last method which is called during the resolving
663 /// process. We're called after everything is fully resolved and actually
664 /// register the constraints with SRE and the TypeManager.
666 public bool DefineType (IResolveContext ec)
668 return DefineType (ec, null, null, false);
672 /// This is the fith and last method which is called during the resolving
673 /// process. We're called after everything is fully resolved and actually
674 /// register the constraints with SRE and the TypeManager.
676 /// The `builder', `implementing' and `is_override' arguments are only
677 /// applicable to method type parameters.
679 public bool DefineType (IResolveContext ec, MethodBuilder builder,
680 MethodInfo implementing, bool is_override)
682 if (!ResolveType (ec))
685 if (implementing != null) {
686 if (is_override && (constraints != null)) {
688 460, loc, "Constraints for override and " +
689 "explicit interface implementation methods " +
690 "are inherited from the base method so they " +
691 "cannot be specified directly");
695 MethodBase mb = TypeManager.DropGenericMethodArguments (implementing);
697 int pos = type.GenericParameterPosition;
698 Type mparam = mb.GetGenericArguments () [pos];
699 GenericConstraints temp_gc = ReflectionConstraints.GetConstraints (mparam);
702 gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
703 else if (constraints != null)
704 gc = new InflatedConstraints (constraints, implementing.DeclaringType);
707 if (constraints != null) {
710 else if (!constraints.CheckInterfaceMethod (gc))
713 if (!is_override && (temp_gc != null))
718 Report.SymbolRelatedToPreviousError (implementing);
721 425, loc, "The constraints for type " +
722 "parameter `{0}' of method `{1}' must match " +
723 "the constraints for type parameter `{2}' " +
724 "of interface method `{3}'. Consider using " +
725 "an explicit interface implementation instead",
726 Name, TypeManager.CSharpSignature (builder),
727 TypeManager.CSharpName (mparam), TypeManager.CSharpSignature (mb));
730 } else if (DeclSpace is Iterator) {
731 TypeParameter[] tparams = DeclSpace.TypeParameters;
732 Type[] types = new Type [tparams.Length];
733 for (int i = 0; i < tparams.Length; i++)
734 types [i] = tparams [i].Type;
736 if (constraints != null)
737 gc = new InflatedConstraints (constraints, types);
739 gc = (GenericConstraints) constraints;
745 if (gc.HasClassConstraint)
746 type.SetBaseTypeConstraint (gc.ClassConstraint);
748 type.SetInterfaceConstraints (gc.InterfaceConstraints);
749 type.SetGenericParameterAttributes (gc.Attributes);
750 TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
756 /// Check whether there are no conflicts in our type parameter constraints.
758 /// This is an example:
762 /// where U : T, struct
764 public bool CheckDependencies ()
766 if (constraints != null)
767 return constraints.CheckDependencies ();
773 /// This is called for each part of a partial generic type definition.
775 /// If `new_constraints' is not null and we don't already have constraints,
776 /// they become our constraints. If we already have constraints, we must
777 /// check that they're the same.
780 public bool UpdateConstraints (IResolveContext ec, Constraints new_constraints)
783 throw new InvalidOperationException ();
785 if (new_constraints == null)
788 if (!new_constraints.Resolve (ec))
790 if (!new_constraints.ResolveTypes (ec))
793 if (constraints != null)
794 return constraints.CheckInterfaceMethod (new_constraints);
796 constraints = new_constraints;
800 public void EmitAttributes ()
802 if (OptAttributes != null)
803 OptAttributes.Emit ();
806 public override string DocCommentHeader {
808 throw new InvalidOperationException (
809 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
817 public override bool Define ()
822 public override void ApplyAttributeBuilder (Attribute a,
823 CustomAttributeBuilder cb)
825 type.SetCustomAttribute (cb);
828 public override AttributeTargets AttributeTargets {
830 return (AttributeTargets) AttributeTargets.GenericParameter;
834 public override string[] ValidAttributeTargets {
836 return new string [] { "type parameter" };
844 string IMemberContainer.Name {
848 MemberCache IMemberContainer.BaseCache {
852 bool IMemberContainer.IsInterface {
856 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
858 return FindMembers (mt, bf, null, null);
861 MemberCache IMemberContainer.MemberCache {
865 public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
866 MemberFilter filter, object criteria)
868 if (constraints == null)
869 return MemberList.Empty;
871 ArrayList members = new ArrayList ();
873 if (gc.HasClassConstraint) {
874 MemberList list = TypeManager.FindMembers (
875 gc.ClassConstraint, mt, bf, filter, criteria);
877 members.AddRange (list);
880 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
881 foreach (Type t in ifaces) {
882 MemberList list = TypeManager.FindMembers (
883 t, mt, bf, filter, criteria);
885 members.AddRange (list);
888 return new MemberList (members);
891 public bool IsSubclassOf (Type t)
896 if (constraints != null)
897 return constraints.IsSubclassOf (t);
902 public override string ToString ()
904 return "TypeParameter[" + name + "]";
907 public static string GetSignatureForError (TypeParameter[] tp)
909 if (tp == null || tp.Length == 0)
912 StringBuilder sb = new StringBuilder ("<");
913 for (int i = 0; i < tp.Length; ++i) {
916 sb.Append (tp[i].GetSignatureForError ());
919 return sb.ToString ();
922 public void InflateConstraints (Type declaring)
924 if (constraints != null)
925 gc = new InflatedConstraints (constraints, declaring);
928 protected class InflatedConstraints : GenericConstraints
930 GenericConstraints gc;
932 Type class_constraint;
933 Type[] iface_constraints;
936 public InflatedConstraints (GenericConstraints gc, Type declaring)
937 : this (gc, TypeManager.GetTypeArguments (declaring))
940 public InflatedConstraints (GenericConstraints gc, Type[] dargs)
945 ArrayList list = new ArrayList ();
946 if (gc.HasClassConstraint)
947 list.Add (inflate (gc.ClassConstraint));
948 foreach (Type iface in gc.InterfaceConstraints)
949 list.Add (inflate (iface));
951 bool has_class_constr = false;
952 if (list.Count > 0) {
953 Type first = (Type) list [0];
954 has_class_constr = !first.IsInterface && !first.IsGenericParameter;
957 if ((list.Count > 0) && has_class_constr) {
958 class_constraint = (Type) list [0];
959 iface_constraints = new Type [list.Count - 1];
960 list.CopyTo (1, iface_constraints, 0, list.Count - 1);
962 iface_constraints = new Type [list.Count];
963 list.CopyTo (iface_constraints, 0);
966 if (HasValueTypeConstraint)
967 base_type = TypeManager.value_type;
968 else if (class_constraint != null)
969 base_type = class_constraint;
971 base_type = TypeManager.object_type;
974 Type inflate (Type t)
978 if (t.IsGenericParameter)
979 return dargs [t.GenericParameterPosition];
980 if (t.IsGenericType) {
981 Type[] args = t.GetGenericArguments ();
982 Type[] inflated = new Type [args.Length];
984 for (int i = 0; i < args.Length; i++)
985 inflated [i] = inflate (args [i]);
987 t = t.GetGenericTypeDefinition ();
988 t = t.MakeGenericType (inflated);
994 public override string TypeParameter {
995 get { return gc.TypeParameter; }
998 public override GenericParameterAttributes Attributes {
999 get { return gc.Attributes; }
1002 public override Type ClassConstraint {
1003 get { return class_constraint; }
1006 public override Type EffectiveBaseClass {
1007 get { return base_type; }
1010 public override Type[] InterfaceConstraints {
1011 get { return iface_constraints; }
1017 /// A TypeExpr which already resolved to a type parameter.
1019 public class TypeParameterExpr : TypeExpr {
1020 TypeParameter type_parameter;
1022 public override string Name {
1024 return type_parameter.Name;
1028 public override string FullName {
1030 return type_parameter.Name;
1034 public TypeParameter TypeParameter {
1036 return type_parameter;
1040 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1042 this.type_parameter = type_parameter;
1046 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1048 type = type_parameter.Type;
1053 public override bool IsInterface {
1054 get { return false; }
1057 public override bool CheckAccessLevel (DeclSpace ds)
1062 public void Error_CannotUseAsUnmanagedType (Location loc)
1064 Report.Error (-203, loc, "Can not use type parameter as unmanaged type");
1069 /// Tracks the type arguments when instantiating a generic type. We're used in
1070 /// ConstructedType.
1072 public class TypeArguments {
1073 public readonly Location Location;
1080 public TypeArguments (Location loc)
1082 args = new ArrayList ();
1083 this.Location = loc;
1086 public TypeArguments (int dimension, Location loc)
1088 this.dimension = dimension;
1089 this.Location = loc;
1092 public void Add (Expression type)
1095 throw new InvalidOperationException ();
1100 public void Add (TypeArguments new_args)
1103 throw new InvalidOperationException ();
1105 args.AddRange (new_args.args);
1109 /// We're used during the parsing process: the parser can't distinguish
1110 /// between type parameters and type arguments. Because of that, the
1111 /// parser creates a `MemberName' with `TypeArguments' for both cases and
1112 /// in case of a generic type definition, we call GetDeclarations().
1114 public TypeParameterName[] GetDeclarations ()
1116 TypeParameterName[] ret = new TypeParameterName [args.Count];
1117 for (int i = 0; i < args.Count; i++) {
1118 TypeParameterName name = args [i] as TypeParameterName;
1123 SimpleName sn = args [i] as SimpleName;
1125 ret [i] = new TypeParameterName (sn.Name, null, sn.Location);
1129 Report.Error (81, Location, "Type parameter declaration " +
1130 "must be an identifier not a type");
1137 /// We may only be used after Resolve() is called and return the fully
1140 public Type[] Arguments {
1146 public bool HasTypeArguments {
1148 return has_type_args;
1161 public bool IsUnbound {
1163 return dimension > 0;
1167 public override string ToString ()
1169 StringBuilder s = new StringBuilder ();
1172 for (int i = 0; i < count; i++){
1174 // FIXME: Use TypeManager.CSharpname once we have the type
1177 s.Append (args [i].ToString ());
1181 return s.ToString ();
1185 /// Resolve the type arguments.
1187 public bool Resolve (IResolveContext ec)
1189 int count = args.Count;
1192 atypes = new Type [count];
1194 for (int i = 0; i < count; i++){
1195 TypeExpr te = ((Expression) args [i]).ResolveAsTypeTerminal (ec, false);
1200 if (te is TypeParameterExpr)
1201 has_type_args = true;
1203 if (te.Type.IsPointer) {
1204 Report.Error (306, Location, "The type `{0}' may not be used " +
1205 "as a type argument", TypeManager.CSharpName (te.Type));
1207 } else if (te.Type == TypeManager.void_type) {
1208 Report.Error (1547, Location,
1209 "Keyword `void' cannot be used in this context");
1213 atypes [i] = te.Type;
1219 public class TypeParameterName : SimpleName
1221 Attributes attributes;
1223 public TypeParameterName (string name, Attributes attrs, Location loc)
1229 public Attributes OptAttributes {
1237 /// An instantiation of a generic type.
1239 public class ConstructedType : TypeExpr {
1241 FullNamedExpression name;
1243 Type[] gen_params, atypes;
1247 /// Instantiate the generic type `fname' with the type arguments `args'.
1249 public ConstructedType (FullNamedExpression fname, TypeArguments args, Location l)
1255 eclass = ExprClass.Type;
1256 full_name = name + "<" + args.ToString () + ">";
1259 protected ConstructedType (TypeArguments args, Location l)
1264 eclass = ExprClass.Type;
1267 protected ConstructedType (TypeParameter[] type_params, Location l)
1271 args = new TypeArguments (l);
1272 foreach (TypeParameter type_param in type_params)
1273 args.Add (new TypeParameterExpr (type_param, l));
1275 eclass = ExprClass.Type;
1279 /// This is used to construct the `this' type inside a generic type definition.
1281 public ConstructedType (Type t, TypeParameter[] type_params, Location l)
1282 : this (type_params, l)
1284 gt = t.GetGenericTypeDefinition ();
1286 this.name = new TypeExpression (gt, l);
1287 full_name = gt.FullName + "<" + args.ToString () + ">";
1291 /// Instantiate the generic type `t' with the type arguments `args'.
1292 /// Use this constructor if you already know the fully resolved
1295 public ConstructedType (Type t, TypeArguments args, Location l)
1298 gt = t.GetGenericTypeDefinition ();
1300 this.name = new TypeExpression (gt, l);
1301 full_name = gt.FullName + "<" + args.ToString () + ">";
1304 public TypeArguments TypeArguments {
1305 get { return args; }
1308 public override string GetSignatureForError ()
1310 return TypeManager.CSharpName (gt);
1313 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1315 if (!ResolveConstructedType (ec))
1322 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1323 /// after fully resolving the constructed type.
1325 public bool CheckConstraints (IResolveContext ec)
1327 return ConstraintChecker.CheckConstraints (ec, gt, gen_params, atypes, loc);
1331 /// Resolve the constructed type, but don't check the constraints.
1333 public bool ResolveConstructedType (IResolveContext ec)
1337 // If we already know the fully resolved generic type.
1339 return DoResolveType (ec);
1345 Report.Error (246, loc, "Cannot find type `{0}'<...>", Name);
1349 num_args = TypeManager.GetNumberOfTypeArguments (t);
1350 if (num_args == 0) {
1351 Report.Error (308, loc,
1352 "The non-generic type `{0}' cannot " +
1353 "be used with type arguments.",
1354 TypeManager.CSharpName (t));
1358 gt = t.GetGenericTypeDefinition ();
1359 return DoResolveType (ec);
1362 bool DoResolveType (IResolveContext ec)
1365 // Resolve the arguments.
1367 if (args.Resolve (ec) == false)
1370 gen_params = gt.GetGenericArguments ();
1371 atypes = args.Arguments;
1373 if (atypes.Length != gen_params.Length) {
1374 Report.Error (305, loc,
1375 "Using the generic type `{0}' " +
1376 "requires {1} type arguments",
1377 TypeManager.CSharpName (gt),
1378 gen_params.Length.ToString ());
1383 // Now bind the parameters.
1385 type = gt.MakeGenericType (atypes);
1389 public Expression GetSimpleName (EmitContext ec)
1394 public override bool CheckAccessLevel (DeclSpace ds)
1396 return ds.CheckAccessLevel (gt);
1399 public override bool AsAccessible (DeclSpace ds, int flags)
1401 return ds.AsAccessible (gt, flags);
1404 public override bool IsClass {
1405 get { return gt.IsClass; }
1408 public override bool IsValueType {
1409 get { return gt.IsValueType; }
1412 public override bool IsInterface {
1413 get { return gt.IsInterface; }
1416 public override bool IsSealed {
1417 get { return gt.IsSealed; }
1420 public override bool Equals (object obj)
1422 ConstructedType cobj = obj as ConstructedType;
1426 if ((type == null) || (cobj.type == null))
1429 return type == cobj.type;
1432 public override int GetHashCode ()
1434 return base.GetHashCode ();
1437 public override string Name {
1444 public override string FullName {
1451 public abstract class ConstraintChecker
1453 protected readonly Type[] gen_params;
1454 protected readonly Type[] atypes;
1455 protected readonly Location loc;
1457 protected ConstraintChecker (Type[] gen_params, Type[] atypes, Location loc)
1459 this.gen_params = gen_params;
1460 this.atypes = atypes;
1465 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1466 /// after fully resolving the constructed type.
1468 public bool CheckConstraints (IResolveContext ec)
1470 for (int i = 0; i < gen_params.Length; i++) {
1471 if (!CheckConstraints (ec, i))
1478 protected bool CheckConstraints (IResolveContext ec, int index)
1480 Type atype = atypes [index];
1481 Type ptype = gen_params [index];
1486 Expression aexpr = new EmptyExpression (atype);
1488 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1492 bool is_class, is_struct;
1493 if (atype.IsGenericParameter) {
1494 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1496 if (agc is Constraints)
1497 ((Constraints) agc).Resolve (ec);
1498 is_class = agc.HasReferenceTypeConstraint;
1499 is_struct = agc.HasValueTypeConstraint;
1501 is_class = is_struct = false;
1506 if (!atype.IsGenericType)
1508 is_class = atype.IsClass || atype.IsInterface;
1509 is_struct = atype.IsValueType && !TypeManager.IsNullableType (atype);
1513 // First, check the `class' and `struct' constraints.
1515 if (gc.HasReferenceTypeConstraint && !is_class) {
1516 Report.Error (452, loc, "The type `{0}' must be " +
1517 "a reference type in order to use it " +
1518 "as type parameter `{1}' in the " +
1519 "generic type or method `{2}'.",
1520 TypeManager.CSharpName (atype),
1521 TypeManager.CSharpName (ptype),
1522 GetSignatureForError ());
1524 } else if (gc.HasValueTypeConstraint && !is_struct) {
1525 Report.Error (453, loc, "The type `{0}' must be a " +
1526 "non-nullable value type in order to use it " +
1527 "as type parameter `{1}' in the " +
1528 "generic type or method `{2}'.",
1529 TypeManager.CSharpName (atype),
1530 TypeManager.CSharpName (ptype),
1531 GetSignatureForError ());
1536 // The class constraint comes next.
1538 if (gc.HasClassConstraint) {
1539 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint))
1544 // Now, check the interface constraints.
1546 if (gc.InterfaceConstraints != null) {
1547 foreach (Type it in gc.InterfaceConstraints) {
1548 if (!CheckConstraint (ec, ptype, aexpr, it))
1554 // Finally, check the constructor constraint.
1557 if (!gc.HasConstructorConstraint)
1560 if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
1563 if (HasDefaultConstructor (ec.DeclContainer.TypeBuilder, atype))
1566 Report_SymbolRelatedToPreviousError ();
1567 Report.SymbolRelatedToPreviousError (atype);
1568 Report.Error (310, loc, "The type `{0}' must have a public " +
1569 "parameterless constructor in order to use it " +
1570 "as parameter `{1}' in the generic type or " +
1572 TypeManager.CSharpName (atype),
1573 TypeManager.CSharpName (ptype),
1574 GetSignatureForError ());
1578 protected bool CheckConstraint (IResolveContext ec, Type ptype, Expression expr,
1581 if (TypeManager.HasGenericArguments (ctype)) {
1582 Type[] types = TypeManager.GetTypeArguments (ctype);
1584 TypeArguments new_args = new TypeArguments (loc);
1586 for (int i = 0; i < types.Length; i++) {
1589 if (t.IsGenericParameter) {
1590 int pos = t.GenericParameterPosition;
1593 new_args.Add (new TypeExpression (t, loc));
1596 TypeExpr ct = new ConstructedType (ctype, new_args, loc);
1597 if (ct.ResolveAsTypeStep (ec, false) == null)
1600 } else if (ctype.IsGenericParameter) {
1601 int pos = ctype.GenericParameterPosition;
1602 ctype = atypes [pos];
1605 if (Convert.ImplicitStandardConversionExists (expr, ctype))
1608 Error_TypeMustBeConvertible (expr.Type, ctype, ptype);
1612 bool HasDefaultConstructor (Type containerType, Type atype)
1614 if (atype.IsAbstract)
1618 atype = TypeManager.DropGenericTypeArguments (atype);
1619 if (atype is TypeBuilder) {
1620 TypeContainer tc = TypeManager.LookupTypeContainer (atype);
1621 if (tc.InstanceConstructors == null) {
1622 atype = atype.BaseType;
1626 foreach (Constructor c in tc.InstanceConstructors) {
1627 if ((c.ModFlags & Modifiers.PUBLIC) == 0)
1629 if ((c.Parameters.FixedParameters != null) &&
1630 (c.Parameters.FixedParameters.Length != 0))
1632 if (c.Parameters.HasArglist || c.Parameters.HasParams)
1639 TypeParameter tparam = TypeManager.LookupTypeParameter (atype);
1641 return tparam.HasConstructorConstraint;
1643 MemberList list = TypeManager.FindMembers (
1644 atype, MemberTypes.Constructor,
1645 BindingFlags.Public | BindingFlags.Instance |
1646 BindingFlags.DeclaredOnly, null, null);
1648 if (atype.IsAbstract || (list == null))
1651 foreach (MethodBase mb in list) {
1652 ParameterData pd = TypeManager.GetParameterData (mb);
1653 if ((pd.Count == 0) && mb.IsPublic && !mb.IsStatic)
1660 protected abstract string GetSignatureForError ();
1661 protected abstract void Report_SymbolRelatedToPreviousError ();
1663 void Error_TypeMustBeConvertible (Type atype, Type gc, Type ptype)
1665 Report_SymbolRelatedToPreviousError ();
1666 Report.SymbolRelatedToPreviousError (atype);
1667 Report.Error (309, loc,
1668 "The type `{0}' must be convertible to `{1}' in order to " +
1669 "use it as parameter `{2}' in the generic type or method `{3}'",
1670 TypeManager.CSharpName (atype), TypeManager.CSharpName (gc),
1671 TypeManager.CSharpName (ptype), GetSignatureForError ());
1674 public static bool CheckConstraints (EmitContext ec, MethodBase definition,
1675 MethodBase instantiated, Location loc)
1677 MethodConstraintChecker checker = new MethodConstraintChecker (
1678 definition, definition.GetGenericArguments (),
1679 instantiated.GetGenericArguments (), loc);
1681 return checker.CheckConstraints (ec);
1684 public static bool CheckConstraints (IResolveContext ec, Type gt, Type[] gen_params,
1685 Type[] atypes, Location loc)
1687 TypeConstraintChecker checker = new TypeConstraintChecker (
1688 gt, gen_params, atypes, loc);
1690 return checker.CheckConstraints (ec);
1693 protected class MethodConstraintChecker : ConstraintChecker
1695 MethodBase definition;
1697 public MethodConstraintChecker (MethodBase definition, Type[] gen_params,
1698 Type[] atypes, Location loc)
1699 : base (gen_params, atypes, loc)
1701 this.definition = definition;
1704 protected override string GetSignatureForError ()
1706 return TypeManager.CSharpSignature (definition);
1709 protected override void Report_SymbolRelatedToPreviousError ()
1711 Report.SymbolRelatedToPreviousError (definition);
1715 protected class TypeConstraintChecker : ConstraintChecker
1719 public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
1721 : base (gen_params, atypes, loc)
1726 protected override string GetSignatureForError ()
1728 return TypeManager.CSharpName (gt);
1731 protected override void Report_SymbolRelatedToPreviousError ()
1733 Report.SymbolRelatedToPreviousError (gt);
1739 /// A generic method definition.
1741 public class GenericMethod : DeclSpace
1743 Expression return_type;
1744 Parameters parameters;
1746 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
1747 Expression return_type, Parameters parameters)
1748 : base (ns, parent, name, null)
1750 this.return_type = return_type;
1751 this.parameters = parameters;
1754 public override TypeBuilder DefineType ()
1756 throw new Exception ();
1759 public override bool Define ()
1761 for (int i = 0; i < TypeParameters.Length; i++)
1762 if (!TypeParameters [i].Resolve (this))
1769 /// Define and resolve the type parameters.
1770 /// We're called from Method.Define().
1772 public bool Define (MethodBuilder mb, ToplevelBlock block)
1774 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1775 string[] snames = new string [names.Length];
1776 for (int i = 0; i < names.Length; i++) {
1777 string type_argument_name = names[i].Name;
1778 Parameter p = parameters.GetParameterByName (type_argument_name);
1780 Error_ParameterNameCollision (p.Location, type_argument_name, "method parameter");
1783 if (block != null) {
1784 LocalInfo li = (LocalInfo)block.Variables[type_argument_name];
1786 Error_ParameterNameCollision (li.Location, type_argument_name, "local variable");
1790 snames[i] = type_argument_name;
1793 GenericTypeParameterBuilder[] gen_params = mb.DefineGenericParameters (snames);
1794 for (int i = 0; i < TypeParameters.Length; i++)
1795 TypeParameters [i].Define (gen_params [i]);
1800 for (int i = 0; i < TypeParameters.Length; i++) {
1801 if (!TypeParameters [i].ResolveType (this))
1808 static void Error_ParameterNameCollision (Location loc, string name, string collisionWith)
1810 Report.Error (412, loc, "The type parameter name `{0}' is the same as `{1}'",
1811 name, collisionWith);
1815 /// We're called from MethodData.Define() after creating the MethodBuilder.
1817 public bool DefineType (EmitContext ec, MethodBuilder mb,
1818 MethodInfo implementing, bool is_override)
1820 for (int i = 0; i < TypeParameters.Length; i++)
1821 if (!TypeParameters [i].DefineType (
1822 ec, mb, implementing, is_override))
1826 foreach (Parameter p in parameters.FixedParameters){
1827 if (!p.Resolve (ec))
1830 if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec, false) == null))
1836 public void EmitAttributes ()
1838 for (int i = 0; i < TypeParameters.Length; i++)
1839 TypeParameters [i].EmitAttributes ();
1841 if (OptAttributes != null)
1842 OptAttributes.Emit ();
1845 public override bool DefineMembers ()
1850 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1851 MemberFilter filter, object criteria)
1853 throw new Exception ();
1856 public override MemberCache MemberCache {
1862 public override AttributeTargets AttributeTargets {
1864 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1868 public override string DocCommentHeader {
1869 get { return "M:"; }
1873 public class DefaultValueExpression : Expression
1877 public DefaultValueExpression (Expression expr, Location loc)
1883 public override Expression DoResolve (EmitContext ec)
1885 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
1891 eclass = ExprClass.Variable;
1895 public override void Emit (EmitContext ec)
1897 if (type.IsGenericParameter || TypeManager.IsValueType (type)) {
1898 LocalTemporary temp_storage = new LocalTemporary (type);
1900 temp_storage.AddressOf (ec, AddressOp.LoadStore);
1901 ec.ig.Emit (OpCodes.Initobj, type);
1902 temp_storage.Emit (ec);
1904 ec.ig.Emit (OpCodes.Ldnull);
1908 public class NullableType : TypeExpr
1910 Expression underlying;
1912 public NullableType (Expression underlying, Location l)
1914 this.underlying = underlying;
1917 eclass = ExprClass.Type;
1920 public NullableType (Type type, Location loc)
1921 : this (new TypeExpression (type, loc), loc)
1924 public override string Name {
1925 get { return underlying.ToString () + "?"; }
1928 public override string FullName {
1929 get { return underlying.ToString () + "?"; }
1932 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1934 TypeArguments args = new TypeArguments (loc);
1935 args.Add (underlying);
1937 ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
1938 return ctype.ResolveAsTypeTerminal (ec, false);
1942 public partial class TypeManager
1945 // A list of core types that the compiler requires or uses
1947 static public Type activator_type;
1948 static public Type generic_ilist_type;
1949 static public Type generic_icollection_type;
1950 static public Type generic_ienumerator_type;
1951 static public Type generic_ienumerable_type;
1952 static public Type generic_nullable_type;
1955 // Tracks the generic parameters.
1957 static PtrHashtable builder_to_type_param;
1960 // These methods are called by code generated by the compiler
1962 static public MethodInfo activator_create_instance;
1964 static void InitGenerics ()
1966 builder_to_type_param = new PtrHashtable ();
1969 static void CleanUpGenerics ()
1971 builder_to_type_param = null;
1974 static void InitGenericCoreTypes ()
1976 activator_type = CoreLookupType ("System", "Activator");
1978 generic_ilist_type = CoreLookupType (
1979 "System.Collections.Generic", "IList", 1);
1980 generic_icollection_type = CoreLookupType (
1981 "System.Collections.Generic", "ICollection", 1);
1982 generic_ienumerator_type = CoreLookupType (
1983 "System.Collections.Generic", "IEnumerator", 1);
1984 generic_ienumerable_type = CoreLookupType (
1985 "System.Collections.Generic", "IEnumerable", 1);
1986 generic_nullable_type = CoreLookupType (
1987 "System", "Nullable", 1);
1990 static void InitGenericCodeHelpers ()
1993 Type [] type_arg = { type_type };
1994 activator_create_instance = GetMethod (
1995 activator_type, "CreateInstance", type_arg);
1998 static Type CoreLookupType (string ns, string name, int arity)
2000 return CoreLookupType (ns, MemberName.MakeName (name, arity));
2003 public static void AddTypeParameter (Type t, TypeParameter tparam)
2005 if (!builder_to_type_param.Contains (t))
2006 builder_to_type_param.Add (t, tparam);
2009 public static TypeContainer LookupGenericTypeContainer (Type t)
2011 t = DropGenericTypeArguments (t);
2012 return LookupTypeContainer (t);
2015 public static TypeParameter LookupTypeParameter (Type t)
2017 return (TypeParameter) builder_to_type_param [t];
2020 public static GenericConstraints GetTypeParameterConstraints (Type t)
2022 if (!t.IsGenericParameter)
2023 throw new InvalidOperationException ();
2025 TypeParameter tparam = LookupTypeParameter (t);
2027 return tparam.GenericConstraints;
2029 return ReflectionConstraints.GetConstraints (t);
2032 public static bool HasGenericArguments (Type t)
2034 return GetNumberOfTypeArguments (t) > 0;
2037 public static int GetNumberOfTypeArguments (Type t)
2039 if (t.IsGenericParameter)
2041 DeclSpace tc = LookupDeclSpace (t);
2043 return tc.IsGeneric ? tc.CountTypeParameters : 0;
2045 return t.IsGenericType ? t.GetGenericArguments ().Length : 0;
2048 public static Type[] GetTypeArguments (Type t)
2050 DeclSpace tc = LookupDeclSpace (t);
2053 return Type.EmptyTypes;
2055 TypeParameter[] tparam = tc.TypeParameters;
2056 Type[] ret = new Type [tparam.Length];
2057 for (int i = 0; i < tparam.Length; i++) {
2058 ret [i] = tparam [i].Type;
2059 if (ret [i] == null)
2060 throw new InternalErrorException ();
2065 return t.GetGenericArguments ();
2068 public static Type DropGenericTypeArguments (Type t)
2070 if (!t.IsGenericType)
2072 // Micro-optimization: a generic typebuilder is always a generic type definition
2073 if (t is TypeBuilder)
2075 return t.GetGenericTypeDefinition ();
2078 public static MethodBase DropGenericMethodArguments (MethodBase m)
2080 if (m.IsGenericMethodDefinition)
2082 if (m.IsGenericMethod)
2083 return ((MethodInfo) m).GetGenericMethodDefinition ();
2084 if (!m.DeclaringType.IsGenericType)
2087 Type t = m.DeclaringType.GetGenericTypeDefinition ();
2088 BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
2089 BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
2091 if (m is ConstructorInfo) {
2092 foreach (ConstructorInfo c in t.GetConstructors (bf))
2093 if (c.MetadataToken == m.MetadataToken)
2096 foreach (MethodBase mb in t.GetMethods (bf))
2097 if (mb.MetadataToken == m.MetadataToken)
2104 public static FieldInfo GetGenericFieldDefinition (FieldInfo fi)
2106 if (fi.DeclaringType.IsGenericTypeDefinition ||
2107 !fi.DeclaringType.IsGenericType)
2110 Type t = fi.DeclaringType.GetGenericTypeDefinition ();
2111 BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
2112 BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
2114 foreach (FieldInfo f in t.GetFields (bf))
2115 if (f.MetadataToken == fi.MetadataToken)
2122 // Whether `array' is an array of T and `list' is `IList<T>'.
2123 // For instance "string[]" -> "IList<string>".
2125 public static bool IsIList (Type array, Type list)
2127 if (!array.IsArray || !list.IsGenericType)
2130 Type gt = list.GetGenericTypeDefinition ();
2131 if ((gt != generic_ilist_type) && (gt != generic_icollection_type) &&
2132 (gt != generic_ienumerable_type))
2135 Type arg_type = GetTypeArguments (list) [0];
2136 Type element_type = GetElementType (array);
2138 if (arg_type == element_type)
2140 else if (element_type.IsValueType)
2143 while (element_type != null) {
2144 if (arg_type == element_type)
2146 foreach (Type iface in element_type.GetInterfaces ())
2147 if (arg_type == iface)
2149 element_type = element_type.BaseType;
2155 public static bool IsEqual (Type a, Type b)
2160 if (a.IsGenericParameter && b.IsGenericParameter) {
2161 if (a.DeclaringMethod != b.DeclaringMethod &&
2162 (a.DeclaringMethod == null || b.DeclaringMethod == null))
2164 return a.GenericParameterPosition == b.GenericParameterPosition;
2167 if (a.IsArray && b.IsArray) {
2168 if (a.GetArrayRank () != b.GetArrayRank ())
2170 return IsEqual (a.GetElementType (), b.GetElementType ());
2173 if (a.IsByRef && b.IsByRef)
2174 return IsEqual (a.GetElementType (), b.GetElementType ());
2176 if (a.IsGenericType && b.IsGenericType) {
2177 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2180 Type[] aargs = a.GetGenericArguments ();
2181 Type[] bargs = b.GetGenericArguments ();
2183 if (aargs.Length != bargs.Length)
2186 for (int i = 0; i < aargs.Length; i++) {
2187 if (!IsEqual (aargs [i], bargs [i]))
2195 // This is to build with the broken circular dependencies between
2196 // System and System.Configuration in the 2.x profile where we
2197 // end up with a situation where:
2199 // System on the second build is referencing the System.Configuration
2200 // that has references to the first System build.
2202 // Point in case: NameValueCollection built on the first pass, vs
2203 // NameValueCollection build on the second one. The problem is that
2204 // we need to override some methods sometimes, or we need to
2206 if (RootContext.BrokenCircularDeps){
2207 if (a.Name == b.Name && a.Namespace == b.Namespace){
2208 Console.WriteLine ("GonziMatch: {0}.{1}", a.Namespace, a.Name);
2216 /// Check whether `a' and `b' may become equal generic types.
2217 /// The algorithm to do that is a little bit complicated.
2219 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_infered,
2220 Type[] method_infered)
2222 if (a.IsGenericParameter) {
2224 // If a is an array of a's type, they may never
2228 b = b.GetElementType ();
2234 // If b is a generic parameter or an actual type,
2235 // they may become equal:
2237 // class X<T,U> : I<T>, I<U>
2238 // class X<T> : I<T>, I<float>
2240 if (b.IsGenericParameter || !b.IsGenericType) {
2241 int pos = a.GenericParameterPosition;
2242 Type[] args = a.DeclaringMethod != null ? method_infered : class_infered;
2243 if (args [pos] == null) {
2248 return args [pos] == a;
2252 // We're now comparing a type parameter with a
2253 // generic instance. They may become equal unless
2254 // the type parameter appears anywhere in the
2255 // generic instance:
2257 // class X<T,U> : I<T>, I<X<U>>
2258 // -> error because you could instanciate it as
2261 // class X<T> : I<T>, I<X<T>> -> ok
2264 Type[] bargs = GetTypeArguments (b);
2265 for (int i = 0; i < bargs.Length; i++) {
2266 if (a.Equals (bargs [i]))
2273 if (b.IsGenericParameter)
2274 return MayBecomeEqualGenericTypes (b, a, class_infered, method_infered);
2277 // At this point, neither a nor b are a type parameter.
2279 // If one of them is a generic instance, let
2280 // MayBecomeEqualGenericInstances() compare them (if the
2281 // other one is not a generic instance, they can never
2285 if (a.IsGenericType || b.IsGenericType)
2286 return MayBecomeEqualGenericInstances (a, b, class_infered, method_infered);
2289 // If both of them are arrays.
2292 if (a.IsArray && b.IsArray) {
2293 if (a.GetArrayRank () != b.GetArrayRank ())
2296 a = a.GetElementType ();
2297 b = b.GetElementType ();
2299 return MayBecomeEqualGenericTypes (a, b, class_infered, method_infered);
2303 // Ok, two ordinary types.
2306 return a.Equals (b);
2310 // Checks whether two generic instances may become equal for some
2311 // particular instantiation (26.3.1).
2313 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
2314 Type[] class_infered,
2315 Type[] method_infered)
2317 if (!a.IsGenericType || !b.IsGenericType)
2319 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2322 return MayBecomeEqualGenericInstances (
2323 GetTypeArguments (a), GetTypeArguments (b), class_infered, method_infered);
2326 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
2327 Type[] class_infered,
2328 Type[] method_infered)
2330 if (aargs.Length != bargs.Length)
2333 for (int i = 0; i < aargs.Length; i++) {
2334 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_infered, method_infered))
2342 /// Check whether `type' and `parent' are both instantiations of the same
2343 /// generic type. Note that we do not check the type parameters here.
2345 public static bool IsInstantiationOfSameGenericType (Type type, Type parent)
2347 int tcount = GetNumberOfTypeArguments (type);
2348 int pcount = GetNumberOfTypeArguments (parent);
2350 if (tcount != pcount)
2353 type = DropGenericTypeArguments (type);
2354 parent = DropGenericTypeArguments (parent);
2356 return type.Equals (parent);
2360 /// Whether `mb' is a generic method definition.
2362 public static bool IsGenericMethodDefinition (MethodBase mb)
2364 if (mb.DeclaringType is TypeBuilder) {
2365 IMethodData method = (IMethodData) builder_to_method [mb];
2369 return method.GenericMethod != null;
2372 return mb.IsGenericMethodDefinition;
2376 /// Whether `mb' is a generic method definition.
2378 public static bool IsGenericMethod (MethodBase mb)
2380 if (mb.DeclaringType is TypeBuilder) {
2381 IMethodData method = (IMethodData) builder_to_method [mb];
2385 return method.GenericMethod != null;
2388 return mb.IsGenericMethod;
2395 static bool InferType (Type pt, Type at, Type[] infered)
2397 if (pt.IsGenericParameter) {
2398 if (pt.DeclaringMethod == null)
2401 int pos = pt.GenericParameterPosition;
2403 if (infered [pos] == null) {
2408 if (infered [pos] != at)
2414 if (!pt.ContainsGenericParameters) {
2415 if (at.ContainsGenericParameters)
2416 return InferType (at, pt, infered);
2423 if (at.GetArrayRank () != pt.GetArrayRank ())
2426 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2429 if (!pt.IsGenericType)
2432 Type gt = pt.GetGenericTypeDefinition ();
2433 if ((gt != generic_ilist_type) && (gt != generic_icollection_type) &&
2434 (gt != generic_ienumerable_type))
2437 Type[] args = GetTypeArguments (pt);
2438 return InferType (args [0], at.GetElementType (), infered);
2443 (pt.GetArrayRank () != at.GetArrayRank ()))
2446 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2449 if (pt.IsByRef && at.IsByRef)
2450 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2451 ArrayList list = new ArrayList ();
2452 if (at.IsGenericType)
2454 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
2457 list.AddRange (TypeManager.GetInterfaces (at));
2459 bool found_one = false;
2461 foreach (Type type in list) {
2462 if (!type.IsGenericType)
2465 Type[] infered_types = new Type [infered.Length];
2467 if (!InferGenericInstance (pt, type, infered_types))
2470 for (int i = 0; i < infered_types.Length; i++) {
2471 if (infered [i] == null) {
2472 infered [i] = infered_types [i];
2476 if (infered [i] != infered_types [i])
2486 static bool InferGenericInstance (Type pt, Type at, Type[] infered_types)
2488 Type[] at_args = at.GetGenericArguments ();
2489 Type[] pt_args = pt.GetGenericArguments ();
2491 if (at_args.Length != pt_args.Length)
2494 for (int i = 0; i < at_args.Length; i++) {
2495 if (!InferType (pt_args [i], at_args [i], infered_types))
2499 for (int i = 0; i < infered_types.Length; i++) {
2500 if (infered_types [i] == null)
2508 /// Type inference. Try to infer the type arguments from the params method
2509 /// `method', which is invoked with the arguments `arguments'. This is used
2510 /// when resolving an Invocation or a DelegateInvocation and the user
2511 /// did not explicitly specify type arguments.
2513 public static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
2514 ref MethodBase method)
2516 if (!TypeManager.IsGenericMethod (method))
2519 // if there are no arguments, there's no way to infer the type-arguments
2520 if (arguments == null || arguments.Count == 0)
2523 ParameterData pd = TypeManager.GetParameterData (method);
2524 int pd_count = pd.Count;
2525 int arg_count = arguments.Count;
2530 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2533 if (pd_count - 1 > arg_count)
2536 Type[] method_args = method.GetGenericArguments ();
2537 Type[] infered_types = new Type [method_args.Length];
2540 // If we have come this far, the case which
2541 // remains is when the number of parameters is
2542 // less than or equal to the argument count.
2544 for (int i = 0; i < pd_count - 1; ++i) {
2545 Argument a = (Argument) arguments [i];
2547 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2550 Type pt = pd.ParameterType (i);
2553 if (!InferType (pt, at, infered_types))
2557 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
2559 for (int i = pd_count - 1; i < arg_count; i++) {
2560 Argument a = (Argument) arguments [i];
2562 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2565 if (!InferType (element_type, a.Type, infered_types))
2569 for (int i = 0; i < infered_types.Length; i++)
2570 if (infered_types [i] == null)
2573 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2577 static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
2578 Type[] infered_types)
2580 if (infered_types == null)
2583 for (int i = 0; i < arg_types.Length; i++) {
2584 if (arg_types [i] == null)
2587 if (!InferType (param_types [i], arg_types [i], infered_types))
2591 for (int i = 0; i < infered_types.Length; i++)
2592 if (infered_types [i] == null)
2599 /// Type inference. Try to infer the type arguments from `method',
2600 /// which is invoked with the arguments `arguments'. This is used
2601 /// when resolving an Invocation or a DelegateInvocation and the user
2602 /// did not explicitly specify type arguments.
2604 public static bool InferTypeArguments (ArrayList arguments,
2605 ref MethodBase method)
2607 if (!TypeManager.IsGenericMethod (method))
2611 if (arguments != null)
2612 arg_count = arguments.Count;
2616 ParameterData pd = TypeManager.GetParameterData (method);
2617 if (arg_count != pd.Count)
2620 Type[] method_args = method.GetGenericArguments ();
2622 bool is_open = false;
2623 for (int i = 0; i < method_args.Length; i++) {
2624 if (method_args [i].IsGenericParameter) {
2630 // If none of the method parameters mention a generic parameter, we can't infer the generic parameters
2632 return !TypeManager.IsGenericMethodDefinition (method);
2634 Type[] infered_types = new Type [method_args.Length];
2636 Type[] param_types = new Type [pd.Count];
2637 Type[] arg_types = new Type [pd.Count];
2639 for (int i = 0; i < arg_count; i++) {
2640 param_types [i] = pd.ParameterType (i);
2642 Argument a = (Argument) arguments [i];
2643 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr) ||
2644 (a.Expr is AnonymousMethod))
2647 arg_types [i] = a.Type;
2650 if (!InferTypeArguments (param_types, arg_types, infered_types))
2653 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2660 public static bool InferTypeArguments (ParameterData apd,
2661 ref MethodBase method)
2663 if (!TypeManager.IsGenericMethod (method))
2666 ParameterData pd = TypeManager.GetParameterData (method);
2667 if (apd.Count != pd.Count)
2670 Type[] method_args = method.GetGenericArguments ();
2671 Type[] infered_types = new Type [method_args.Length];
2673 Type[] param_types = new Type [pd.Count];
2674 Type[] arg_types = new Type [pd.Count];
2676 for (int i = 0; i < apd.Count; i++) {
2677 param_types [i] = pd.ParameterType (i);
2678 arg_types [i] = apd.ParameterType (i);
2681 if (!InferTypeArguments (param_types, arg_types, infered_types))
2684 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2688 public static bool IsNullableType (Type t)
2690 return generic_nullable_type == DropGenericTypeArguments (t);
2693 public static bool IsNullableTypeOf (Type t, Type nullable)
2695 if (!IsNullableType (t))
2698 return GetTypeArguments (t) [0] == nullable;
2701 public static bool IsNullableValueType (Type t)
2703 if (!IsNullableType (t))
2706 return GetTypeArguments (t) [0].IsValueType;
2710 public abstract class Nullable
2712 public sealed class NullableInfo
2714 public readonly Type Type;
2715 public readonly Type UnderlyingType;
2716 public readonly MethodInfo HasValue;
2717 public readonly MethodInfo Value;
2718 public readonly ConstructorInfo Constructor;
2720 public NullableInfo (Type type)
2723 UnderlyingType = TypeManager.GetTypeArguments (type) [0];
2725 PropertyInfo has_value_pi = TypeManager.GetProperty (type, "HasValue");
2726 PropertyInfo value_pi = TypeManager.GetProperty (type, "Value");
2728 HasValue = has_value_pi.GetGetMethod (false);
2729 Value = value_pi.GetGetMethod (false);
2730 Constructor = type.GetConstructor (new Type[] { UnderlyingType });
2734 public class Unwrap : Expression, IMemoryLocation, IAssignMethod
2739 LocalTemporary temp;
2742 protected Unwrap (Expression expr)
2745 this.loc = expr.Location;
2748 public static Unwrap Create (Expression expr, EmitContext ec)
2750 return new Unwrap (expr).Resolve (ec) as Unwrap;
2753 public override Expression DoResolve (EmitContext ec)
2755 expr = expr.Resolve (ec);
2759 temp = new LocalTemporary (expr.Type);
2761 info = new NullableInfo (expr.Type);
2762 type = info.UnderlyingType;
2763 eclass = expr.eclass;
2767 public override void Emit (EmitContext ec)
2769 AddressOf (ec, AddressOp.LoadStore);
2770 ec.ig.EmitCall (OpCodes.Call, info.Value, null);
2773 public void EmitCheck (EmitContext ec)
2775 AddressOf (ec, AddressOp.LoadStore);
2776 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
2779 public void Store (EmitContext ec)
2784 void create_temp (EmitContext ec)
2786 if ((temp != null) && !has_temp) {
2793 public void AddressOf (EmitContext ec, AddressOp mode)
2797 temp.AddressOf (ec, AddressOp.LoadStore);
2799 ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
2802 public void Emit (EmitContext ec, bool leave_copy)
2815 public void EmitAssign (EmitContext ec, Expression source,
2816 bool leave_copy, bool prepare_for_load)
2818 InternalWrap wrap = new InternalWrap (source, info, loc);
2819 ((IAssignMethod) expr).EmitAssign (ec, wrap, leave_copy, false);
2822 protected class InternalWrap : Expression
2824 public Expression expr;
2825 public NullableInfo info;
2827 public InternalWrap (Expression expr, NullableInfo info, Location loc)
2834 eclass = ExprClass.Value;
2837 public override Expression DoResolve (EmitContext ec)
2842 public override void Emit (EmitContext ec)
2845 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2850 public class Wrap : Expression
2855 protected Wrap (Expression expr)
2858 this.loc = expr.Location;
2861 public static Wrap Create (Expression expr, EmitContext ec)
2863 return new Wrap (expr).Resolve (ec) as Wrap;
2866 public override Expression DoResolve (EmitContext ec)
2868 expr = expr.Resolve (ec);
2872 TypeExpr target_type = new NullableType (expr.Type, loc);
2873 target_type = target_type.ResolveAsTypeTerminal (ec, false);
2874 if (target_type == null)
2877 type = target_type.Type;
2878 info = new NullableInfo (type);
2879 eclass = ExprClass.Value;
2883 public override void Emit (EmitContext ec)
2886 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2890 public class NullableLiteral : NullLiteral, IMemoryLocation {
2891 public NullableLiteral (Type target_type, Location loc)
2894 this.type = target_type;
2896 eclass = ExprClass.Value;
2899 public override Expression DoResolve (EmitContext ec)
2904 public override void Emit (EmitContext ec)
2906 LocalTemporary value_target = new LocalTemporary (type);
2908 value_target.AddressOf (ec, AddressOp.Store);
2909 ec.ig.Emit (OpCodes.Initobj, type);
2910 value_target.Emit (ec);
2913 public void AddressOf (EmitContext ec, AddressOp Mode)
2915 LocalTemporary value_target = new LocalTemporary (type);
2917 value_target.AddressOf (ec, AddressOp.Store);
2918 ec.ig.Emit (OpCodes.Initobj, type);
2919 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
2923 public abstract class Lifted : Expression, IMemoryLocation
2925 Expression expr, underlying, wrap, null_value;
2928 protected Lifted (Expression expr, Location loc)
2934 public override Expression DoResolve (EmitContext ec)
2936 expr = expr.Resolve (ec);
2940 unwrap = Unwrap.Create (expr, ec);
2944 underlying = ResolveUnderlying (unwrap, ec);
2945 if (underlying == null)
2948 wrap = Wrap.Create (underlying, ec);
2952 null_value = new NullableLiteral (wrap.Type, loc).Resolve (ec);
2953 if (null_value == null)
2957 eclass = ExprClass.Value;
2961 protected abstract Expression ResolveUnderlying (Expression unwrap, EmitContext ec);
2963 public override void Emit (EmitContext ec)
2965 ILGenerator ig = ec.ig;
2966 Label is_null_label = ig.DefineLabel ();
2967 Label end_label = ig.DefineLabel ();
2969 unwrap.EmitCheck (ec);
2970 ig.Emit (OpCodes.Brfalse, is_null_label);
2973 ig.Emit (OpCodes.Br, end_label);
2975 ig.MarkLabel (is_null_label);
2976 null_value.Emit (ec);
2978 ig.MarkLabel (end_label);
2981 public void AddressOf (EmitContext ec, AddressOp mode)
2983 unwrap.AddressOf (ec, mode);
2987 public class LiftedConversion : Lifted
2989 public readonly bool IsUser;
2990 public readonly bool IsExplicit;
2991 public readonly Type TargetType;
2993 public LiftedConversion (Expression expr, Type target_type, bool is_user,
2994 bool is_explicit, Location loc)
2997 this.IsUser = is_user;
2998 this.IsExplicit = is_explicit;
2999 this.TargetType = target_type;
3002 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
3004 Type type = TypeManager.GetTypeArguments (TargetType) [0];
3007 return Convert.UserDefinedConversion (ec, unwrap, type, loc, IsExplicit);
3010 return Convert.ExplicitConversion (ec, unwrap, type, loc);
3012 return Convert.ImplicitConversion (ec, unwrap, type, loc);
3017 public class LiftedUnaryOperator : Lifted
3019 public readonly Unary.Operator Oper;
3021 public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
3027 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
3029 return new Unary (Oper, unwrap, loc);
3033 public class LiftedConditional : Lifted
3035 Expression true_expr, false_expr;
3037 public LiftedConditional (Expression expr, Expression true_expr, Expression false_expr,
3041 this.true_expr = true_expr;
3042 this.false_expr = false_expr;
3045 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
3047 return new Conditional (unwrap, true_expr, false_expr);
3051 public class LiftedBinaryOperator : Expression
3053 public readonly Binary.Operator Oper;
3055 Expression left, right, original_left, original_right;
3056 Expression underlying, null_value, bool_wrap;
3057 Unwrap left_unwrap, right_unwrap;
3058 bool is_equality, is_comparision, is_boolean;
3060 public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
3064 this.left = original_left = left;
3065 this.right = original_right = right;
3069 public override Expression DoResolve (EmitContext ec)
3071 if (TypeManager.IsNullableType (left.Type)) {
3072 left = left_unwrap = Unwrap.Create (left, ec);
3077 if (TypeManager.IsNullableType (right.Type)) {
3078 right = right_unwrap = Unwrap.Create (right, ec);
3083 if ((Oper == Binary.Operator.LogicalAnd) ||
3084 (Oper == Binary.Operator.LogicalOr)) {
3085 Binary.Error_OperatorCannotBeApplied (
3086 loc, Binary.OperName (Oper),
3087 original_left.GetSignatureForError (),
3088 original_right.GetSignatureForError ());
3092 if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr)) &&
3093 ((left.Type == TypeManager.bool_type) && (right.Type == TypeManager.bool_type))) {
3094 Expression empty = new EmptyExpression (TypeManager.bool_type);
3095 bool_wrap = Wrap.Create (empty, ec);
3096 null_value = new NullableLiteral (bool_wrap.Type, loc).Resolve (ec);
3098 type = bool_wrap.Type;
3100 } else if ((Oper == Binary.Operator.Equality) || (Oper == Binary.Operator.Inequality)) {
3101 if (!(left is NullLiteral) && !(right is NullLiteral)) {
3102 underlying = new Binary (Oper, left, right).Resolve (ec);
3103 if (underlying == null)
3107 type = TypeManager.bool_type;
3109 } else if ((Oper == Binary.Operator.LessThan) ||
3110 (Oper == Binary.Operator.GreaterThan) ||
3111 (Oper == Binary.Operator.LessThanOrEqual) ||
3112 (Oper == Binary.Operator.GreaterThanOrEqual)) {
3113 underlying = new Binary (Oper, left, right).Resolve (ec);
3114 if (underlying == null)
3117 type = TypeManager.bool_type;
3118 is_comparision = true;
3120 underlying = new Binary (Oper, left, right).Resolve (ec);
3121 if (underlying == null)
3124 underlying = Wrap.Create (underlying, ec);
3125 if (underlying == null)
3128 type = underlying.Type;
3129 null_value = new NullableLiteral (type, loc).Resolve (ec);
3132 eclass = ExprClass.Value;
3136 void EmitBoolean (EmitContext ec)
3138 ILGenerator ig = ec.ig;
3140 Label left_is_null_label = ig.DefineLabel ();
3141 Label right_is_null_label = ig.DefineLabel ();
3142 Label is_null_label = ig.DefineLabel ();
3143 Label wrap_label = ig.DefineLabel ();
3144 Label end_label = ig.DefineLabel ();
3146 if (left_unwrap != null) {
3147 left_unwrap.EmitCheck (ec);
3148 ig.Emit (OpCodes.Brfalse, left_is_null_label);
3152 ig.Emit (OpCodes.Dup);
3153 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3154 ig.Emit (OpCodes.Brtrue, wrap_label);
3156 ig.Emit (OpCodes.Brfalse, wrap_label);
3158 if (right_unwrap != null) {
3159 right_unwrap.EmitCheck (ec);
3160 ig.Emit (OpCodes.Brfalse, right_is_null_label);
3163 if ((Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr))
3164 ig.Emit (OpCodes.Pop);
3167 if (Oper == Binary.Operator.BitwiseOr)
3168 ig.Emit (OpCodes.Or);
3169 else if (Oper == Binary.Operator.BitwiseAnd)
3170 ig.Emit (OpCodes.And);
3171 ig.Emit (OpCodes.Br, wrap_label);
3173 ig.MarkLabel (left_is_null_label);
3174 if (right_unwrap != null) {
3175 right_unwrap.EmitCheck (ec);
3176 ig.Emit (OpCodes.Brfalse, is_null_label);
3180 ig.Emit (OpCodes.Dup);
3181 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3182 ig.Emit (OpCodes.Brtrue, wrap_label);
3184 ig.Emit (OpCodes.Brfalse, wrap_label);
3186 ig.MarkLabel (right_is_null_label);
3187 ig.Emit (OpCodes.Pop);
3188 ig.MarkLabel (is_null_label);
3189 null_value.Emit (ec);
3190 ig.Emit (OpCodes.Br, end_label);
3192 ig.MarkLabel (wrap_label);
3193 ig.Emit (OpCodes.Nop);
3194 bool_wrap.Emit (ec);
3195 ig.Emit (OpCodes.Nop);
3197 ig.MarkLabel (end_label);
3200 void EmitEquality (EmitContext ec)
3202 ILGenerator ig = ec.ig;
3204 // Given 'X? x;' for any value type X: 'x != null' is the same as 'x.HasValue'
3205 if (left is NullLiteral) {
3206 if (right_unwrap == null)
3207 throw new InternalErrorException ();
3208 right_unwrap.EmitCheck (ec);
3209 if (Oper == Binary.Operator.Equality) {
3210 ig.Emit (OpCodes.Ldc_I4_0);
3211 ig.Emit (OpCodes.Ceq);
3216 if (right is NullLiteral) {
3217 if (left_unwrap == null)
3218 throw new InternalErrorException ();
3219 left_unwrap.EmitCheck (ec);
3220 if (Oper == Binary.Operator.Equality) {
3221 ig.Emit (OpCodes.Ldc_I4_0);
3222 ig.Emit (OpCodes.Ceq);
3227 Label both_have_value_label = ig.DefineLabel ();
3228 Label end_label = ig.DefineLabel ();
3230 if (left_unwrap != null && right_unwrap != null) {
3231 Label dissimilar_label = ig.DefineLabel ();
3233 left_unwrap.EmitCheck (ec);
3234 ig.Emit (OpCodes.Dup);
3235 right_unwrap.EmitCheck (ec);
3236 ig.Emit (OpCodes.Bne_Un, dissimilar_label);
3238 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3241 if (Oper == Binary.Operator.Equality)
3242 ig.Emit (OpCodes.Ldc_I4_1);
3244 ig.Emit (OpCodes.Ldc_I4_0);
3245 ig.Emit (OpCodes.Br, end_label);
3247 ig.MarkLabel (dissimilar_label);
3248 ig.Emit (OpCodes.Pop);
3249 } else if (left_unwrap != null) {
3250 left_unwrap.EmitCheck (ec);
3251 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3252 } else if (right_unwrap != null) {
3253 right_unwrap.EmitCheck (ec);
3254 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3256 throw new InternalErrorException ("shouldn't get here");
3259 // one is null while the other isn't
3260 if (Oper == Binary.Operator.Equality)
3261 ig.Emit (OpCodes.Ldc_I4_0);
3263 ig.Emit (OpCodes.Ldc_I4_1);
3264 ig.Emit (OpCodes.Br, end_label);
3266 ig.MarkLabel (both_have_value_label);
3267 underlying.Emit (ec);
3269 ig.MarkLabel (end_label);
3272 void EmitComparision (EmitContext ec)
3274 ILGenerator ig = ec.ig;
3276 Label is_null_label = ig.DefineLabel ();
3277 Label end_label = ig.DefineLabel ();
3279 if (left_unwrap != null) {
3280 left_unwrap.EmitCheck (ec);
3281 ig.Emit (OpCodes.Brfalse, is_null_label);
3284 if (right_unwrap != null) {
3285 right_unwrap.EmitCheck (ec);
3286 ig.Emit (OpCodes.Brfalse, is_null_label);
3289 underlying.Emit (ec);
3290 ig.Emit (OpCodes.Br, end_label);
3292 ig.MarkLabel (is_null_label);
3293 ig.Emit (OpCodes.Ldc_I4_0);
3295 ig.MarkLabel (end_label);
3298 public override void Emit (EmitContext ec)
3300 if (left_unwrap != null)
3301 left_unwrap.Store (ec);
3302 if (right_unwrap != null)
3303 right_unwrap.Store (ec);
3308 } else if (is_equality) {
3311 } else if (is_comparision) {
3312 EmitComparision (ec);
3316 ILGenerator ig = ec.ig;
3318 Label is_null_label = ig.DefineLabel ();
3319 Label end_label = ig.DefineLabel ();
3321 if (left_unwrap != null) {
3322 left_unwrap.EmitCheck (ec);
3323 ig.Emit (OpCodes.Brfalse, is_null_label);
3326 if (right_unwrap != null) {
3327 right_unwrap.EmitCheck (ec);
3328 ig.Emit (OpCodes.Brfalse, is_null_label);
3331 underlying.Emit (ec);
3332 ig.Emit (OpCodes.Br, end_label);
3334 ig.MarkLabel (is_null_label);
3335 null_value.Emit (ec);
3337 ig.MarkLabel (end_label);
3341 public class OperatorTrueOrFalse : Expression
3343 public readonly bool IsTrue;
3348 public OperatorTrueOrFalse (Expression expr, bool is_true, Location loc)
3350 this.IsTrue = is_true;
3355 public override Expression DoResolve (EmitContext ec)
3357 unwrap = Unwrap.Create (expr, ec);
3361 if (unwrap.Type != TypeManager.bool_type)
3364 type = TypeManager.bool_type;
3365 eclass = ExprClass.Value;
3369 public override void Emit (EmitContext ec)
3371 ILGenerator ig = ec.ig;
3373 Label is_null_label = ig.DefineLabel ();
3374 Label end_label = ig.DefineLabel ();
3376 unwrap.EmitCheck (ec);
3377 ig.Emit (OpCodes.Brfalse, is_null_label);
3381 ig.Emit (OpCodes.Ldc_I4_0);
3382 ig.Emit (OpCodes.Ceq);
3384 ig.Emit (OpCodes.Br, end_label);
3386 ig.MarkLabel (is_null_label);
3387 ig.Emit (OpCodes.Ldc_I4_0);
3389 ig.MarkLabel (end_label);
3393 public class NullCoalescingOperator : Expression
3395 Expression left, right;
3399 public NullCoalescingOperator (Expression left, Expression right, Location loc)
3405 eclass = ExprClass.Value;
3408 public override Expression DoResolve (EmitContext ec)
3413 left = left.Resolve (ec);
3417 right = right.Resolve (ec);
3421 Type ltype = left.Type, rtype = right.Type;
3423 if (!TypeManager.IsNullableType (ltype) && ltype.IsValueType) {
3424 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3428 if (TypeManager.IsNullableType (ltype)) {
3429 NullableInfo info = new NullableInfo (ltype);
3431 unwrap = Unwrap.Create (left, ec);
3435 expr = Convert.ImplicitConversion (ec, right, info.UnderlyingType, loc);
3443 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
3449 if (unwrap != null) {
3450 expr = Convert.ImplicitConversion (ec, unwrap, rtype, loc);
3459 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3463 public override void Emit (EmitContext ec)
3465 ILGenerator ig = ec.ig;
3467 Label is_null_label = ig.DefineLabel ();
3468 Label end_label = ig.DefineLabel ();
3470 if (unwrap != null) {
3471 unwrap.EmitCheck (ec);
3472 ig.Emit (OpCodes.Brfalse, is_null_label);
3475 ig.Emit (OpCodes.Br, end_label);
3477 ig.MarkLabel (is_null_label);
3480 ig.MarkLabel (end_label);
3483 ig.Emit (OpCodes.Dup);
3484 ig.Emit (OpCodes.Brtrue, end_label);
3486 ig.MarkLabel (is_null_label);
3488 ig.Emit (OpCodes.Pop);
3491 ig.MarkLabel (end_label);
3496 public class LiftedUnaryMutator : ExpressionStatement
3498 public readonly UnaryMutator.Mode Mode;
3499 Expression expr, null_value;
3500 UnaryMutator underlying;
3503 public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
3509 eclass = ExprClass.Value;
3512 public override Expression DoResolve (EmitContext ec)
3514 expr = expr.Resolve (ec);
3518 unwrap = Unwrap.Create (expr, ec);
3522 underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
3523 if (underlying == null)
3526 null_value = new NullableLiteral (expr.Type, loc).Resolve (ec);
3527 if (null_value == null)
3534 void DoEmit (EmitContext ec, bool is_expr)
3536 ILGenerator ig = ec.ig;
3537 Label is_null_label = ig.DefineLabel ();
3538 Label end_label = ig.DefineLabel ();
3540 unwrap.EmitCheck (ec);
3541 ig.Emit (OpCodes.Brfalse, is_null_label);
3544 underlying.Emit (ec);
3546 underlying.EmitStatement (ec);
3547 ig.Emit (OpCodes.Br, end_label);
3549 ig.MarkLabel (is_null_label);
3551 null_value.Emit (ec);
3553 ig.MarkLabel (end_label);
3556 public override void Emit (EmitContext ec)
3561 public override void EmitStatement (EmitContext ec)