2 // generic.cs: Generics support
4 // Authors: Martin Baulig (martin@ximian.com)
5 // Miguel de Icaza (miguel@ximian.com)
7 // Licensed under the terms of the GNU GPL
9 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
10 // (C) 2004 Novell, Inc
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.Globalization;
16 using System.Collections;
18 using System.Text.RegularExpressions;
20 namespace Mono.CSharp {
23 /// Abstract base class for type parameter constraints.
24 /// The type parameter can come from a generic type definition or from reflection.
26 public abstract class GenericConstraints {
27 public abstract string TypeParameter {
31 public abstract GenericParameterAttributes Attributes {
35 public bool HasConstructorConstraint {
36 get { return (Attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0; }
39 public bool HasReferenceTypeConstraint {
40 get { return (Attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0; }
43 public bool HasValueTypeConstraint {
44 get { return (Attributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0; }
47 public virtual bool HasClassConstraint {
48 get { return ClassConstraint != null; }
51 public abstract Type ClassConstraint {
55 public abstract Type[] InterfaceConstraints {
59 public abstract Type EffectiveBaseClass {
64 // Returns whether the type parameter is "known to be a reference type".
66 public virtual bool IsReferenceType {
68 if (HasReferenceTypeConstraint)
70 if (HasValueTypeConstraint)
73 if (ClassConstraint != null) {
74 if (ClassConstraint.IsValueType)
77 if (ClassConstraint != TypeManager.object_type)
81 foreach (Type t in InterfaceConstraints) {
82 if (!t.IsGenericParameter)
85 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
86 if ((gc != null) && gc.IsReferenceType)
95 // Returns whether the type parameter is "known to be a value type".
97 public virtual bool IsValueType {
99 if (HasValueTypeConstraint)
101 if (HasReferenceTypeConstraint)
104 if (ClassConstraint != null) {
105 if (!ClassConstraint.IsValueType)
108 if (ClassConstraint != TypeManager.value_type)
112 foreach (Type t in InterfaceConstraints) {
113 if (!t.IsGenericParameter)
116 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
117 if ((gc != null) && gc.IsValueType)
126 public enum SpecialConstraint
134 /// Tracks the constraints for a type parameter from a generic type definition.
136 public class Constraints : GenericConstraints {
138 ArrayList constraints;
142 // name is the identifier, constraints is an arraylist of
143 // Expressions (with types) or `true' for the constructor constraint.
145 public Constraints (string name, ArrayList constraints,
149 this.constraints = constraints;
153 public override string TypeParameter {
159 GenericParameterAttributes attrs;
160 TypeExpr class_constraint;
161 ArrayList iface_constraints;
162 ArrayList type_param_constraints;
164 Type class_constraint_type;
165 Type[] iface_constraint_types;
166 Type effective_base_type;
171 /// Resolve the constraints - but only resolve things into Expression's, not
172 /// into actual types.
174 public bool Resolve (EmitContext ec)
179 iface_constraints = new ArrayList ();
180 type_param_constraints = new ArrayList ();
182 foreach (object obj in constraints) {
183 if (HasConstructorConstraint) {
184 Report.Error (401, loc,
185 "The new() constraint must be last.");
189 if (obj is SpecialConstraint) {
190 SpecialConstraint sc = (SpecialConstraint) obj;
192 if (sc == SpecialConstraint.Constructor) {
193 if (!HasValueTypeConstraint) {
194 attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
199 451, loc, "The new () constraint " +
200 "cannot be used with the `struct' " +
205 if ((num_constraints > 0) || HasReferenceTypeConstraint || HasValueTypeConstraint) {
206 Report.Error (449, loc,
207 "The `class' or `struct' " +
208 "constraint must be first");
212 if (sc == SpecialConstraint.ReferenceType)
213 attrs |= GenericParameterAttributes.ReferenceTypeConstraint;
215 attrs |= GenericParameterAttributes.NotNullableValueTypeConstraint;
219 int errors = Report.Errors;
220 FullNamedExpression fn = ((Expression) obj).ResolveAsTypeStep (ec);
223 if (errors != Report.Errors)
226 Report.Error (246, loc, "Cannot find type '{0}'", ((Expression) obj).GetSignatureForError ());
231 ConstructedType cexpr = fn as ConstructedType;
233 if (!cexpr.ResolveConstructedType (ec))
238 expr = fn.ResolveAsTypeTerminal (ec);
240 if ((expr == null) || (expr.Type == null))
243 TypeParameterExpr texpr = expr as TypeParameterExpr;
245 type_param_constraints.Add (expr);
246 else if (expr.IsInterface)
247 iface_constraints.Add (expr);
248 else if (class_constraint != null) {
249 Report.Error (406, loc,
250 "`{0}': the class constraint for `{1}' " +
251 "must come before any other constraints.",
254 } else if (HasReferenceTypeConstraint || HasValueTypeConstraint) {
255 Report.Error (450, loc, "`{0}': cannot specify both " +
256 "a constraint class and the `class' " +
257 "or `struct' constraint.", expr.Name);
260 class_constraint = expr;
265 ArrayList list = new ArrayList ();
266 foreach (TypeExpr iface_constraint in iface_constraints) {
267 foreach (Type type in list) {
268 if (!type.Equals (iface_constraint.Type))
271 Report.Error (405, loc,
272 "Duplicate constraint `{0}' for type " +
273 "parameter `{1}'.", iface_constraint.GetSignatureForError (),
278 list.Add (iface_constraint.Type);
281 foreach (TypeParameterExpr expr in type_param_constraints) {
282 foreach (Type type in list) {
283 if (!type.Equals (expr.Type))
286 Report.Error (405, loc,
287 "Duplicate constraint `{0}' for type " +
288 "parameter `{1}'.", expr.GetSignatureForError (), name);
292 list.Add (expr.Type);
295 iface_constraint_types = new Type [list.Count];
296 list.CopyTo (iface_constraint_types, 0);
298 if (class_constraint != null) {
299 class_constraint_type = class_constraint.Type;
300 if (class_constraint_type == null)
303 if (class_constraint_type.IsSealed) {
304 Report.Error (701, loc,
305 "`{0}' is not a valid bound. Bounds " +
306 "must be interfaces or non sealed " +
307 "classes", TypeManager.CSharpName (class_constraint_type));
311 if ((class_constraint_type == TypeManager.array_type) ||
312 (class_constraint_type == TypeManager.delegate_type) ||
313 (class_constraint_type == TypeManager.enum_type) ||
314 (class_constraint_type == TypeManager.value_type) ||
315 (class_constraint_type == TypeManager.object_type)) {
316 Report.Error (702, loc,
317 "Bound cannot be special class `{0}'",
318 TypeManager.CSharpName (class_constraint_type));
323 if (class_constraint_type != null)
324 effective_base_type = class_constraint_type;
325 else if (HasValueTypeConstraint)
326 effective_base_type = TypeManager.value_type;
328 effective_base_type = TypeManager.object_type;
334 bool CheckTypeParameterConstraints (TypeParameter tparam, Hashtable seen)
336 seen.Add (tparam, true);
338 Constraints constraints = tparam.Constraints;
339 if (constraints == null)
342 if (constraints.HasValueTypeConstraint) {
343 Report.Error (456, loc, "Type parameter `{0}' has " +
344 "the `struct' constraint, so it cannot " +
345 "be used as a constraint for `{1}'",
350 if (constraints.type_param_constraints == null)
353 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
354 if (seen.Contains (expr.TypeParameter)) {
355 Report.Error (454, loc, "Circular constraint " +
356 "dependency involving `{0}' and `{1}'",
357 tparam.Name, expr.Name);
361 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
369 /// Resolve the constraints into actual types.
371 public bool ResolveTypes (EmitContext ec)
376 resolved_types = true;
378 foreach (object obj in constraints) {
379 ConstructedType cexpr = obj as ConstructedType;
383 if (!cexpr.CheckConstraints (ec))
387 foreach (TypeParameterExpr expr in type_param_constraints) {
388 Hashtable seen = new Hashtable ();
389 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
393 foreach (TypeExpr iface_constraint in iface_constraints) {
394 if (iface_constraint.ResolveType (ec) == null)
398 if (class_constraint != null) {
399 if (class_constraint.ResolveType (ec) == null)
407 /// Check whether there are no conflicts in our type parameter constraints.
409 /// This is an example:
413 /// where U : T, struct
415 public bool CheckDependencies (EmitContext ec)
417 foreach (TypeParameterExpr expr in type_param_constraints) {
418 if (!CheckDependencies (expr.TypeParameter, ec))
425 bool CheckDependencies (TypeParameter tparam, EmitContext ec)
427 Constraints constraints = tparam.Constraints;
428 if (constraints == null)
431 if (HasValueTypeConstraint && constraints.HasClassConstraint) {
432 Report.Error (455, loc, "Type parameter `{0}' inherits " +
433 "conflicting constraints `{1}' and `{2}'",
434 name, TypeManager.CSharpName (constraints.ClassConstraint),
439 if (HasClassConstraint && constraints.HasClassConstraint) {
440 Type t1 = ClassConstraint;
441 TypeExpr e1 = class_constraint;
442 Type t2 = constraints.ClassConstraint;
443 TypeExpr e2 = constraints.class_constraint;
445 if (!Convert.ImplicitReferenceConversionExists (ec, e1, t2) &&
446 !Convert.ImplicitReferenceConversionExists (ec, e2, t1)) {
447 Report.Error (455, loc,
448 "Type parameter `{0}' inherits " +
449 "conflicting constraints `{1}' and `{2}'",
450 name, TypeManager.CSharpName (t1), TypeManager.CSharpName (t2));
455 if (constraints.type_param_constraints == null)
458 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
459 if (!CheckDependencies (expr.TypeParameter, ec))
466 public override GenericParameterAttributes Attributes {
467 get { return attrs; }
470 public override bool HasClassConstraint {
471 get { return class_constraint != null; }
474 public override Type ClassConstraint {
475 get { return class_constraint_type; }
478 public override Type[] InterfaceConstraints {
479 get { return iface_constraint_types; }
482 public override Type EffectiveBaseClass {
483 get { return effective_base_type; }
486 public bool IsSubclassOf (Type t)
488 if ((class_constraint_type != null) &&
489 class_constraint_type.IsSubclassOf (t))
492 if (iface_constraint_types == null)
495 foreach (Type iface in iface_constraint_types) {
496 if (TypeManager.IsSubclassOf (iface, t))
504 /// This is used when we're implementing a generic interface method.
505 /// Each method type parameter in implementing method must have the same
506 /// constraints than the corresponding type parameter in the interface
507 /// method. To do that, we're called on each of the implementing method's
510 public bool CheckInterfaceMethod (EmitContext ec, GenericConstraints gc)
512 if (gc.Attributes != attrs)
515 if (HasClassConstraint != gc.HasClassConstraint)
517 if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
520 int gc_icount = gc.InterfaceConstraints != null ?
521 gc.InterfaceConstraints.Length : 0;
522 int icount = InterfaceConstraints != null ?
523 InterfaceConstraints.Length : 0;
525 if (gc_icount != icount)
528 foreach (Type iface in gc.InterfaceConstraints) {
530 foreach (Type check in InterfaceConstraints) {
531 if (TypeManager.IsEqual (iface, check)) {
546 /// A type parameter from a generic type definition.
548 public class TypeParameter : MemberCore, IMemberContainer {
551 GenericConstraints gc;
552 Constraints constraints;
554 GenericTypeParameterBuilder type;
556 public TypeParameter (DeclSpace parent, DeclSpace decl, string name,
557 Constraints constraints, Attributes attrs, Location loc)
558 : base (parent, new MemberName (name, loc), attrs)
562 this.constraints = constraints;
566 public GenericConstraints GenericConstraints {
568 return gc != null ? gc : constraints;
572 public Constraints Constraints {
578 public bool HasConstructorConstraint {
580 if (constraints != null)
581 return constraints.HasConstructorConstraint;
587 public DeclSpace DeclSpace {
600 /// This is the first method which is called during the resolving
601 /// process; we're called immediately after creating the type parameters
602 /// with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
605 /// We're either called from TypeContainer.DefineType() or from
606 /// GenericMethod.Define() (called from Method.Define()).
608 public void Define (GenericTypeParameterBuilder type)
610 if (this.type != null)
611 throw new InvalidOperationException ();
614 TypeManager.AddTypeParameter (type, this);
618 /// This is the second method which is called during the resolving
619 /// process - in case of class type parameters, we're called from
620 /// TypeContainer.ResolveType() - after it resolved the class'es
621 /// base class and interfaces. For method type parameters, we're
622 /// called immediately after Define().
624 /// We're just resolving the constraints into expressions here, we
625 /// don't resolve them into actual types.
627 /// Note that in the special case of partial generic classes, we may be
628 /// called _before_ Define() and we may also be called multiple types.
630 public bool Resolve (DeclSpace ds)
632 if (constraints != null) {
633 if (!constraints.Resolve (ds.EmitContext)) {
643 /// This is the third method which is called during the resolving
644 /// process. We're called immediately after calling DefineConstraints()
645 /// on all of the current class'es type parameters.
647 /// Our job is to resolve the constraints to actual types.
649 /// Note that we may have circular dependencies on type parameters - this
650 /// is why Resolve() and ResolveType() are separate.
652 public bool ResolveType (EmitContext ec)
654 if (constraints != null) {
655 if (!constraints.ResolveTypes (ec)) {
665 /// This is the fourth and last method which is called during the resolving
666 /// process. We're called after everything is fully resolved and actually
667 /// register the constraints with SRE and the TypeManager.
669 public bool DefineType (EmitContext ec)
671 return DefineType (ec, null, null, false);
675 /// This is the fith and last method which is called during the resolving
676 /// process. We're called after everything is fully resolved and actually
677 /// register the constraints with SRE and the TypeManager.
679 /// The `builder', `implementing' and `is_override' arguments are only
680 /// applicable to method type parameters.
682 public bool DefineType (EmitContext ec, MethodBuilder builder,
683 MethodInfo implementing, bool is_override)
685 if (!ResolveType (ec))
688 if (implementing != null) {
689 if (is_override && (constraints != null)) {
691 460, loc, "Constraints for override and " +
692 "explicit interface implementation methods " +
693 "are inherited from the base method so they " +
694 "cannot be specified directly");
698 MethodBase mb = implementing;
699 if (mb.Mono_IsInflatedMethod)
700 mb = mb.GetGenericMethodDefinition ();
702 int pos = type.GenericParameterPosition;
703 Type mparam = mb.GetGenericArguments () [pos];
704 GenericConstraints temp_gc = ReflectionConstraints.GetConstraints (mparam);
707 gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
708 else if (constraints != null)
709 gc = new InflatedConstraints (constraints, implementing.DeclaringType);
712 if (constraints != null) {
715 else if (!constraints.CheckInterfaceMethod (ec, gc))
718 if (!is_override && (temp_gc != null))
723 Report.SymbolRelatedToPreviousError (implementing);
726 425, loc, "The constraints for type " +
727 "parameter `{0}' of method `{1}' must match " +
728 "the constraints for type parameter `{2}' " +
729 "of interface method `{3}'. Consider using " +
730 "an explicit interface implementation instead",
731 Name, TypeManager.CSharpSignature (builder),
732 TypeManager.CSharpName (mparam), TypeManager.CSharpSignature (mb));
735 } else if (DeclSpace is Iterator) {
736 TypeParameter[] tparams = DeclSpace.TypeParameters;
737 Type[] types = new Type [tparams.Length];
738 for (int i = 0; i < tparams.Length; i++)
739 types [i] = tparams [i].Type;
741 if (constraints != null)
742 gc = new InflatedConstraints (constraints, types);
744 gc = (GenericConstraints) constraints;
750 if (gc.HasClassConstraint)
751 type.SetBaseTypeConstraint (gc.ClassConstraint);
753 type.SetInterfaceConstraints (gc.InterfaceConstraints);
754 type.SetGenericParameterAttributes (gc.Attributes);
755 TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
761 /// Check whether there are no conflicts in our type parameter constraints.
763 /// This is an example:
767 /// where U : T, struct
769 public bool CheckDependencies (EmitContext ec)
771 if (constraints != null)
772 return constraints.CheckDependencies (ec);
778 /// This is called for each part of a partial generic type definition.
780 /// If `new_constraints' is not null and we don't already have constraints,
781 /// they become our constraints. If we already have constraints, we must
782 /// check that they're the same.
785 public bool UpdateConstraints (EmitContext ec, Constraints new_constraints)
788 throw new InvalidOperationException ();
790 if (constraints == null) {
791 new_constraints = constraints;
793 } else if (new_constraints == null)
796 if (!new_constraints.Resolve (ec))
798 if (!new_constraints.ResolveTypes (ec))
801 return constraints.CheckInterfaceMethod (ec, new_constraints);
804 public void EmitAttributes (EmitContext ec)
806 if (OptAttributes != null)
807 OptAttributes.Emit (ec, this);
810 public override string DocCommentHeader {
812 throw new InvalidOperationException (
813 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
821 public override bool Define ()
826 public override void ApplyAttributeBuilder (Attribute a,
827 CustomAttributeBuilder cb)
829 type.SetCustomAttribute (cb);
832 public override AttributeTargets AttributeTargets {
834 return (AttributeTargets) AttributeTargets.GenericParameter;
838 public override string[] ValidAttributeTargets {
840 return new string [] { "type parameter" };
848 string IMemberContainer.Name {
852 MemberCache IMemberContainer.BaseCache {
856 bool IMemberContainer.IsInterface {
860 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
862 return FindMembers (mt, bf, null, null);
865 MemberCache IMemberContainer.MemberCache {
869 public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
870 MemberFilter filter, object criteria)
872 if (constraints == null)
873 return MemberList.Empty;
875 ArrayList members = new ArrayList ();
877 if (gc.HasClassConstraint) {
878 MemberList list = TypeManager.FindMembers (
879 gc.ClassConstraint, mt, bf, filter, criteria);
881 members.AddRange (list);
884 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
885 foreach (Type t in ifaces) {
886 MemberList list = TypeManager.FindMembers (
887 t, mt, bf, filter, criteria);
889 members.AddRange (list);
892 return new MemberList (members);
895 public bool IsSubclassOf (Type t)
900 if (constraints != null)
901 return constraints.IsSubclassOf (t);
906 public override string ToString ()
908 return "TypeParameter[" + name + "]";
911 public static string GetSignatureForError (TypeParameter[] tp)
913 if (tp == null || tp.Length == 0)
916 StringBuilder sb = new StringBuilder ("<");
917 for (int i = 0; i < tp.Length; ++i) {
920 sb.Append (tp[i].GetSignatureForError ());
923 return sb.ToString ();
926 public void InflateConstraints (Type declaring)
928 if (constraints != null)
929 gc = new InflatedConstraints (constraints, declaring);
932 protected class InflatedConstraints : GenericConstraints
934 GenericConstraints gc;
936 Type class_constraint;
937 Type[] iface_constraints;
940 public InflatedConstraints (GenericConstraints gc, Type declaring)
941 : this (gc, TypeManager.GetTypeArguments (declaring))
944 public InflatedConstraints (GenericConstraints gc, Type[] dargs)
949 ArrayList list = new ArrayList ();
950 if (gc.HasClassConstraint)
951 list.Add (inflate (gc.ClassConstraint));
952 foreach (Type iface in gc.InterfaceConstraints)
953 list.Add (inflate (iface));
955 bool has_class_constr = false;
956 if (list.Count > 0) {
957 Type first = (Type) list [0];
958 has_class_constr = !first.IsInterface && !first.IsGenericParameter;
961 if ((list.Count > 0) && has_class_constr) {
962 class_constraint = (Type) list [0];
963 iface_constraints = new Type [list.Count - 1];
964 list.CopyTo (1, iface_constraints, 0, list.Count - 1);
966 iface_constraints = new Type [list.Count];
967 list.CopyTo (iface_constraints, 0);
970 if (HasValueTypeConstraint)
971 base_type = TypeManager.value_type;
972 else if (class_constraint != null)
973 base_type = class_constraint;
975 base_type = TypeManager.object_type;
978 Type inflate (Type t)
982 if (t.IsGenericParameter)
983 return dargs [t.GenericParameterPosition];
984 if (t.IsGenericInstance) {
985 t = t.GetGenericTypeDefinition ();
986 t = t.MakeGenericType (dargs);
992 public override string TypeParameter {
993 get { return gc.TypeParameter; }
996 public override GenericParameterAttributes Attributes {
997 get { return gc.Attributes; }
1000 public override Type ClassConstraint {
1001 get { return class_constraint; }
1004 public override Type EffectiveBaseClass {
1005 get { return base_type; }
1008 public override Type[] InterfaceConstraints {
1009 get { return iface_constraints; }
1015 /// A TypeExpr which already resolved to a type parameter.
1017 public class TypeParameterExpr : TypeExpr {
1018 TypeParameter type_parameter;
1020 public override string Name {
1022 return type_parameter.Name;
1026 public override string FullName {
1028 return type_parameter.Name;
1032 public TypeParameter TypeParameter {
1034 return type_parameter;
1038 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1040 this.type_parameter = type_parameter;
1044 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
1046 type = type_parameter.Type;
1051 public override bool IsInterface {
1052 get { return false; }
1055 public override bool CheckAccessLevel (DeclSpace ds)
1060 public void Error_CannotUseAsUnmanagedType (Location loc)
1062 Report.Error (-203, loc, "Can not use type parameter as unamanged type");
1067 /// Tracks the type arguments when instantiating a generic type. We're used in
1068 /// ConstructedType.
1070 public class TypeArguments {
1071 public readonly Location Location;
1078 public TypeArguments (Location loc)
1080 args = new ArrayList ();
1081 this.Location = loc;
1084 public TypeArguments (int dimension, Location loc)
1086 this.dimension = dimension;
1087 this.Location = loc;
1090 public void Add (Expression type)
1093 throw new InvalidOperationException ();
1098 public void Add (TypeArguments new_args)
1101 throw new InvalidOperationException ();
1103 args.AddRange (new_args.args);
1107 /// We're used during the parsing process: the parser can't distinguish
1108 /// between type parameters and type arguments. Because of that, the
1109 /// parser creates a `MemberName' with `TypeArguments' for both cases and
1110 /// in case of a generic type definition, we call GetDeclarations().
1112 public TypeParameterName[] GetDeclarations ()
1114 TypeParameterName[] ret = new TypeParameterName [args.Count];
1115 for (int i = 0; i < args.Count; i++) {
1116 TypeParameterName name = args [i] as TypeParameterName;
1121 SimpleName sn = args [i] as SimpleName;
1123 ret [i] = new TypeParameterName (sn.Name, null, sn.Location);
1127 Report.Error (81, Location, "Type parameter declaration " +
1128 "must be an identifier not a type");
1135 /// We may only be used after Resolve() is called and return the fully
1138 public Type[] Arguments {
1144 public bool HasTypeArguments {
1146 return has_type_args;
1159 public bool IsUnbound {
1161 return dimension > 0;
1165 public override string ToString ()
1167 StringBuilder s = new StringBuilder ();
1170 for (int i = 0; i < count; i++){
1172 // FIXME: Use TypeManager.CSharpname once we have the type
1175 s.Append (args [i].ToString ());
1179 return s.ToString ();
1183 /// Resolve the type arguments.
1185 public bool Resolve (EmitContext ec)
1187 int count = args.Count;
1190 atypes = new Type [count];
1192 for (int i = 0; i < count; i++){
1193 TypeExpr te = ((Expression) args [i]).ResolveAsTypeTerminal (ec);
1198 if (te is TypeParameterExpr)
1199 has_type_args = true;
1201 if (te.Type.IsPointer) {
1202 Report.Error (306, Location, "The type `{0}' may not be used " +
1203 "as a type argument.", TypeManager.CSharpName (te.Type));
1205 } else if (te.Type == TypeManager.void_type) {
1206 Report.Error (1547, Location,
1207 "Keyword `void' cannot be used in this context");
1211 atypes [i] = te.Type;
1217 public class TypeParameterName : SimpleName
1219 Attributes attributes;
1221 public TypeParameterName (string name, Attributes attrs, Location loc)
1227 public Attributes OptAttributes {
1235 /// An instantiation of a generic type.
1237 public class ConstructedType : TypeExpr {
1239 FullNamedExpression name;
1241 Type[] gen_params, atypes;
1245 /// Instantiate the generic type `fname' with the type arguments `args'.
1247 public ConstructedType (FullNamedExpression fname, TypeArguments args, Location l)
1253 eclass = ExprClass.Type;
1254 full_name = name + "<" + args.ToString () + ">";
1257 protected ConstructedType (TypeArguments args, Location l)
1262 eclass = ExprClass.Type;
1265 protected ConstructedType (TypeParameter[] type_params, Location l)
1269 args = new TypeArguments (l);
1270 foreach (TypeParameter type_param in type_params)
1271 args.Add (new TypeParameterExpr (type_param, l));
1273 eclass = ExprClass.Type;
1277 /// This is used to construct the `this' type inside a generic type definition.
1279 public ConstructedType (Type t, TypeParameter[] type_params, Location l)
1280 : this (type_params, l)
1282 gt = t.GetGenericTypeDefinition ();
1284 this.name = new TypeExpression (gt, l);
1285 full_name = gt.FullName + "<" + args.ToString () + ">";
1289 /// Instantiate the generic type `t' with the type arguments `args'.
1290 /// Use this constructor if you already know the fully resolved
1293 public ConstructedType (Type t, TypeArguments args, Location l)
1296 gt = t.GetGenericTypeDefinition ();
1298 this.name = new TypeExpression (gt, l);
1299 full_name = gt.FullName + "<" + args.ToString () + ">";
1302 public TypeArguments TypeArguments {
1303 get { return args; }
1306 public override string GetSignatureForError ()
1308 return TypeManager.CSharpName (gt);
1311 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
1313 if (!ResolveConstructedType (ec))
1320 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1321 /// after fully resolving the constructed type.
1323 public bool CheckConstraints (EmitContext ec)
1325 return ConstraintChecker.CheckConstraints (ec, gt, gen_params, atypes, loc);
1329 /// Resolve the constructed type, but don't check the constraints.
1331 public bool ResolveConstructedType (EmitContext ec)
1335 // If we already know the fully resolved generic type.
1337 return DoResolveType (ec);
1343 Report.Error (246, loc, "Cannot find type `{0}'<...>", Name);
1347 num_args = TypeManager.GetNumberOfTypeArguments (t);
1348 if (num_args == 0) {
1349 Report.Error (308, loc,
1350 "The non-generic type `{0}' cannot " +
1351 "be used with type arguments.",
1352 TypeManager.CSharpName (t));
1356 gt = t.GetGenericTypeDefinition ();
1357 return DoResolveType (ec);
1360 bool DoResolveType (EmitContext ec)
1363 // Resolve the arguments.
1365 if (args.Resolve (ec) == false)
1368 gen_params = gt.GetGenericArguments ();
1369 atypes = args.Arguments;
1371 if (atypes.Length != gen_params.Length) {
1372 Report.Error (305, loc,
1373 "Using the generic type `{0}' " +
1374 "requires {1} type arguments",
1375 TypeManager.CSharpName (gt),
1376 gen_params.Length.ToString ());
1381 // Now bind the parameters.
1383 type = gt.MakeGenericType (atypes);
1387 public Expression GetSimpleName (EmitContext ec)
1392 public override bool CheckAccessLevel (DeclSpace ds)
1394 return ds.CheckAccessLevel (gt);
1397 public override bool AsAccessible (DeclSpace ds, int flags)
1399 return ds.AsAccessible (gt, flags);
1402 public override bool IsClass {
1403 get { return gt.IsClass; }
1406 public override bool IsValueType {
1407 get { return gt.IsValueType; }
1410 public override bool IsInterface {
1411 get { return gt.IsInterface; }
1414 public override bool IsSealed {
1415 get { return gt.IsSealed; }
1418 public override bool Equals (object obj)
1420 ConstructedType cobj = obj as ConstructedType;
1424 if ((type == null) || (cobj.type == null))
1427 return type == cobj.type;
1430 public override int GetHashCode ()
1432 return base.GetHashCode ();
1435 public override string Name {
1442 public override string FullName {
1449 public abstract class ConstraintChecker
1451 protected readonly Type[] gen_params;
1452 protected readonly Type[] atypes;
1453 protected readonly Location loc;
1455 protected ConstraintChecker (Type[] gen_params, Type[] atypes, Location loc)
1457 this.gen_params = gen_params;
1458 this.atypes = atypes;
1463 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1464 /// after fully resolving the constructed type.
1466 public bool CheckConstraints (EmitContext ec)
1468 for (int i = 0; i < gen_params.Length; i++) {
1469 if (!CheckConstraints (ec, i))
1476 protected bool CheckConstraints (EmitContext ec, int index)
1478 Type atype = atypes [index];
1479 Type ptype = gen_params [index];
1484 Expression aexpr = new EmptyExpression (atype);
1486 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1490 bool is_class, is_struct;
1491 if (atype.IsGenericParameter) {
1492 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1494 is_class = agc.HasReferenceTypeConstraint;
1495 is_struct = agc.HasValueTypeConstraint;
1497 is_class = is_struct = false;
1500 is_class = atype.IsClass;
1501 is_struct = atype.IsValueType;
1505 // First, check the `class' and `struct' constraints.
1507 if (gc.HasReferenceTypeConstraint && !is_class) {
1508 Report.Error (452, loc, "The type `{0}' must be " +
1509 "a reference type in order to use it " +
1510 "as type parameter `{1}' in the " +
1511 "generic type or method `{2}'.",
1512 TypeManager.CSharpName (atype),
1513 TypeManager.CSharpName (ptype),
1514 GetSignatureForError ());
1516 } else if (gc.HasValueTypeConstraint && !is_struct) {
1517 Report.Error (453, loc, "The type `{0}' must be " +
1518 "a value type in order to use it " +
1519 "as type parameter `{1}' in the " +
1520 "generic type or method `{2}'.",
1521 TypeManager.CSharpName (atype),
1522 TypeManager.CSharpName (ptype),
1523 GetSignatureForError ());
1528 // The class constraint comes next.
1530 if (gc.HasClassConstraint) {
1531 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint)) {
1532 Error_TypeMustBeConvertible (atype, gc.ClassConstraint, ptype);
1538 // Now, check the interface constraints.
1540 foreach (Type it in gc.InterfaceConstraints) {
1542 if (it.IsGenericParameter)
1543 itype = atypes [it.GenericParameterPosition];
1547 if (!CheckConstraint (ec, ptype, aexpr, itype)) {
1548 Error_TypeMustBeConvertible (atype, itype, ptype);
1554 // Finally, check the constructor constraint.
1557 if (!gc.HasConstructorConstraint)
1560 if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
1563 if (HasDefaultConstructor (ec, 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 (EmitContext 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) == null)
1602 return Convert.ImplicitStandardConversionExists (ec, expr, ctype);
1605 bool HasDefaultConstructor (EmitContext ec, Type atype)
1607 if (atype is TypeBuilder) {
1608 if (atype.IsAbstract)
1611 TypeContainer tc = TypeManager.LookupTypeContainer (atype);
1612 foreach (Constructor c in tc.InstanceConstructors) {
1613 if ((c.ModFlags & Modifiers.PUBLIC) == 0)
1615 if ((c.Parameters.FixedParameters != null) &&
1616 (c.Parameters.FixedParameters.Length != 0))
1618 if (c.Parameters.HasArglist || c.Parameters.HasParams)
1625 MethodGroupExpr mg = Expression.MemberLookup (
1626 ec, atype, ".ctor", MemberTypes.Constructor,
1627 BindingFlags.Public | BindingFlags.Instance |
1628 BindingFlags.DeclaredOnly, loc)
1631 if (!atype.IsAbstract && (mg != null) && mg.IsInstance) {
1632 foreach (MethodBase mb in mg.Methods) {
1633 ParameterData pd = TypeManager.GetParameterData (mb);
1642 protected abstract string GetSignatureForError ();
1643 protected abstract void Report_SymbolRelatedToPreviousError ();
1645 void Error_TypeMustBeConvertible (Type atype, Type gc, Type ptype)
1647 Report_SymbolRelatedToPreviousError ();
1648 Report.SymbolRelatedToPreviousError (atype);
1649 Report.Error (309, loc,
1650 "The type `{0}' must be convertible to `{1}' in order to " +
1651 "use it as parameter `{2}' in the generic type or method `{3}'",
1652 TypeManager.CSharpName (atype), TypeManager.CSharpName (gc),
1653 TypeManager.CSharpName (ptype), GetSignatureForError ());
1656 public static bool CheckConstraints (EmitContext ec, MethodBase definition,
1657 MethodBase instantiated, Location loc)
1659 MethodConstraintChecker checker = new MethodConstraintChecker (
1660 definition, definition.GetGenericArguments (),
1661 instantiated.GetGenericArguments (), loc);
1663 return checker.CheckConstraints (ec);
1666 public static bool CheckConstraints (EmitContext ec, Type gt, Type[] gen_params,
1667 Type[] atypes, Location loc)
1669 TypeConstraintChecker checker = new TypeConstraintChecker (
1670 gt, gen_params, atypes, loc);
1672 return checker.CheckConstraints (ec);
1675 protected class MethodConstraintChecker : ConstraintChecker
1677 MethodBase definition;
1679 public MethodConstraintChecker (MethodBase definition, Type[] gen_params,
1680 Type[] atypes, Location loc)
1681 : base (gen_params, atypes, loc)
1683 this.definition = definition;
1686 protected override string GetSignatureForError ()
1688 return TypeManager.CSharpSignature (definition);
1691 protected override void Report_SymbolRelatedToPreviousError ()
1693 Report.SymbolRelatedToPreviousError (definition);
1697 protected class TypeConstraintChecker : ConstraintChecker
1701 public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
1703 : base (gen_params, atypes, loc)
1708 protected override string GetSignatureForError ()
1710 return TypeManager.CSharpName (gt);
1713 protected override void Report_SymbolRelatedToPreviousError ()
1715 Report.SymbolRelatedToPreviousError (gt);
1721 /// A generic method definition.
1723 public class GenericMethod : DeclSpace
1725 Expression return_type;
1726 Parameters parameters;
1728 public GenericMethod (NamespaceEntry ns, TypeContainer parent, MemberName name,
1729 Expression return_type, Parameters parameters)
1730 : base (ns, parent, name, null)
1732 this.return_type = return_type;
1733 this.parameters = parameters;
1736 public override TypeBuilder DefineType ()
1738 throw new Exception ();
1741 public override bool Define ()
1743 ec = new EmitContext (this, this, Location, null, null, ModFlags, false);
1745 for (int i = 0; i < TypeParameters.Length; i++)
1746 if (!TypeParameters [i].Resolve (this))
1753 /// Define and resolve the type parameters.
1754 /// We're called from Method.Define().
1756 public bool Define (MethodBuilder mb)
1758 GenericTypeParameterBuilder[] gen_params;
1759 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1760 string[] snames = new string [names.Length];
1761 for (int i = 0; i < names.Length; i++)
1762 snames [i] = names [i].Name;
1763 gen_params = mb.DefineGenericParameters (snames);
1764 for (int i = 0; i < TypeParameters.Length; i++)
1765 TypeParameters [i].Define (gen_params [i]);
1770 for (int i = 0; i < TypeParameters.Length; i++) {
1771 if (!TypeParameters [i].ResolveType (ec))
1779 /// We're called from MethodData.Define() after creating the MethodBuilder.
1781 public bool DefineType (EmitContext ec, MethodBuilder mb,
1782 MethodInfo implementing, bool is_override)
1784 for (int i = 0; i < TypeParameters.Length; i++)
1785 if (!TypeParameters [i].DefineType (
1786 ec, mb, implementing, is_override))
1790 foreach (Parameter p in parameters.FixedParameters){
1791 if (!p.Resolve (ec))
1794 if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec) == null))
1800 public void EmitAttributes (EmitContext ec)
1802 for (int i = 0; i < TypeParameters.Length; i++)
1803 TypeParameters [i].EmitAttributes (ec);
1805 if (OptAttributes != null)
1806 OptAttributes.Emit (ec, this);
1809 public override bool DefineMembers ()
1814 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1815 MemberFilter filter, object criteria)
1817 throw new Exception ();
1820 public override MemberCache MemberCache {
1826 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1828 base.ApplyAttributeBuilder (a, cb);
1831 public override AttributeTargets AttributeTargets {
1833 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1837 public override string DocCommentHeader {
1838 get { return "M:"; }
1842 public class DefaultValueExpression : Expression
1846 public DefaultValueExpression (Expression expr, Location loc)
1852 public override Expression DoResolve (EmitContext ec)
1854 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
1860 eclass = ExprClass.Variable;
1864 public override void Emit (EmitContext ec)
1866 if (type.IsGenericParameter || TypeManager.IsValueType (type)) {
1867 LocalTemporary temp_storage = new LocalTemporary (ec, type);
1869 temp_storage.AddressOf (ec, AddressOp.LoadStore);
1870 ec.ig.Emit (OpCodes.Initobj, type);
1871 temp_storage.Emit (ec);
1873 ec.ig.Emit (OpCodes.Ldnull);
1877 public class NullableType : TypeExpr
1879 Expression underlying;
1881 public NullableType (Expression underlying, Location l)
1883 this.underlying = underlying;
1886 eclass = ExprClass.Type;
1889 public NullableType (Type type, Location loc)
1890 : this (new TypeExpression (type, loc), loc)
1893 public override string Name {
1894 get { return underlying.ToString () + "?"; }
1897 public override string FullName {
1898 get { return underlying.ToString () + "?"; }
1901 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
1903 TypeArguments args = new TypeArguments (loc);
1904 args.Add (underlying);
1906 ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
1907 return ctype.ResolveAsTypeTerminal (ec);
1911 public partial class TypeManager
1914 // A list of core types that the compiler requires or uses
1916 static public Type activator_type;
1917 static public Type generic_ienumerator_type;
1918 static public Type generic_ienumerable_type;
1919 static public Type generic_nullable_type;
1922 // Tracks the generic parameters.
1924 static PtrHashtable builder_to_type_param;
1927 // These methods are called by code generated by the compiler
1929 static public MethodInfo activator_create_instance;
1931 static void InitGenerics ()
1933 builder_to_type_param = new PtrHashtable ();
1936 static void CleanUpGenerics ()
1938 builder_to_type_param = null;
1941 static void InitGenericCoreTypes ()
1943 activator_type = CoreLookupType ("System", "Activator");
1945 generic_ienumerator_type = CoreLookupType (
1946 "System.Collections.Generic", "IEnumerator", 1);
1947 generic_ienumerable_type = CoreLookupType (
1948 "System.Collections.Generic", "IEnumerable", 1);
1949 generic_nullable_type = CoreLookupType (
1950 "System", "Nullable", 1);
1953 static void InitGenericCodeHelpers ()
1956 Type [] type_arg = { type_type };
1957 activator_create_instance = GetMethod (
1958 activator_type, "CreateInstance", type_arg);
1961 static Type CoreLookupType (string ns, string name, int arity)
1963 return CoreLookupType (ns, MemberName.MakeName (name, arity));
1966 public static void AddTypeParameter (Type t, TypeParameter tparam)
1968 if (!builder_to_type_param.Contains (t))
1969 builder_to_type_param.Add (t, tparam);
1972 public static TypeContainer LookupGenericTypeContainer (Type t)
1974 t = DropGenericTypeArguments (t);
1975 return LookupTypeContainer (t);
1978 public static TypeParameter LookupTypeParameter (Type t)
1980 return (TypeParameter) builder_to_type_param [t];
1983 public static GenericConstraints GetTypeParameterConstraints (Type t)
1985 if (!t.IsGenericParameter)
1986 throw new InvalidOperationException ();
1988 TypeParameter tparam = LookupTypeParameter (t);
1990 return tparam.GenericConstraints;
1992 return ReflectionConstraints.GetConstraints (t);
1995 public static bool HasGenericArguments (Type t)
1997 return GetNumberOfTypeArguments (t) > 0;
2000 public static int GetNumberOfTypeArguments (Type t)
2002 if (t.IsGenericParameter)
2004 DeclSpace tc = LookupDeclSpace (t);
2006 return tc.IsGeneric ? tc.CountTypeParameters : 0;
2008 return t.IsGenericType ? t.GetGenericArguments ().Length : 0;
2011 public static Type[] GetTypeArguments (Type t)
2013 DeclSpace tc = LookupDeclSpace (t);
2016 return Type.EmptyTypes;
2018 TypeParameter[] tparam = tc.TypeParameters;
2019 Type[] ret = new Type [tparam.Length];
2020 for (int i = 0; i < tparam.Length; i++) {
2021 ret [i] = tparam [i].Type;
2022 if (ret [i] == null)
2023 throw new InternalErrorException ();
2028 return t.GetGenericArguments ();
2031 public static Type DropGenericTypeArguments (Type t)
2033 if (!t.IsGenericType)
2035 // Micro-optimization: a generic typebuilder is always a generic type definition
2036 if (t is TypeBuilder)
2038 return t.GetGenericTypeDefinition ();
2042 // Whether `array' is an array of T and `enumerator' is `IEnumerable<T>'.
2043 // For instance "string[]" -> "IEnumerable<string>".
2045 public static bool IsIEnumerable (Type array, Type enumerator)
2047 if (!array.IsArray || !enumerator.IsGenericInstance)
2050 if (enumerator.GetGenericTypeDefinition () != generic_ienumerable_type)
2053 Type[] args = GetTypeArguments (enumerator);
2054 return args [0] == GetElementType (array);
2057 public static bool IsEqual (Type a, Type b)
2062 if (a.IsGenericParameter && b.IsGenericParameter) {
2063 if (a.DeclaringMethod != b.DeclaringMethod &&
2064 (a.DeclaringMethod == null || b.DeclaringMethod == null))
2066 return a.GenericParameterPosition == b.GenericParameterPosition;
2069 if (a.IsArray && b.IsArray) {
2070 if (a.GetArrayRank () != b.GetArrayRank ())
2072 return IsEqual (a.GetElementType (), b.GetElementType ());
2075 if (a.IsGenericType && b.IsGenericType) {
2076 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2079 Type[] aargs = a.GetGenericArguments ();
2080 Type[] bargs = b.GetGenericArguments ();
2082 if (aargs.Length != bargs.Length)
2085 for (int i = 0; i < aargs.Length; i++) {
2086 if (!IsEqual (aargs [i], bargs [i]))
2094 // This is to build with the broken circular dependencies between
2095 // System and System.Configuration in the 2.x profile where we
2096 // end up with a situation where:
2098 // System on the second build is referencing the System.Configuration
2099 // that has references to the first System build.
2101 // Point in case: NameValueCollection built on the first pass, vs
2102 // NameValueCollection build on the second one. The problem is that
2103 // we need to override some methods sometimes, or we need to
2105 if (RootContext.BrokenCircularDeps){
2106 if (a.Name == b.Name && a.Namespace == b.Namespace){
2107 Console.WriteLine ("GonziMatch: {0}.{1}", a.Namespace, a.Name);
2115 /// Check whether `a' and `b' may become equal generic types.
2116 /// The algorithm to do that is a little bit complicated.
2118 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_infered,
2119 Type[] method_infered)
2121 if (a.IsGenericParameter) {
2123 // If a is an array of a's type, they may never
2127 b = b.GetElementType ();
2133 // If b is a generic parameter or an actual type,
2134 // they may become equal:
2136 // class X<T,U> : I<T>, I<U>
2137 // class X<T> : I<T>, I<float>
2139 if (b.IsGenericParameter || !b.IsGenericInstance) {
2140 int pos = a.GenericParameterPosition;
2141 Type[] args = a.DeclaringMethod != null ? method_infered : class_infered;
2142 if (args [pos] == null) {
2147 return args [pos] == a;
2151 // We're now comparing a type parameter with a
2152 // generic instance. They may become equal unless
2153 // the type parameter appears anywhere in the
2154 // generic instance:
2156 // class X<T,U> : I<T>, I<X<U>>
2157 // -> error because you could instanciate it as
2160 // class X<T> : I<T>, I<X<T>> -> ok
2163 Type[] bargs = GetTypeArguments (b);
2164 for (int i = 0; i < bargs.Length; i++) {
2165 if (a.Equals (bargs [i]))
2172 if (b.IsGenericParameter)
2173 return MayBecomeEqualGenericTypes (b, a, class_infered, method_infered);
2176 // At this point, neither a nor b are a type parameter.
2178 // If one of them is a generic instance, let
2179 // MayBecomeEqualGenericInstances() compare them (if the
2180 // other one is not a generic instance, they can never
2184 if (a.IsGenericInstance || b.IsGenericInstance)
2185 return MayBecomeEqualGenericInstances (a, b, class_infered, method_infered);
2188 // If both of them are arrays.
2191 if (a.IsArray && b.IsArray) {
2192 if (a.GetArrayRank () != b.GetArrayRank ())
2195 a = a.GetElementType ();
2196 b = b.GetElementType ();
2198 return MayBecomeEqualGenericTypes (a, b, class_infered, method_infered);
2202 // Ok, two ordinary types.
2205 return a.Equals (b);
2209 // Checks whether two generic instances may become equal for some
2210 // particular instantiation (26.3.1).
2212 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
2213 Type[] class_infered,
2214 Type[] method_infered)
2216 if (!a.IsGenericInstance || !b.IsGenericInstance)
2218 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2221 return MayBecomeEqualGenericInstances (
2222 GetTypeArguments (a), GetTypeArguments (b), class_infered, method_infered);
2225 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
2226 Type[] class_infered,
2227 Type[] method_infered)
2229 if (aargs.Length != bargs.Length)
2232 for (int i = 0; i < aargs.Length; i++) {
2233 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_infered, method_infered))
2241 /// Check whether `type' and `parent' are both instantiations of the same
2242 /// generic type. Note that we do not check the type parameters here.
2244 public static bool IsInstantiationOfSameGenericType (Type type, Type parent)
2246 int tcount = GetNumberOfTypeArguments (type);
2247 int pcount = GetNumberOfTypeArguments (parent);
2249 if (tcount != pcount)
2252 type = DropGenericTypeArguments (type);
2253 parent = DropGenericTypeArguments (parent);
2255 return type.Equals (parent);
2259 /// Whether `mb' is a generic method definition.
2261 public static bool IsGenericMethod (MethodBase mb)
2263 if (mb.DeclaringType is TypeBuilder) {
2264 IMethodData method = (IMethodData) builder_to_method [mb];
2268 return method.GenericMethod != null;
2271 return mb.IsGenericMethodDefinition;
2278 static bool InferType (Type pt, Type at, Type[] infered)
2280 if (pt.IsGenericParameter && (pt.DeclaringMethod != null)) {
2281 int pos = pt.GenericParameterPosition;
2283 if (infered [pos] == null) {
2285 while (check.IsArray)
2286 check = check.GetElementType ();
2295 if (infered [pos] != at)
2301 if (!pt.ContainsGenericParameters) {
2302 if (at.ContainsGenericParameters)
2303 return InferType (at, pt, infered);
2310 (at.GetArrayRank () != pt.GetArrayRank ()))
2313 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2318 (pt.GetArrayRank () != at.GetArrayRank ()))
2321 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2324 if (pt.IsByRef && at.IsByRef)
2325 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2326 ArrayList list = new ArrayList ();
2327 if (at.IsGenericInstance)
2329 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
2332 list.AddRange (TypeManager.GetInterfaces (at));
2334 bool found_one = false;
2336 foreach (Type type in list) {
2337 if (!type.IsGenericInstance)
2340 Type[] infered_types = new Type [infered.Length];
2342 if (!InferGenericInstance (pt, type, infered_types))
2345 for (int i = 0; i < infered_types.Length; i++) {
2346 if (infered [i] == null) {
2347 infered [i] = infered_types [i];
2351 if (infered [i] != infered_types [i])
2361 static bool InferGenericInstance (Type pt, Type at, Type[] infered_types)
2363 Type[] at_args = at.GetGenericArguments ();
2364 Type[] pt_args = pt.GetGenericArguments ();
2366 if (at_args.Length != pt_args.Length)
2369 for (int i = 0; i < at_args.Length; i++) {
2370 if (!InferType (pt_args [i], at_args [i], infered_types))
2374 for (int i = 0; i < infered_types.Length; i++) {
2375 if (infered_types [i] == null)
2383 /// Type inference. Try to infer the type arguments from the params method
2384 /// `method', which is invoked with the arguments `arguments'. This is used
2385 /// when resolving an Invocation or a DelegateInvocation and the user
2386 /// did not explicitly specify type arguments.
2388 public static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
2389 ref MethodBase method)
2391 if ((arguments == null) || !TypeManager.IsGenericMethod (method))
2396 if (arguments == null)
2399 arg_count = arguments.Count;
2401 ParameterData pd = TypeManager.GetParameterData (method);
2403 int pd_count = pd.Count;
2408 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2411 if (pd_count - 1 > arg_count)
2414 if (pd_count == 1 && arg_count == 0)
2417 Type[] method_args = method.GetGenericArguments ();
2418 Type[] infered_types = new Type [method_args.Length];
2421 // If we have come this far, the case which
2422 // remains is when the number of parameters is
2423 // less than or equal to the argument count.
2425 for (int i = 0; i < pd_count - 1; ++i) {
2426 Argument a = (Argument) arguments [i];
2428 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2431 Type pt = pd.ParameterType (i);
2434 if (!InferType (pt, at, infered_types))
2438 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
2440 for (int i = pd_count - 1; i < arg_count; i++) {
2441 Argument a = (Argument) arguments [i];
2443 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2446 if (!InferType (element_type, a.Type, infered_types))
2450 for (int i = 0; i < infered_types.Length; i++)
2451 if (infered_types [i] == null)
2454 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2458 static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
2459 Type[] infered_types)
2461 if (infered_types == null)
2464 for (int i = 0; i < arg_types.Length; i++) {
2465 if (arg_types [i] == null)
2468 if (!InferType (param_types [i], arg_types [i], infered_types))
2472 for (int i = 0; i < infered_types.Length; i++)
2473 if (infered_types [i] == null)
2480 /// Type inference. Try to infer the type arguments from `method',
2481 /// which is invoked with the arguments `arguments'. This is used
2482 /// when resolving an Invocation or a DelegateInvocation and the user
2483 /// did not explicitly specify type arguments.
2485 public static bool InferTypeArguments (EmitContext ec, ArrayList arguments,
2486 ref MethodBase method)
2488 if (!TypeManager.IsGenericMethod (method))
2492 if (arguments != null)
2493 arg_count = arguments.Count;
2497 ParameterData pd = TypeManager.GetParameterData (method);
2498 if (arg_count != pd.Count)
2501 Type[] method_args = method.GetGenericArguments ();
2503 bool is_open = false;
2504 for (int i = 0; i < method_args.Length; i++) {
2505 if (method_args [i].IsGenericParameter) {
2513 Type[] infered_types = new Type [method_args.Length];
2515 Type[] param_types = new Type [pd.Count];
2516 Type[] arg_types = new Type [pd.Count];
2518 for (int i = 0; i < arg_count; i++) {
2519 param_types [i] = pd.ParameterType (i);
2521 Argument a = (Argument) arguments [i];
2522 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr) ||
2523 (a.Expr is AnonymousMethod))
2526 arg_types [i] = a.Type;
2529 if (!InferTypeArguments (param_types, arg_types, infered_types))
2532 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2539 public static bool InferTypeArguments (EmitContext ec, ParameterData apd,
2540 ref MethodBase method)
2542 if (!TypeManager.IsGenericMethod (method))
2545 ParameterData pd = TypeManager.GetParameterData (method);
2546 if (apd.Count != pd.Count)
2549 Type[] method_args = method.GetGenericArguments ();
2550 Type[] infered_types = new Type [method_args.Length];
2552 Type[] param_types = new Type [pd.Count];
2553 Type[] arg_types = new Type [pd.Count];
2555 for (int i = 0; i < apd.Count; i++) {
2556 param_types [i] = pd.ParameterType (i);
2557 arg_types [i] = apd.ParameterType (i);
2560 if (!InferTypeArguments (param_types, arg_types, infered_types))
2563 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2567 public static bool IsNullableType (Type t)
2569 return generic_nullable_type == DropGenericTypeArguments (t);
2573 public abstract class Nullable
2575 protected sealed class NullableInfo
2577 public readonly Type Type;
2578 public readonly Type UnderlyingType;
2579 public readonly MethodInfo HasValue;
2580 public readonly MethodInfo Value;
2581 public readonly ConstructorInfo Constructor;
2583 public NullableInfo (Type type)
2586 UnderlyingType = TypeManager.GetTypeArguments (type) [0];
2588 PropertyInfo has_value_pi = TypeManager.GetProperty (type, "HasValue");
2589 PropertyInfo value_pi = TypeManager.GetProperty (type, "Value");
2591 HasValue = has_value_pi.GetGetMethod (false);
2592 Value = value_pi.GetGetMethod (false);
2593 Constructor = type.GetConstructor (new Type[] { UnderlyingType });
2597 protected class Unwrap : Expression, IMemoryLocation, IAssignMethod
2602 LocalTemporary temp;
2605 public Unwrap (Expression expr, Location loc)
2611 public override Expression DoResolve (EmitContext ec)
2613 expr = expr.Resolve (ec);
2617 if (!(expr is IMemoryLocation))
2618 temp = new LocalTemporary (ec, expr.Type);
2620 info = new NullableInfo (expr.Type);
2621 type = info.UnderlyingType;
2622 eclass = expr.eclass;
2626 public override void Emit (EmitContext ec)
2628 AddressOf (ec, AddressOp.LoadStore);
2629 ec.ig.EmitCall (OpCodes.Call, info.Value, null);
2632 public void EmitCheck (EmitContext ec)
2634 AddressOf (ec, AddressOp.LoadStore);
2635 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
2638 void create_temp (EmitContext ec)
2640 if ((temp != null) && !has_temp) {
2647 public void AddressOf (EmitContext ec, AddressOp mode)
2651 temp.AddressOf (ec, AddressOp.LoadStore);
2653 ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
2656 public void Emit (EmitContext ec, bool leave_copy)
2669 public void EmitAssign (EmitContext ec, Expression source,
2670 bool leave_copy, bool prepare_for_load)
2673 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2676 ec.ig.Emit (OpCodes.Dup);
2678 Expression empty = new EmptyExpression (expr.Type);
2679 ((IAssignMethod) expr).EmitAssign (ec, empty, false, prepare_for_load);
2683 protected class Wrap : Expression
2688 public Wrap (Expression expr, Location loc)
2694 public override Expression DoResolve (EmitContext ec)
2696 expr = expr.Resolve (ec);
2700 TypeExpr target_type = new NullableType (expr.Type, loc);
2701 target_type = target_type.ResolveAsTypeTerminal (ec);
2702 if (target_type == null)
2705 type = target_type.Type;
2706 info = new NullableInfo (type);
2707 eclass = ExprClass.Value;
2711 public override void Emit (EmitContext ec)
2714 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2718 public class NullableLiteral : Expression, IMemoryLocation {
2719 public NullableLiteral (Type target_type, Location loc)
2721 this.type = target_type;
2724 eclass = ExprClass.Value;
2727 public override Expression DoResolve (EmitContext ec)
2732 public override void Emit (EmitContext ec)
2734 LocalTemporary value_target = new LocalTemporary (ec, type);
2736 value_target.AddressOf (ec, AddressOp.Store);
2737 ec.ig.Emit (OpCodes.Initobj, type);
2738 value_target.Emit (ec);
2741 public void AddressOf (EmitContext ec, AddressOp Mode)
2743 LocalTemporary value_target = new LocalTemporary (ec, type);
2745 value_target.AddressOf (ec, AddressOp.Store);
2746 ec.ig.Emit (OpCodes.Initobj, type);
2747 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
2751 public abstract class Lifted : Expression, IMemoryLocation
2753 Expression expr, underlying, wrap, null_value;
2756 protected Lifted (Expression expr, Location loc)
2762 public override Expression DoResolve (EmitContext ec)
2764 expr = expr.Resolve (ec);
2768 unwrap = (Unwrap) new Unwrap (expr, loc).Resolve (ec);
2772 underlying = ResolveUnderlying (unwrap, ec);
2773 if (underlying == null)
2776 wrap = new Wrap (underlying, loc).Resolve (ec);
2780 null_value = new NullableLiteral (wrap.Type, loc).Resolve (ec);
2781 if (null_value == null)
2785 eclass = ExprClass.Value;
2789 protected abstract Expression ResolveUnderlying (Expression unwrap, EmitContext ec);
2791 public override void Emit (EmitContext ec)
2793 ILGenerator ig = ec.ig;
2794 Label is_null_label = ig.DefineLabel ();
2795 Label end_label = ig.DefineLabel ();
2797 unwrap.EmitCheck (ec);
2798 ig.Emit (OpCodes.Brfalse, is_null_label);
2801 ig.Emit (OpCodes.Br, end_label);
2803 ig.MarkLabel (is_null_label);
2804 null_value.Emit (ec);
2806 ig.MarkLabel (end_label);
2809 public void AddressOf (EmitContext ec, AddressOp mode)
2811 unwrap.AddressOf (ec, mode);
2815 public class LiftedConversion : Lifted
2817 public readonly bool IsUser;
2818 public readonly bool IsExplicit;
2819 public readonly Type TargetType;
2821 public LiftedConversion (Expression expr, Type target_type, bool is_user,
2822 bool is_explicit, Location loc)
2825 this.IsUser = is_user;
2826 this.IsExplicit = is_explicit;
2827 this.TargetType = target_type;
2830 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2832 Type type = TypeManager.GetTypeArguments (TargetType) [0];
2835 return Convert.UserDefinedConversion (ec, unwrap, type, loc, IsExplicit);
2838 return Convert.ExplicitConversion (ec, unwrap, type, loc);
2840 return Convert.ImplicitConversion (ec, unwrap, type, loc);
2845 public class LiftedUnaryOperator : Lifted
2847 public readonly Unary.Operator Oper;
2849 public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
2855 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2857 return new Unary (Oper, unwrap, loc);
2861 public class LiftedConditional : Lifted
2863 Expression true_expr, false_expr;
2865 public LiftedConditional (Expression expr, Expression true_expr, Expression false_expr,
2869 this.true_expr = true_expr;
2870 this.false_expr = false_expr;
2873 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2875 return new Conditional (unwrap, true_expr, false_expr);
2879 public class LiftedBinaryOperator : Expression
2881 public readonly Binary.Operator Oper;
2883 Expression left, right, underlying, null_value, bool_wrap;
2884 Unwrap left_unwrap, right_unwrap;
2885 bool is_equality, is_comparision, is_boolean;
2887 public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
2896 public override Expression DoResolve (EmitContext ec)
2898 if (TypeManager.IsNullableType (left.Type)) {
2899 left_unwrap = new Unwrap (left, loc);
2900 left = left_unwrap.Resolve (ec);
2905 if (TypeManager.IsNullableType (right.Type)) {
2906 right_unwrap = new Unwrap (right, loc);
2907 right = right_unwrap.Resolve (ec);
2912 if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr) ||
2913 (Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr)) &&
2914 ((left.Type == TypeManager.bool_type) && (right.Type == TypeManager.bool_type))) {
2915 Expression empty = new EmptyExpression (TypeManager.bool_type);
2916 bool_wrap = new Wrap (empty, loc).Resolve (ec);
2917 null_value = new NullableLiteral (bool_wrap.Type, loc).Resolve (ec);
2919 type = bool_wrap.Type;
2921 } else if ((Oper == Binary.Operator.Equality) || (Oper == Binary.Operator.Inequality)) {
2922 if (!(left is NullLiteral) && !(right is NullLiteral)) {
2923 underlying = new Binary (Oper, left, right).Resolve (ec);
2924 if (underlying == null)
2928 type = TypeManager.bool_type;
2930 } else if ((Oper == Binary.Operator.LessThan) ||
2931 (Oper == Binary.Operator.GreaterThan) ||
2932 (Oper == Binary.Operator.LessThanOrEqual) ||
2933 (Oper == Binary.Operator.GreaterThanOrEqual)) {
2934 underlying = new Binary (Oper, left, right).Resolve (ec);
2935 if (underlying == null)
2938 type = TypeManager.bool_type;
2939 is_comparision = true;
2941 underlying = new Binary (Oper, left, right).Resolve (ec);
2942 if (underlying == null)
2945 underlying = new Wrap (underlying, loc).Resolve (ec);
2946 if (underlying == null)
2949 type = underlying.Type;
2950 null_value = new NullableLiteral (type, loc).Resolve (ec);
2953 eclass = ExprClass.Value;
2957 void EmitBoolean (EmitContext ec)
2959 ILGenerator ig = ec.ig;
2961 Label left_is_null_label = ig.DefineLabel ();
2962 Label right_is_null_label = ig.DefineLabel ();
2963 Label is_null_label = ig.DefineLabel ();
2964 Label wrap_label = ig.DefineLabel ();
2965 Label end_label = ig.DefineLabel ();
2967 if (left_unwrap != null) {
2968 left_unwrap.EmitCheck (ec);
2969 ig.Emit (OpCodes.Brfalse, left_is_null_label);
2973 ig.Emit (OpCodes.Dup);
2974 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
2975 ig.Emit (OpCodes.Brtrue, wrap_label);
2977 ig.Emit (OpCodes.Brfalse, wrap_label);
2979 if (right_unwrap != null) {
2980 right_unwrap.EmitCheck (ec);
2981 ig.Emit (OpCodes.Brfalse, right_is_null_label);
2984 if ((Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr))
2985 ig.Emit (OpCodes.Pop);
2988 if (Oper == Binary.Operator.BitwiseOr)
2989 ig.Emit (OpCodes.Or);
2990 else if (Oper == Binary.Operator.BitwiseAnd)
2991 ig.Emit (OpCodes.And);
2992 ig.Emit (OpCodes.Br, wrap_label);
2994 ig.MarkLabel (left_is_null_label);
2995 if (right_unwrap != null) {
2996 right_unwrap.EmitCheck (ec);
2997 ig.Emit (OpCodes.Brfalse, is_null_label);
3001 ig.Emit (OpCodes.Dup);
3002 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3003 ig.Emit (OpCodes.Brtrue, wrap_label);
3005 ig.Emit (OpCodes.Brfalse, wrap_label);
3007 ig.MarkLabel (right_is_null_label);
3008 ig.Emit (OpCodes.Pop);
3009 ig.MarkLabel (is_null_label);
3010 null_value.Emit (ec);
3011 ig.Emit (OpCodes.Br, end_label);
3013 ig.MarkLabel (wrap_label);
3014 ig.Emit (OpCodes.Nop);
3015 bool_wrap.Emit (ec);
3016 ig.Emit (OpCodes.Nop);
3018 ig.MarkLabel (end_label);
3021 void EmitEquality (EmitContext ec)
3023 ILGenerator ig = ec.ig;
3025 Label left_not_null_label = ig.DefineLabel ();
3026 Label false_label = ig.DefineLabel ();
3027 Label true_label = ig.DefineLabel ();
3028 Label end_label = ig.DefineLabel ();
3030 bool false_label_used = false;
3031 bool true_label_used = false;
3033 if (left_unwrap != null) {
3034 left_unwrap.EmitCheck (ec);
3035 if (right is NullLiteral) {
3036 if (Oper == Binary.Operator.Equality) {
3037 true_label_used = true;
3038 ig.Emit (OpCodes.Brfalse, true_label);
3040 false_label_used = true;
3041 ig.Emit (OpCodes.Brfalse, false_label);
3043 } else if (right_unwrap != null) {
3044 ig.Emit (OpCodes.Dup);
3045 ig.Emit (OpCodes.Brtrue, left_not_null_label);
3046 right_unwrap.EmitCheck (ec);
3047 ig.Emit (OpCodes.Ceq);
3048 if (Oper == Binary.Operator.Inequality) {
3049 ig.Emit (OpCodes.Ldc_I4_0);
3050 ig.Emit (OpCodes.Ceq);
3052 ig.Emit (OpCodes.Br, end_label);
3054 ig.MarkLabel (left_not_null_label);
3055 ig.Emit (OpCodes.Pop);
3057 if (Oper == Binary.Operator.Equality) {
3058 false_label_used = true;
3059 ig.Emit (OpCodes.Brfalse, false_label);
3061 true_label_used = true;
3062 ig.Emit (OpCodes.Brfalse, true_label);
3067 if (right_unwrap != null) {
3068 right_unwrap.EmitCheck (ec);
3069 if (left is NullLiteral) {
3070 if (Oper == Binary.Operator.Equality) {
3071 true_label_used = true;
3072 ig.Emit (OpCodes.Brfalse, true_label);
3074 false_label_used = true;
3075 ig.Emit (OpCodes.Brfalse, false_label);
3078 if (Oper == Binary.Operator.Equality) {
3079 false_label_used = true;
3080 ig.Emit (OpCodes.Brfalse, false_label);
3082 true_label_used = true;
3083 ig.Emit (OpCodes.Brfalse, true_label);
3088 bool left_is_null = left is NullLiteral;
3089 bool right_is_null = right is NullLiteral;
3090 if (left_is_null || right_is_null) {
3091 if (((Oper == Binary.Operator.Equality) && (left_is_null == right_is_null)) ||
3092 ((Oper == Binary.Operator.Inequality) && (left_is_null != right_is_null))) {
3093 true_label_used = true;
3094 ig.Emit (OpCodes.Br, true_label);
3096 false_label_used = true;
3097 ig.Emit (OpCodes.Br, false_label);
3100 underlying.Emit (ec);
3101 ig.Emit (OpCodes.Br, end_label);
3104 ig.MarkLabel (false_label);
3105 if (false_label_used) {
3106 ig.Emit (OpCodes.Ldc_I4_0);
3107 if (true_label_used)
3108 ig.Emit (OpCodes.Br, end_label);
3111 ig.MarkLabel (true_label);
3112 if (true_label_used)
3113 ig.Emit (OpCodes.Ldc_I4_1);
3115 ig.MarkLabel (end_label);
3118 void EmitComparision (EmitContext ec)
3120 ILGenerator ig = ec.ig;
3122 Label is_null_label = ig.DefineLabel ();
3123 Label end_label = ig.DefineLabel ();
3125 if (left_unwrap != null) {
3126 left_unwrap.EmitCheck (ec);
3127 ig.Emit (OpCodes.Brfalse, is_null_label);
3130 if (right_unwrap != null) {
3131 right_unwrap.EmitCheck (ec);
3132 ig.Emit (OpCodes.Brfalse, is_null_label);
3135 underlying.Emit (ec);
3136 ig.Emit (OpCodes.Br, end_label);
3138 ig.MarkLabel (is_null_label);
3139 ig.Emit (OpCodes.Ldc_I4_0);
3141 ig.MarkLabel (end_label);
3144 public override void Emit (EmitContext ec)
3149 } else if (is_equality) {
3152 } else if (is_comparision) {
3153 EmitComparision (ec);
3157 ILGenerator ig = ec.ig;
3159 Label is_null_label = ig.DefineLabel ();
3160 Label end_label = ig.DefineLabel ();
3162 if (left_unwrap != null) {
3163 left_unwrap.EmitCheck (ec);
3164 ig.Emit (OpCodes.Brfalse, is_null_label);
3167 if (right_unwrap != null) {
3168 right_unwrap.EmitCheck (ec);
3169 ig.Emit (OpCodes.Brfalse, is_null_label);
3172 underlying.Emit (ec);
3173 ig.Emit (OpCodes.Br, end_label);
3175 ig.MarkLabel (is_null_label);
3176 null_value.Emit (ec);
3178 ig.MarkLabel (end_label);
3182 public class OperatorTrueOrFalse : Expression
3184 public readonly bool IsTrue;
3189 public OperatorTrueOrFalse (Expression expr, bool is_true, Location loc)
3191 this.IsTrue = is_true;
3196 public override Expression DoResolve (EmitContext ec)
3198 unwrap = new Unwrap (expr, loc);
3199 expr = unwrap.Resolve (ec);
3203 if (unwrap.Type != TypeManager.bool_type)
3206 type = TypeManager.bool_type;
3207 eclass = ExprClass.Value;
3211 public override void Emit (EmitContext ec)
3213 ILGenerator ig = ec.ig;
3215 Label is_null_label = ig.DefineLabel ();
3216 Label end_label = ig.DefineLabel ();
3218 unwrap.EmitCheck (ec);
3219 ig.Emit (OpCodes.Brfalse, is_null_label);
3223 ig.Emit (OpCodes.Ldc_I4_0);
3224 ig.Emit (OpCodes.Ceq);
3226 ig.Emit (OpCodes.Br, end_label);
3228 ig.MarkLabel (is_null_label);
3229 ig.Emit (OpCodes.Ldc_I4_0);
3231 ig.MarkLabel (end_label);
3235 public class NullCoalescingOperator : Expression
3237 Expression left, right;
3241 public NullCoalescingOperator (Expression left, Expression right, Location loc)
3247 eclass = ExprClass.Value;
3250 public override Expression DoResolve (EmitContext ec)
3255 left = left.Resolve (ec);
3259 right = right.Resolve (ec);
3263 Type ltype = left.Type, rtype = right.Type;
3265 if (!TypeManager.IsNullableType (ltype) && ltype.IsValueType) {
3266 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3270 if (TypeManager.IsNullableType (ltype)) {
3271 NullableInfo info = new NullableInfo (ltype);
3273 unwrap = (Unwrap) new Unwrap (left, loc).Resolve (ec);
3277 expr = Convert.ImplicitConversion (ec, right, info.UnderlyingType, loc);
3285 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
3291 if (unwrap != null) {
3292 expr = Convert.ImplicitConversion (ec, unwrap, rtype, loc);
3301 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3305 public override void Emit (EmitContext ec)
3307 ILGenerator ig = ec.ig;
3309 Label is_null_label = ig.DefineLabel ();
3310 Label end_label = ig.DefineLabel ();
3312 if (unwrap != null) {
3313 unwrap.EmitCheck (ec);
3314 ig.Emit (OpCodes.Brfalse, is_null_label);
3317 ig.Emit (OpCodes.Br, end_label);
3319 ig.MarkLabel (is_null_label);
3322 ig.MarkLabel (end_label);
3325 ig.Emit (OpCodes.Dup);
3326 ig.Emit (OpCodes.Brtrue, end_label);
3328 ig.MarkLabel (is_null_label);
3330 ig.Emit (OpCodes.Pop);
3333 ig.MarkLabel (end_label);
3338 public class LiftedUnaryMutator : ExpressionStatement
3340 public readonly UnaryMutator.Mode Mode;
3341 Expression expr, null_value;
3342 UnaryMutator underlying;
3345 public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
3351 eclass = ExprClass.Value;
3354 public override Expression DoResolve (EmitContext ec)
3356 expr = expr.Resolve (ec);
3360 unwrap = (Unwrap) new Unwrap (expr, loc).Resolve (ec);
3364 underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
3365 if (underlying == null)
3368 null_value = new NullableLiteral (expr.Type, loc).Resolve (ec);
3369 if (null_value == null)
3376 void DoEmit (EmitContext ec, bool is_expr)
3378 ILGenerator ig = ec.ig;
3379 Label is_null_label = ig.DefineLabel ();
3380 Label end_label = ig.DefineLabel ();
3382 unwrap.EmitCheck (ec);
3383 ig.Emit (OpCodes.Brfalse, is_null_label);
3386 underlying.Emit (ec);
3388 underlying.EmitStatement (ec);
3389 ig.Emit (OpCodes.Br, end_label);
3391 ig.MarkLabel (is_null_label);
3393 null_value.Emit (ec);
3395 ig.MarkLabel (end_label);
3398 public override void Emit (EmitContext ec)
3403 public override void EmitStatement (EmitContext ec)