2 // generic.cs: Generics support
4 // Authors: Martin Baulig (martin@ximian.com)
5 // Miguel de Icaza (miguel@ximian.com)
7 // Licensed under the terms of the GNU GPL
9 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
10 // (C) 2004 Novell, Inc
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.Globalization;
16 using System.Collections;
18 using System.Text.RegularExpressions;
20 namespace Mono.CSharp {
23 /// Abstract base class for type parameter constraints.
24 /// The type parameter can come from a generic type definition or from reflection.
26 public abstract class GenericConstraints {
27 public abstract string TypeParameter {
31 public abstract GenericParameterAttributes Attributes {
35 public bool HasConstructorConstraint {
36 get { return (Attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0; }
39 public bool HasReferenceTypeConstraint {
40 get { return (Attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0; }
43 public bool HasValueTypeConstraint {
44 get { return (Attributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0; }
47 public virtual bool HasClassConstraint {
48 get { return ClassConstraint != null; }
51 public abstract Type ClassConstraint {
55 public abstract Type[] InterfaceConstraints {
59 public abstract Type EffectiveBaseClass {
64 // Returns whether the type parameter is "known to be a reference type".
66 public virtual bool IsReferenceType {
68 if (HasReferenceTypeConstraint)
70 if (HasValueTypeConstraint)
73 if (ClassConstraint != null) {
74 if (ClassConstraint.IsValueType)
77 if (ClassConstraint != TypeManager.object_type)
81 foreach (Type t in InterfaceConstraints) {
82 if (!t.IsGenericParameter)
85 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
86 if ((gc != null) && gc.IsReferenceType)
95 // Returns whether the type parameter is "known to be a value type".
97 public virtual bool IsValueType {
99 if (HasValueTypeConstraint)
101 if (HasReferenceTypeConstraint)
104 if (ClassConstraint != null) {
105 if (!ClassConstraint.IsValueType)
108 if (ClassConstraint != TypeManager.value_type)
112 foreach (Type t in InterfaceConstraints) {
113 if (!t.IsGenericParameter)
116 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
117 if ((gc != null) && gc.IsValueType)
126 public enum SpecialConstraint
134 /// Tracks the constraints for a type parameter from a generic type definition.
136 public class Constraints : GenericConstraints {
138 ArrayList constraints;
142 // name is the identifier, constraints is an arraylist of
143 // Expressions (with types) or `true' for the constructor constraint.
145 public Constraints (string name, ArrayList constraints,
149 this.constraints = constraints;
153 public override string TypeParameter {
159 GenericParameterAttributes attrs;
160 TypeExpr class_constraint;
161 ArrayList iface_constraints;
162 ArrayList type_param_constraints;
164 Type class_constraint_type;
165 Type[] iface_constraint_types;
166 Type effective_base_type;
171 /// Resolve the constraints - but only resolve things into Expression's, not
172 /// into actual types.
174 public bool Resolve (IResolveContext ec)
179 iface_constraints = new ArrayList ();
180 type_param_constraints = new ArrayList ();
182 foreach (object obj in constraints) {
183 if (HasConstructorConstraint) {
184 Report.Error (401, loc,
185 "The new() constraint must be the last constraint specified");
189 if (obj is SpecialConstraint) {
190 SpecialConstraint sc = (SpecialConstraint) obj;
192 if (sc == SpecialConstraint.Constructor) {
193 if (!HasValueTypeConstraint) {
194 attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
198 Report.Error (451, loc, "The `new()' constraint " +
199 "cannot be used with the `struct' constraint");
203 if ((num_constraints > 0) || HasReferenceTypeConstraint || HasValueTypeConstraint) {
204 Report.Error (449, loc, "The `class' or `struct' " +
205 "constraint must be the first constraint specified");
209 if (sc == SpecialConstraint.ReferenceType)
210 attrs |= GenericParameterAttributes.ReferenceTypeConstraint;
212 attrs |= GenericParameterAttributes.NotNullableValueTypeConstraint;
216 int errors = Report.Errors;
217 FullNamedExpression fn = ((Expression) obj).ResolveAsTypeStep (ec, false);
220 if (errors != Report.Errors)
223 NamespaceEntry.Error_NamespaceNotFound (loc, ((Expression)obj).GetSignatureForError ());
228 ConstructedType cexpr = fn as ConstructedType;
230 if (!cexpr.ResolveConstructedType (ec))
235 expr = ((Expression) obj).ResolveAsTypeTerminal (ec, false);
237 if ((expr == null) || (expr.Type == null))
240 // TODO: It's aleady done in ResolveAsBaseTerminal
241 if (!ec.GenericDeclContainer.AsAccessible (fn.Type, ec.GenericDeclContainer.ModFlags)) {
242 Report.SymbolRelatedToPreviousError (fn.Type);
243 Report.Error (703, loc,
244 "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
245 fn.GetSignatureForError (), ec.GenericDeclContainer.GetSignatureForError ());
249 TypeParameterExpr texpr = expr as TypeParameterExpr;
251 type_param_constraints.Add (expr);
252 else if (expr.IsInterface)
253 iface_constraints.Add (expr);
254 else if (class_constraint != null) {
255 Report.Error (406, loc,
256 "`{0}': the class constraint for `{1}' " +
257 "must come before any other constraints.",
260 } else if (HasReferenceTypeConstraint || HasValueTypeConstraint) {
261 Report.Error (450, loc, "`{0}': cannot specify both " +
262 "a constraint class and the `class' " +
263 "or `struct' constraint", expr.GetSignatureForError ());
266 class_constraint = expr;
271 ArrayList list = new ArrayList ();
272 foreach (TypeExpr iface_constraint in iface_constraints) {
273 foreach (Type type in list) {
274 if (!type.Equals (iface_constraint.Type))
277 Report.Error (405, loc,
278 "Duplicate constraint `{0}' for type " +
279 "parameter `{1}'.", iface_constraint.GetSignatureForError (),
284 list.Add (iface_constraint.Type);
287 foreach (TypeParameterExpr expr in type_param_constraints) {
288 foreach (Type type in list) {
289 if (!type.Equals (expr.Type))
292 Report.Error (405, loc,
293 "Duplicate constraint `{0}' for type " +
294 "parameter `{1}'.", expr.GetSignatureForError (), name);
298 list.Add (expr.Type);
301 iface_constraint_types = new Type [list.Count];
302 list.CopyTo (iface_constraint_types, 0);
304 if (class_constraint != null) {
305 class_constraint_type = class_constraint.Type;
306 if (class_constraint_type == null)
309 if (class_constraint_type.IsSealed) {
310 if (class_constraint_type.IsAbstract)
312 Report.Error (717, loc, "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
313 TypeManager.CSharpName (class_constraint_type));
317 Report.Error (701, loc, "`{0}' is not a valid constraint. A constraint must be an interface, " +
318 "a non-sealed class or a type parameter", TypeManager.CSharpName(class_constraint_type));
323 if ((class_constraint_type == TypeManager.array_type) ||
324 (class_constraint_type == TypeManager.delegate_type) ||
325 (class_constraint_type == TypeManager.enum_type) ||
326 (class_constraint_type == TypeManager.value_type) ||
327 (class_constraint_type == TypeManager.object_type)) {
328 Report.Error (702, loc,
329 "Bound cannot be special class `{0}'",
330 TypeManager.CSharpName (class_constraint_type));
335 if (class_constraint_type != null)
336 effective_base_type = class_constraint_type;
337 else if (HasValueTypeConstraint)
338 effective_base_type = TypeManager.value_type;
340 effective_base_type = TypeManager.object_type;
346 bool CheckTypeParameterConstraints (TypeParameter tparam, Hashtable seen)
348 seen.Add (tparam, true);
350 Constraints constraints = tparam.Constraints;
351 if (constraints == null)
354 if (constraints.HasValueTypeConstraint) {
355 Report.Error (456, loc, "Type parameter `{0}' has " +
356 "the `struct' constraint, so it cannot " +
357 "be used as a constraint for `{1}'",
362 if (constraints.type_param_constraints == null)
365 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
366 if (seen.Contains (expr.TypeParameter)) {
367 Report.Error (454, loc, "Circular constraint " +
368 "dependency involving `{0}' and `{1}'",
369 tparam.Name, expr.Name);
373 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
381 /// Resolve the constraints into actual types.
383 public bool ResolveTypes (IResolveContext ec)
388 resolved_types = true;
390 foreach (object obj in constraints) {
391 ConstructedType cexpr = obj as ConstructedType;
395 if (!cexpr.CheckConstraints (ec))
399 foreach (TypeParameterExpr expr in type_param_constraints) {
400 Hashtable seen = new Hashtable ();
401 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
405 for (int i = 0; i < iface_constraints.Count; ++i) {
406 TypeExpr iface_constraint = (TypeExpr) iface_constraints [i];
407 iface_constraint = iface_constraint.ResolveAsTypeTerminal (ec, false);
408 if (iface_constraint == null)
410 iface_constraints [i] = iface_constraint;
413 if (class_constraint != null) {
414 class_constraint = class_constraint.ResolveAsTypeTerminal (ec, false);
415 if (class_constraint == null)
423 /// Check whether there are no conflicts in our type parameter constraints.
425 /// This is an example:
429 /// where U : T, struct
431 public bool CheckDependencies ()
433 foreach (TypeParameterExpr expr in type_param_constraints) {
434 if (!CheckDependencies (expr.TypeParameter))
441 bool CheckDependencies (TypeParameter tparam)
443 Constraints constraints = tparam.Constraints;
444 if (constraints == null)
447 if (HasValueTypeConstraint && constraints.HasClassConstraint) {
448 Report.Error (455, loc, "Type parameter `{0}' inherits " +
449 "conflicting constraints `{1}' and `{2}'",
450 name, TypeManager.CSharpName (constraints.ClassConstraint),
455 if (HasClassConstraint && constraints.HasClassConstraint) {
456 Type t1 = ClassConstraint;
457 TypeExpr e1 = class_constraint;
458 Type t2 = constraints.ClassConstraint;
459 TypeExpr e2 = constraints.class_constraint;
461 if (!Convert.ImplicitReferenceConversionExists (e1, t2) &&
462 !Convert.ImplicitReferenceConversionExists (e2, t1)) {
463 Report.Error (455, loc,
464 "Type parameter `{0}' inherits " +
465 "conflicting constraints `{1}' and `{2}'",
466 name, TypeManager.CSharpName (t1), TypeManager.CSharpName (t2));
471 if (constraints.type_param_constraints == null)
474 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
475 if (!CheckDependencies (expr.TypeParameter))
482 public override GenericParameterAttributes Attributes {
483 get { return attrs; }
486 public override bool HasClassConstraint {
487 get { return class_constraint != null; }
490 public override Type ClassConstraint {
491 get { return class_constraint_type; }
494 public override Type[] InterfaceConstraints {
495 get { return iface_constraint_types; }
498 public override Type EffectiveBaseClass {
499 get { return effective_base_type; }
502 public bool IsSubclassOf (Type t)
504 if ((class_constraint_type != null) &&
505 class_constraint_type.IsSubclassOf (t))
508 if (iface_constraint_types == null)
511 foreach (Type iface in iface_constraint_types) {
512 if (TypeManager.IsSubclassOf (iface, t))
519 public Location Location {
526 /// This is used when we're implementing a generic interface method.
527 /// Each method type parameter in implementing method must have the same
528 /// constraints than the corresponding type parameter in the interface
529 /// method. To do that, we're called on each of the implementing method's
532 public bool CheckInterfaceMethod (GenericConstraints gc)
534 if (gc.Attributes != attrs)
537 if (HasClassConstraint != gc.HasClassConstraint)
539 if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
542 int gc_icount = gc.InterfaceConstraints != null ?
543 gc.InterfaceConstraints.Length : 0;
544 int icount = InterfaceConstraints != null ?
545 InterfaceConstraints.Length : 0;
547 if (gc_icount != icount)
550 foreach (Type iface in gc.InterfaceConstraints) {
552 foreach (Type check in InterfaceConstraints) {
553 if (TypeManager.IsEqual (iface, check)) {
566 public void VerifyClsCompliance ()
568 if (class_constraint_type != null && !AttributeTester.IsClsCompliant (class_constraint_type))
569 Warning_ConstrainIsNotClsCompliant (class_constraint_type, class_constraint.Location);
571 if (iface_constraint_types != null) {
572 for (int i = 0; i < iface_constraint_types.Length; ++i) {
573 if (!AttributeTester.IsClsCompliant (iface_constraint_types [i]))
574 Warning_ConstrainIsNotClsCompliant (iface_constraint_types [i],
575 ((TypeExpr)iface_constraints [i]).Location);
580 void Warning_ConstrainIsNotClsCompliant (Type t, Location loc)
582 Report.SymbolRelatedToPreviousError (t);
583 Report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
584 TypeManager.CSharpName (t));
589 /// A type parameter from a generic type definition.
591 public class TypeParameter : MemberCore, IMemberContainer {
594 GenericConstraints gc;
595 Constraints constraints;
597 GenericTypeParameterBuilder type;
599 public TypeParameter (DeclSpace parent, DeclSpace decl, string name,
600 Constraints constraints, Attributes attrs, Location loc)
601 : base (parent, new MemberName (name, loc), attrs)
605 this.constraints = constraints;
609 public GenericConstraints GenericConstraints {
610 get { return gc != null ? gc : constraints; }
613 public Constraints Constraints {
614 get { return constraints; }
617 public bool HasConstructorConstraint {
618 get { return constraints != null && constraints.HasConstructorConstraint; }
621 public DeclSpace DeclSpace {
630 /// This is the first method which is called during the resolving
631 /// process; we're called immediately after creating the type parameters
632 /// with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
635 /// We're either called from TypeContainer.DefineType() or from
636 /// GenericMethod.Define() (called from Method.Define()).
638 public void Define (GenericTypeParameterBuilder type)
640 if (this.type != null)
641 throw new InvalidOperationException ();
644 TypeManager.AddTypeParameter (type, this);
648 /// This is the second method which is called during the resolving
649 /// process - in case of class type parameters, we're called from
650 /// TypeContainer.ResolveType() - after it resolved the class'es
651 /// base class and interfaces. For method type parameters, we're
652 /// called immediately after Define().
654 /// We're just resolving the constraints into expressions here, we
655 /// don't resolve them into actual types.
657 /// Note that in the special case of partial generic classes, we may be
658 /// called _before_ Define() and we may also be called multiple types.
660 public bool Resolve (DeclSpace ds)
662 if (constraints != null) {
663 if (!constraints.Resolve (ds)) {
673 /// This is the third method which is called during the resolving
674 /// process. We're called immediately after calling DefineConstraints()
675 /// on all of the current class'es type parameters.
677 /// Our job is to resolve the constraints to actual types.
679 /// Note that we may have circular dependencies on type parameters - this
680 /// is why Resolve() and ResolveType() are separate.
682 public bool ResolveType (IResolveContext ec)
684 if (constraints != null) {
685 if (!constraints.ResolveTypes (ec)) {
695 /// This is the fourth and last method which is called during the resolving
696 /// process. We're called after everything is fully resolved and actually
697 /// register the constraints with SRE and the TypeManager.
699 public bool DefineType (IResolveContext ec)
701 return DefineType (ec, null, null, false);
705 /// This is the fith and last method which is called during the resolving
706 /// process. We're called after everything is fully resolved and actually
707 /// register the constraints with SRE and the TypeManager.
709 /// The `builder', `implementing' and `is_override' arguments are only
710 /// applicable to method type parameters.
712 public bool DefineType (IResolveContext ec, MethodBuilder builder,
713 MethodInfo implementing, bool is_override)
715 if (!ResolveType (ec))
718 if (implementing != null) {
719 if (is_override && (constraints != null)) {
720 Report.Error (460, loc,
721 "`{0}': Cannot specify constraints for overrides or explicit interface implementation methods",
722 TypeManager.CSharpSignature (builder));
726 MethodBase mb = TypeManager.DropGenericMethodArguments (implementing);
728 int pos = type.GenericParameterPosition;
729 Type mparam = mb.GetGenericArguments () [pos];
730 GenericConstraints temp_gc = ReflectionConstraints.GetConstraints (mparam);
733 gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
734 else if (constraints != null)
735 gc = new InflatedConstraints (constraints, implementing.DeclaringType);
738 if (constraints != null) {
741 else if (!constraints.CheckInterfaceMethod (gc))
744 if (!is_override && (temp_gc != null))
749 Report.SymbolRelatedToPreviousError (implementing);
752 425, loc, "The constraints for type " +
753 "parameter `{0}' of method `{1}' must match " +
754 "the constraints for type parameter `{2}' " +
755 "of interface method `{3}'. Consider using " +
756 "an explicit interface implementation instead",
757 Name, TypeManager.CSharpSignature (builder),
758 TypeManager.CSharpName (mparam), TypeManager.CSharpSignature (mb));
761 } else if (DeclSpace is Iterator) {
762 TypeParameter[] tparams = DeclSpace.TypeParameters;
763 Type[] types = new Type [tparams.Length];
764 for (int i = 0; i < tparams.Length; i++)
765 types [i] = tparams [i].Type;
767 if (constraints != null)
768 gc = new InflatedConstraints (constraints, types);
770 gc = (GenericConstraints) constraints;
776 if (gc.HasClassConstraint)
777 type.SetBaseTypeConstraint (gc.ClassConstraint);
779 type.SetInterfaceConstraints (gc.InterfaceConstraints);
780 type.SetGenericParameterAttributes (gc.Attributes);
781 TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
787 /// Check whether there are no conflicts in our type parameter constraints.
789 /// This is an example:
793 /// where U : T, struct
795 public bool CheckDependencies ()
797 if (constraints != null)
798 return constraints.CheckDependencies ();
804 /// This is called for each part of a partial generic type definition.
806 /// If `new_constraints' is not null and we don't already have constraints,
807 /// they become our constraints. If we already have constraints, we must
808 /// check that they're the same.
811 public bool UpdateConstraints (IResolveContext ec, Constraints new_constraints)
814 throw new InvalidOperationException ();
816 if (new_constraints == null)
819 if (!new_constraints.Resolve (ec))
821 if (!new_constraints.ResolveTypes (ec))
824 if (constraints != null)
825 return constraints.CheckInterfaceMethod (new_constraints);
827 constraints = new_constraints;
831 public void EmitAttributes ()
833 if (OptAttributes != null)
834 OptAttributes.Emit ();
837 public override string DocCommentHeader {
839 throw new InvalidOperationException (
840 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
848 public override bool Define ()
853 public override void ApplyAttributeBuilder (Attribute a,
854 CustomAttributeBuilder cb)
856 type.SetCustomAttribute (cb);
859 public override AttributeTargets AttributeTargets {
861 return (AttributeTargets) AttributeTargets.GenericParameter;
865 public override string[] ValidAttributeTargets {
867 return new string [] { "type parameter" };
875 string IMemberContainer.Name {
879 MemberCache IMemberContainer.BaseCache {
883 bool IMemberContainer.IsInterface {
887 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
889 return FindMembers (mt, bf, null, null);
892 MemberCache IMemberContainer.MemberCache {
896 public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
897 MemberFilter filter, object criteria)
899 if (constraints == null)
900 return MemberList.Empty;
902 ArrayList members = new ArrayList ();
904 if (gc.HasClassConstraint) {
905 MemberList list = TypeManager.FindMembers (
906 gc.ClassConstraint, mt, bf, filter, criteria);
908 members.AddRange (list);
911 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
912 foreach (Type t in ifaces) {
913 MemberList list = TypeManager.FindMembers (
914 t, mt, bf, filter, criteria);
916 members.AddRange (list);
919 return new MemberList (members);
922 public bool IsSubclassOf (Type t)
927 if (constraints != null)
928 return constraints.IsSubclassOf (t);
933 public override string ToString ()
935 return "TypeParameter[" + name + "]";
938 public static string GetSignatureForError (TypeParameter[] tp)
940 if (tp == null || tp.Length == 0)
943 StringBuilder sb = new StringBuilder ("<");
944 for (int i = 0; i < tp.Length; ++i) {
947 sb.Append (tp[i].GetSignatureForError ());
950 return sb.ToString ();
953 public void InflateConstraints (Type declaring)
955 if (constraints != null)
956 gc = new InflatedConstraints (constraints, declaring);
959 protected class InflatedConstraints : GenericConstraints
961 GenericConstraints gc;
963 Type class_constraint;
964 Type[] iface_constraints;
967 public InflatedConstraints (GenericConstraints gc, Type declaring)
968 : this (gc, TypeManager.GetTypeArguments (declaring))
971 public InflatedConstraints (GenericConstraints gc, Type[] dargs)
976 ArrayList list = new ArrayList ();
977 if (gc.HasClassConstraint)
978 list.Add (inflate (gc.ClassConstraint));
979 foreach (Type iface in gc.InterfaceConstraints)
980 list.Add (inflate (iface));
982 bool has_class_constr = false;
983 if (list.Count > 0) {
984 Type first = (Type) list [0];
985 has_class_constr = !first.IsInterface && !first.IsGenericParameter;
988 if ((list.Count > 0) && has_class_constr) {
989 class_constraint = (Type) list [0];
990 iface_constraints = new Type [list.Count - 1];
991 list.CopyTo (1, iface_constraints, 0, list.Count - 1);
993 iface_constraints = new Type [list.Count];
994 list.CopyTo (iface_constraints, 0);
997 if (HasValueTypeConstraint)
998 base_type = TypeManager.value_type;
999 else if (class_constraint != null)
1000 base_type = class_constraint;
1002 base_type = TypeManager.object_type;
1005 Type inflate (Type t)
1009 if (t.IsGenericParameter)
1010 return dargs [t.GenericParameterPosition];
1011 if (t.IsGenericType) {
1012 Type[] args = t.GetGenericArguments ();
1013 Type[] inflated = new Type [args.Length];
1015 for (int i = 0; i < args.Length; i++)
1016 inflated [i] = inflate (args [i]);
1018 t = t.GetGenericTypeDefinition ();
1019 t = t.MakeGenericType (inflated);
1025 public override string TypeParameter {
1026 get { return gc.TypeParameter; }
1029 public override GenericParameterAttributes Attributes {
1030 get { return gc.Attributes; }
1033 public override Type ClassConstraint {
1034 get { return class_constraint; }
1037 public override Type EffectiveBaseClass {
1038 get { return base_type; }
1041 public override Type[] InterfaceConstraints {
1042 get { return iface_constraints; }
1048 /// A TypeExpr which already resolved to a type parameter.
1050 public class TypeParameterExpr : TypeExpr {
1051 TypeParameter type_parameter;
1053 public override string Name {
1055 return type_parameter.Name;
1059 public override string FullName {
1061 return type_parameter.Name;
1065 public TypeParameter TypeParameter {
1067 return type_parameter;
1071 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1073 this.type_parameter = type_parameter;
1077 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1079 type = type_parameter.Type;
1084 public override bool IsInterface {
1085 get { return false; }
1088 public override bool CheckAccessLevel (DeclSpace ds)
1093 public void Error_CannotUseAsUnmanagedType (Location loc)
1095 Report.Error (-203, loc, "Can not use type parameter as unmanaged type");
1100 /// Tracks the type arguments when instantiating a generic type. We're used in
1101 /// ConstructedType.
1103 public class TypeArguments {
1104 public readonly Location Location;
1111 public TypeArguments (Location loc)
1113 args = new ArrayList ();
1114 this.Location = loc;
1117 public TypeArguments (int dimension, Location loc)
1119 this.dimension = dimension;
1120 this.Location = loc;
1123 public void Add (Expression type)
1126 throw new InvalidOperationException ();
1131 public void Add (TypeArguments new_args)
1134 throw new InvalidOperationException ();
1136 args.AddRange (new_args.args);
1140 /// We're used during the parsing process: the parser can't distinguish
1141 /// between type parameters and type arguments. Because of that, the
1142 /// parser creates a `MemberName' with `TypeArguments' for both cases and
1143 /// in case of a generic type definition, we call GetDeclarations().
1145 public TypeParameterName[] GetDeclarations ()
1147 TypeParameterName[] ret = new TypeParameterName [args.Count];
1148 for (int i = 0; i < args.Count; i++) {
1149 TypeParameterName name = args [i] as TypeParameterName;
1154 SimpleName sn = args [i] as SimpleName;
1156 ret [i] = new TypeParameterName (sn.Name, null, sn.Location);
1160 Report.Error (81, Location, "Type parameter declaration " +
1161 "must be an identifier not a type");
1168 /// We may only be used after Resolve() is called and return the fully
1171 public Type[] Arguments {
1177 public bool HasTypeArguments {
1179 return has_type_args;
1192 public bool IsUnbound {
1194 return dimension > 0;
1198 public override string ToString ()
1200 StringBuilder s = new StringBuilder ();
1203 for (int i = 0; i < count; i++){
1205 // FIXME: Use TypeManager.CSharpname once we have the type
1208 s.Append (args [i].ToString ());
1212 return s.ToString ();
1215 public string GetSignatureForError()
1217 StringBuilder sb = new StringBuilder();
1218 for (int i = 0; i < Count; ++i)
1220 Expression expr = (Expression)args [i];
1221 sb.Append(expr.GetSignatureForError());
1225 return sb.ToString();
1229 /// Resolve the type arguments.
1231 public bool Resolve (IResolveContext ec)
1233 int count = args.Count;
1236 atypes = new Type [count];
1238 for (int i = 0; i < count; i++){
1239 TypeExpr te = ((Expression) args [i]).ResolveAsTypeTerminal (ec, false);
1244 if (te is TypeParameterExpr)
1245 has_type_args = true;
1247 if (te.Type.IsSealed && te.Type.IsAbstract) {
1248 Report.Error (718, Location, "`{0}': static classes cannot be used as generic arguments",
1249 te.GetSignatureForError ());
1252 if (te.Type.IsPointer) {
1253 Report.Error (306, Location, "The type `{0}' may not be used " +
1254 "as a type argument", TypeManager.CSharpName (te.Type));
1258 if (te.Type == TypeManager.void_type) {
1259 Expression.Error_VoidInvalidInTheContext (Location);
1263 atypes [i] = te.Type;
1269 public class TypeParameterName : SimpleName
1271 Attributes attributes;
1273 public TypeParameterName (string name, Attributes attrs, Location loc)
1279 public Attributes OptAttributes {
1287 /// An instantiation of a generic type.
1289 public class ConstructedType : TypeExpr {
1291 FullNamedExpression name;
1293 Type[] gen_params, atypes;
1297 /// Instantiate the generic type `fname' with the type arguments `args'.
1299 public ConstructedType (FullNamedExpression fname, TypeArguments args, Location l)
1305 eclass = ExprClass.Type;
1306 full_name = name + "<" + args.ToString () + ">";
1309 protected ConstructedType (TypeArguments args, Location l)
1314 eclass = ExprClass.Type;
1317 protected ConstructedType (TypeParameter[] type_params, Location l)
1321 args = new TypeArguments (l);
1322 foreach (TypeParameter type_param in type_params)
1323 args.Add (new TypeParameterExpr (type_param, l));
1325 eclass = ExprClass.Type;
1329 /// This is used to construct the `this' type inside a generic type definition.
1331 public ConstructedType (Type t, TypeParameter[] type_params, Location l)
1332 : this (type_params, l)
1334 gt = t.GetGenericTypeDefinition ();
1336 this.name = new TypeExpression (gt, l);
1337 full_name = gt.FullName + "<" + args.ToString () + ">";
1341 /// Instantiate the generic type `t' with the type arguments `args'.
1342 /// Use this constructor if you already know the fully resolved
1345 public ConstructedType (Type t, TypeArguments args, Location l)
1348 gt = t.GetGenericTypeDefinition ();
1350 this.name = new TypeExpression (gt, l);
1351 full_name = gt.FullName + "<" + args.ToString () + ">";
1354 public TypeArguments TypeArguments {
1355 get { return args; }
1358 public override string GetSignatureForError ()
1360 return TypeManager.RemoveGenericArity (gt.FullName) + "<" + args.GetSignatureForError () + ">";
1363 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1365 if (!ResolveConstructedType (ec))
1372 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1373 /// after fully resolving the constructed type.
1375 public bool CheckConstraints (IResolveContext ec)
1377 return ConstraintChecker.CheckConstraints (ec, gt, gen_params, atypes, loc);
1381 /// Resolve the constructed type, but don't check the constraints.
1383 public bool ResolveConstructedType (IResolveContext ec)
1387 // If we already know the fully resolved generic type.
1389 return DoResolveType (ec);
1395 Report.Error (246, loc, "Cannot find type `{0}'<...>", Name);
1399 num_args = TypeManager.GetNumberOfTypeArguments (t);
1400 if (num_args == 0) {
1401 Report.Error (308, loc,
1402 "The non-generic type `{0}' cannot " +
1403 "be used with type arguments.",
1404 TypeManager.CSharpName (t));
1408 gt = t.GetGenericTypeDefinition ();
1409 return DoResolveType (ec);
1412 bool DoResolveType (IResolveContext ec)
1415 // Resolve the arguments.
1417 if (args.Resolve (ec) == false)
1420 gen_params = gt.GetGenericArguments ();
1421 atypes = args.Arguments;
1423 if (atypes.Length != gen_params.Length) {
1424 Report.Error (305, loc,
1425 "Using the generic type `{0}' " +
1426 "requires {1} type arguments",
1427 TypeManager.CSharpName (gt),
1428 gen_params.Length.ToString ());
1433 // Now bind the parameters.
1435 type = gt.MakeGenericType (atypes);
1439 public Expression GetSimpleName (EmitContext ec)
1444 public override bool CheckAccessLevel (DeclSpace ds)
1446 return ds.CheckAccessLevel (gt);
1449 public override bool AsAccessible (DeclSpace ds, int flags)
1451 return ds.AsAccessible (gt, flags);
1454 public override bool IsClass {
1455 get { return gt.IsClass; }
1458 public override bool IsValueType {
1459 get { return gt.IsValueType; }
1462 public override bool IsInterface {
1463 get { return gt.IsInterface; }
1466 public override bool IsSealed {
1467 get { return gt.IsSealed; }
1470 public override bool Equals (object obj)
1472 ConstructedType cobj = obj as ConstructedType;
1476 if ((type == null) || (cobj.type == null))
1479 return type == cobj.type;
1482 public override int GetHashCode ()
1484 return base.GetHashCode ();
1487 public override string Name {
1493 public override string FullName {
1500 public abstract class ConstraintChecker
1502 protected readonly Type[] gen_params;
1503 protected readonly Type[] atypes;
1504 protected readonly Location loc;
1506 protected ConstraintChecker (Type[] gen_params, Type[] atypes, Location loc)
1508 this.gen_params = gen_params;
1509 this.atypes = atypes;
1514 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1515 /// after fully resolving the constructed type.
1517 public bool CheckConstraints (IResolveContext ec)
1519 for (int i = 0; i < gen_params.Length; i++) {
1520 if (!CheckConstraints (ec, i))
1527 protected bool CheckConstraints (IResolveContext ec, int index)
1529 Type atype = atypes [index];
1530 Type ptype = gen_params [index];
1535 Expression aexpr = new EmptyExpression (atype);
1537 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1541 bool is_class, is_struct;
1542 if (atype.IsGenericParameter) {
1543 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1545 if (agc is Constraints)
1546 ((Constraints) agc).Resolve (ec);
1547 is_class = agc.HasReferenceTypeConstraint;
1548 is_struct = agc.HasValueTypeConstraint;
1550 is_class = is_struct = false;
1555 if (!atype.IsGenericType)
1557 is_class = atype.IsClass || atype.IsInterface;
1558 is_struct = atype.IsValueType && !TypeManager.IsNullableType (atype);
1562 // First, check the `class' and `struct' constraints.
1564 if (gc.HasReferenceTypeConstraint && !is_class) {
1565 Report.Error (452, loc, "The type `{0}' must be " +
1566 "a reference type in order to use it " +
1567 "as type parameter `{1}' in the " +
1568 "generic type or method `{2}'.",
1569 TypeManager.CSharpName (atype),
1570 TypeManager.CSharpName (ptype),
1571 GetSignatureForError ());
1573 } else if (gc.HasValueTypeConstraint && !is_struct) {
1574 Report.Error (453, loc, "The type `{0}' must be a " +
1575 "non-nullable value type in order to use it " +
1576 "as type parameter `{1}' in the " +
1577 "generic type or method `{2}'.",
1578 TypeManager.CSharpName (atype),
1579 TypeManager.CSharpName (ptype),
1580 GetSignatureForError ());
1585 // The class constraint comes next.
1587 if (gc.HasClassConstraint) {
1588 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint))
1593 // Now, check the interface constraints.
1595 if (gc.InterfaceConstraints != null) {
1596 foreach (Type it in gc.InterfaceConstraints) {
1597 if (!CheckConstraint (ec, ptype, aexpr, it))
1603 // Finally, check the constructor constraint.
1606 if (!gc.HasConstructorConstraint)
1609 if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
1612 if (HasDefaultConstructor (ec.DeclContainer.TypeBuilder, atype))
1615 Report_SymbolRelatedToPreviousError ();
1616 Report.SymbolRelatedToPreviousError (atype);
1617 Report.Error (310, loc, "The type `{0}' must have a public " +
1618 "parameterless constructor in order to use it " +
1619 "as parameter `{1}' in the generic type or " +
1621 TypeManager.CSharpName (atype),
1622 TypeManager.CSharpName (ptype),
1623 GetSignatureForError ());
1627 protected bool CheckConstraint (IResolveContext ec, Type ptype, Expression expr,
1630 if (TypeManager.HasGenericArguments (ctype)) {
1631 Type[] types = TypeManager.GetTypeArguments (ctype);
1633 TypeArguments new_args = new TypeArguments (loc);
1635 for (int i = 0; i < types.Length; i++) {
1638 if (t.IsGenericParameter) {
1639 int pos = t.GenericParameterPosition;
1642 new_args.Add (new TypeExpression (t, loc));
1645 TypeExpr ct = new ConstructedType (ctype, new_args, loc);
1646 if (ct.ResolveAsTypeStep (ec, false) == null)
1649 } else if (ctype.IsGenericParameter) {
1650 int pos = ctype.GenericParameterPosition;
1651 ctype = atypes [pos];
1654 if (Convert.ImplicitStandardConversionExists (expr, ctype))
1657 Error_TypeMustBeConvertible (expr.Type, ctype, ptype);
1661 bool HasDefaultConstructor (Type containerType, Type atype)
1663 if (atype.IsAbstract)
1667 atype = TypeManager.DropGenericTypeArguments (atype);
1668 if (atype is TypeBuilder) {
1669 TypeContainer tc = TypeManager.LookupTypeContainer (atype);
1670 if (tc.InstanceConstructors == null) {
1671 atype = atype.BaseType;
1675 foreach (Constructor c in tc.InstanceConstructors) {
1676 if ((c.ModFlags & Modifiers.PUBLIC) == 0)
1678 if ((c.Parameters.FixedParameters != null) &&
1679 (c.Parameters.FixedParameters.Length != 0))
1681 if (c.Parameters.HasArglist || c.Parameters.HasParams)
1688 TypeParameter tparam = TypeManager.LookupTypeParameter (atype);
1690 return tparam.HasConstructorConstraint;
1692 MemberList list = TypeManager.FindMembers (
1693 atype, MemberTypes.Constructor,
1694 BindingFlags.Public | BindingFlags.Instance |
1695 BindingFlags.DeclaredOnly, null, null);
1697 if (atype.IsAbstract || (list == null))
1700 foreach (MethodBase mb in list) {
1701 ParameterData pd = TypeManager.GetParameterData (mb);
1702 if ((pd.Count == 0) && mb.IsPublic && !mb.IsStatic)
1709 protected abstract string GetSignatureForError ();
1710 protected abstract void Report_SymbolRelatedToPreviousError ();
1712 void Error_TypeMustBeConvertible (Type atype, Type gc, Type ptype)
1714 Report_SymbolRelatedToPreviousError ();
1715 Report.SymbolRelatedToPreviousError (atype);
1716 Report.Error (309, loc,
1717 "The type `{0}' must be convertible to `{1}' in order to " +
1718 "use it as parameter `{2}' in the generic type or method `{3}'",
1719 TypeManager.CSharpName (atype), TypeManager.CSharpName (gc),
1720 TypeManager.CSharpName (ptype), GetSignatureForError ());
1723 public static bool CheckConstraints (EmitContext ec, MethodBase definition,
1724 MethodBase instantiated, Location loc)
1726 MethodConstraintChecker checker = new MethodConstraintChecker (
1727 definition, definition.GetGenericArguments (),
1728 instantiated.GetGenericArguments (), loc);
1730 return checker.CheckConstraints (ec);
1733 public static bool CheckConstraints (IResolveContext ec, Type gt, Type[] gen_params,
1734 Type[] atypes, Location loc)
1736 TypeConstraintChecker checker = new TypeConstraintChecker (
1737 gt, gen_params, atypes, loc);
1739 return checker.CheckConstraints (ec);
1742 protected class MethodConstraintChecker : ConstraintChecker
1744 MethodBase definition;
1746 public MethodConstraintChecker (MethodBase definition, Type[] gen_params,
1747 Type[] atypes, Location loc)
1748 : base (gen_params, atypes, loc)
1750 this.definition = definition;
1753 protected override string GetSignatureForError ()
1755 return TypeManager.CSharpSignature (definition);
1758 protected override void Report_SymbolRelatedToPreviousError ()
1760 Report.SymbolRelatedToPreviousError (definition);
1764 protected class TypeConstraintChecker : ConstraintChecker
1768 public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
1770 : base (gen_params, atypes, loc)
1775 protected override string GetSignatureForError ()
1777 return TypeManager.CSharpName (gt);
1780 protected override void Report_SymbolRelatedToPreviousError ()
1782 Report.SymbolRelatedToPreviousError (gt);
1788 /// A generic method definition.
1790 public class GenericMethod : DeclSpace
1792 Expression return_type;
1793 Parameters parameters;
1795 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
1796 Expression return_type, Parameters parameters)
1797 : base (ns, parent, name, null)
1799 this.return_type = return_type;
1800 this.parameters = parameters;
1803 public override TypeBuilder DefineType ()
1805 throw new Exception ();
1808 public override bool Define ()
1810 for (int i = 0; i < TypeParameters.Length; i++)
1811 if (!TypeParameters [i].Resolve (this))
1818 /// Define and resolve the type parameters.
1819 /// We're called from Method.Define().
1821 public bool Define (MethodBuilder mb, ToplevelBlock block)
1823 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1824 string[] snames = new string [names.Length];
1825 for (int i = 0; i < names.Length; i++) {
1826 string type_argument_name = names[i].Name;
1827 Parameter p = parameters.GetParameterByName (type_argument_name);
1829 Error_ParameterNameCollision (p.Location, type_argument_name, "method parameter");
1832 if (block != null) {
1833 LocalInfo li = (LocalInfo)block.Variables[type_argument_name];
1835 Error_ParameterNameCollision (li.Location, type_argument_name, "local variable");
1839 snames[i] = type_argument_name;
1842 GenericTypeParameterBuilder[] gen_params = mb.DefineGenericParameters (snames);
1843 for (int i = 0; i < TypeParameters.Length; i++)
1844 TypeParameters [i].Define (gen_params [i]);
1849 for (int i = 0; i < TypeParameters.Length; i++) {
1850 if (!TypeParameters [i].ResolveType (this))
1857 static void Error_ParameterNameCollision (Location loc, string name, string collisionWith)
1859 Report.Error (412, loc, "The type parameter name `{0}' is the same as `{1}'",
1860 name, collisionWith);
1864 /// We're called from MethodData.Define() after creating the MethodBuilder.
1866 public bool DefineType (EmitContext ec, MethodBuilder mb,
1867 MethodInfo implementing, bool is_override)
1869 for (int i = 0; i < TypeParameters.Length; i++)
1870 if (!TypeParameters [i].DefineType (
1871 ec, mb, implementing, is_override))
1875 foreach (Parameter p in parameters.FixedParameters){
1876 if (!p.Resolve (ec))
1879 if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec, false) == null))
1885 public void EmitAttributes ()
1887 for (int i = 0; i < TypeParameters.Length; i++)
1888 TypeParameters [i].EmitAttributes ();
1890 if (OptAttributes != null)
1891 OptAttributes.Emit ();
1894 public override bool DefineMembers ()
1899 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1900 MemberFilter filter, object criteria)
1902 throw new Exception ();
1905 public override MemberCache MemberCache {
1911 public override AttributeTargets AttributeTargets {
1913 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1917 public override string DocCommentHeader {
1918 get { return "M:"; }
1921 public new void VerifyClsCompliance ()
1923 foreach (TypeParameter tp in TypeParameters) {
1924 if (tp.Constraints == null)
1927 tp.Constraints.VerifyClsCompliance ();
1932 public class DefaultValueExpression : Expression
1936 public DefaultValueExpression (Expression expr, Location loc)
1942 public override Expression DoResolve (EmitContext ec)
1944 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
1950 if (type == TypeManager.void_type) {
1951 Error_VoidInvalidInTheContext (loc);
1955 if (type.IsGenericParameter)
1957 GenericConstraints constraints = TypeManager.GetTypeParameterConstraints(type);
1958 if (constraints != null && constraints.IsReferenceType)
1959 return new NullDefault (new NullLiteral (Location), type);
1963 Constant c = New.Constantify(type);
1965 return new NullDefault (c, type);
1967 if (!TypeManager.IsValueType (type))
1968 return new NullDefault (new NullLiteral (Location), type);
1970 eclass = ExprClass.Variable;
1974 public override void Emit (EmitContext ec)
1976 LocalTemporary temp_storage = new LocalTemporary(type);
1978 temp_storage.AddressOf(ec, AddressOp.LoadStore);
1979 ec.ig.Emit(OpCodes.Initobj, type);
1980 temp_storage.Emit(ec);
1984 public class NullableType : TypeExpr
1986 Expression underlying;
1988 public NullableType (Expression underlying, Location l)
1990 this.underlying = underlying;
1993 eclass = ExprClass.Type;
1996 public NullableType (Type type, Location loc)
1997 : this (new TypeExpression (type, loc), loc)
2000 public override string Name {
2001 get { return underlying.ToString () + "?"; }
2004 public override string FullName {
2005 get { return underlying.ToString () + "?"; }
2008 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
2010 TypeArguments args = new TypeArguments (loc);
2011 args.Add (underlying);
2013 ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
2014 return ctype.ResolveAsTypeTerminal (ec, false);
2018 public partial class TypeManager
2021 // A list of core types that the compiler requires or uses
2023 static public Type activator_type;
2024 static public Type generic_ilist_type;
2025 static public Type generic_icollection_type;
2026 static public Type generic_ienumerator_type;
2027 static public Type generic_ienumerable_type;
2028 static public Type generic_nullable_type;
2031 // These methods are called by code generated by the compiler
2033 static public MethodInfo activator_create_instance;
2035 static void InitGenericCoreTypes ()
2037 activator_type = CoreLookupType ("System", "Activator");
2039 generic_ilist_type = CoreLookupType (
2040 "System.Collections.Generic", "IList", 1);
2041 generic_icollection_type = CoreLookupType (
2042 "System.Collections.Generic", "ICollection", 1);
2043 generic_ienumerator_type = CoreLookupType (
2044 "System.Collections.Generic", "IEnumerator", 1);
2045 generic_ienumerable_type = CoreLookupType (
2046 "System.Collections.Generic", "IEnumerable", 1);
2047 generic_nullable_type = CoreLookupType (
2048 "System", "Nullable", 1);
2051 static void InitGenericCodeHelpers ()
2054 Type [] type_arg = { type_type };
2055 activator_create_instance = GetMethod (
2056 activator_type, "CreateInstance", type_arg);
2059 static Type CoreLookupType (string ns, string name, int arity)
2061 return CoreLookupType (ns, MemberName.MakeName (name, arity));
2064 public static TypeContainer LookupGenericTypeContainer (Type t)
2066 t = DropGenericTypeArguments (t);
2067 return LookupTypeContainer (t);
2070 public static GenericConstraints GetTypeParameterConstraints (Type t)
2072 if (!t.IsGenericParameter)
2073 throw new InvalidOperationException ();
2075 TypeParameter tparam = LookupTypeParameter (t);
2077 return tparam.GenericConstraints;
2079 return ReflectionConstraints.GetConstraints (t);
2083 /// Check whether `a' and `b' may become equal generic types.
2084 /// The algorithm to do that is a little bit complicated.
2086 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_infered,
2087 Type[] method_infered)
2089 if (a.IsGenericParameter) {
2091 // If a is an array of a's type, they may never
2095 b = b.GetElementType ();
2101 // If b is a generic parameter or an actual type,
2102 // they may become equal:
2104 // class X<T,U> : I<T>, I<U>
2105 // class X<T> : I<T>, I<float>
2107 if (b.IsGenericParameter || !b.IsGenericType) {
2108 int pos = a.GenericParameterPosition;
2109 Type[] args = a.DeclaringMethod != null ? method_infered : class_infered;
2110 if (args [pos] == null) {
2115 return args [pos] == a;
2119 // We're now comparing a type parameter with a
2120 // generic instance. They may become equal unless
2121 // the type parameter appears anywhere in the
2122 // generic instance:
2124 // class X<T,U> : I<T>, I<X<U>>
2125 // -> error because you could instanciate it as
2128 // class X<T> : I<T>, I<X<T>> -> ok
2131 Type[] bargs = GetTypeArguments (b);
2132 for (int i = 0; i < bargs.Length; i++) {
2133 if (a.Equals (bargs [i]))
2140 if (b.IsGenericParameter)
2141 return MayBecomeEqualGenericTypes (b, a, class_infered, method_infered);
2144 // At this point, neither a nor b are a type parameter.
2146 // If one of them is a generic instance, let
2147 // MayBecomeEqualGenericInstances() compare them (if the
2148 // other one is not a generic instance, they can never
2152 if (a.IsGenericType || b.IsGenericType)
2153 return MayBecomeEqualGenericInstances (a, b, class_infered, method_infered);
2156 // If both of them are arrays.
2159 if (a.IsArray && b.IsArray) {
2160 if (a.GetArrayRank () != b.GetArrayRank ())
2163 a = a.GetElementType ();
2164 b = b.GetElementType ();
2166 return MayBecomeEqualGenericTypes (a, b, class_infered, method_infered);
2170 // Ok, two ordinary types.
2173 return a.Equals (b);
2177 // Checks whether two generic instances may become equal for some
2178 // particular instantiation (26.3.1).
2180 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
2181 Type[] class_infered,
2182 Type[] method_infered)
2184 if (!a.IsGenericType || !b.IsGenericType)
2186 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2189 return MayBecomeEqualGenericInstances (
2190 GetTypeArguments (a), GetTypeArguments (b), class_infered, method_infered);
2193 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
2194 Type[] class_infered,
2195 Type[] method_infered)
2197 if (aargs.Length != bargs.Length)
2200 for (int i = 0; i < aargs.Length; i++) {
2201 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_infered, method_infered))
2212 static bool InferType (Type pt, Type at, Type[] infered)
2214 if (pt.IsGenericParameter) {
2215 if (pt.DeclaringMethod == null)
2218 int pos = pt.GenericParameterPosition;
2220 if (infered [pos] == null) {
2225 if (infered [pos] != at)
2231 if (!pt.ContainsGenericParameters) {
2232 if (at.ContainsGenericParameters)
2233 return InferType (at, pt, infered);
2240 if (at.GetArrayRank () != pt.GetArrayRank ())
2243 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2246 if (!pt.IsGenericType)
2249 Type gt = pt.GetGenericTypeDefinition ();
2250 if ((gt != generic_ilist_type) && (gt != generic_icollection_type) &&
2251 (gt != generic_ienumerable_type))
2254 Type[] args = GetTypeArguments (pt);
2255 return InferType (args [0], at.GetElementType (), infered);
2260 (pt.GetArrayRank () != at.GetArrayRank ()))
2263 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2266 if (pt.IsByRef && at.IsByRef)
2267 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2268 ArrayList list = new ArrayList ();
2269 if (at.IsGenericType)
2271 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
2274 list.AddRange (TypeManager.GetInterfaces (at));
2276 bool found_one = false;
2278 foreach (Type type in list) {
2279 if (!type.IsGenericType)
2282 Type[] infered_types = new Type [infered.Length];
2284 if (!InferGenericInstance (pt, type, infered_types))
2287 for (int i = 0; i < infered_types.Length; i++) {
2288 if (infered [i] == null) {
2289 infered [i] = infered_types [i];
2293 if (infered [i] != infered_types [i])
2303 static bool InferGenericInstance (Type pt, Type at, Type[] infered_types)
2305 Type[] at_args = at.GetGenericArguments ();
2306 Type[] pt_args = pt.GetGenericArguments ();
2308 if (at_args.Length != pt_args.Length)
2311 for (int i = 0; i < at_args.Length; i++) {
2312 if (!InferType (pt_args [i], at_args [i], infered_types))
2316 for (int i = 0; i < infered_types.Length; i++) {
2317 if (infered_types [i] == null)
2325 /// Type inference. Try to infer the type arguments from the params method
2326 /// `method', which is invoked with the arguments `arguments'. This is used
2327 /// when resolving an Invocation or a DelegateInvocation and the user
2328 /// did not explicitly specify type arguments.
2330 public static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
2331 ref MethodBase method)
2333 if (!TypeManager.IsGenericMethod (method))
2336 // if there are no arguments, there's no way to infer the type-arguments
2337 if (arguments == null || arguments.Count == 0)
2340 ParameterData pd = TypeManager.GetParameterData (method);
2341 int pd_count = pd.Count;
2342 int arg_count = arguments.Count;
2347 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2350 if (pd_count - 1 > arg_count)
2353 Type[] method_args = method.GetGenericArguments ();
2354 Type[] infered_types = new Type [method_args.Length];
2357 // If we have come this far, the case which
2358 // remains is when the number of parameters is
2359 // less than or equal to the argument count.
2361 for (int i = 0; i < pd_count - 1; ++i) {
2362 Argument a = (Argument) arguments [i];
2364 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2367 Type pt = pd.ParameterType (i);
2370 if (!InferType (pt, at, infered_types))
2374 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
2376 for (int i = pd_count - 1; i < arg_count; i++) {
2377 Argument a = (Argument) arguments [i];
2379 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2382 if (!InferType (element_type, a.Type, infered_types))
2386 for (int i = 0; i < infered_types.Length; i++)
2387 if (infered_types [i] == null)
2390 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2394 static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
2395 Type[] infered_types)
2397 if (infered_types == null)
2400 for (int i = 0; i < arg_types.Length; i++) {
2401 if (arg_types [i] == null)
2404 if (!InferType (param_types [i], arg_types [i], infered_types))
2408 for (int i = 0; i < infered_types.Length; i++)
2409 if (infered_types [i] == null)
2416 /// Type inference. Try to infer the type arguments from `method',
2417 /// which is invoked with the arguments `arguments'. This is used
2418 /// when resolving an Invocation or a DelegateInvocation and the user
2419 /// did not explicitly specify type arguments.
2421 public static bool InferTypeArguments (ArrayList arguments,
2422 ref MethodBase method)
2424 if (!TypeManager.IsGenericMethod (method))
2428 if (arguments != null)
2429 arg_count = arguments.Count;
2433 ParameterData pd = TypeManager.GetParameterData (method);
2434 if (arg_count != pd.Count)
2437 Type[] method_args = method.GetGenericArguments ();
2439 bool is_open = false;
2440 for (int i = 0; i < method_args.Length; i++) {
2441 if (method_args [i].IsGenericParameter) {
2447 // If none of the method parameters mention a generic parameter, we can't infer the generic parameters
2449 return !TypeManager.IsGenericMethodDefinition (method);
2451 Type[] infered_types = new Type [method_args.Length];
2453 Type[] param_types = new Type [pd.Count];
2454 Type[] arg_types = new Type [pd.Count];
2456 for (int i = 0; i < arg_count; i++) {
2457 param_types [i] = pd.ParameterType (i);
2459 Argument a = (Argument) arguments [i];
2460 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr) ||
2461 (a.Expr is AnonymousMethod))
2464 arg_types [i] = a.Type;
2467 if (!InferTypeArguments (param_types, arg_types, infered_types))
2470 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2477 public static bool InferTypeArguments (ParameterData apd,
2478 ref MethodBase method)
2480 if (!TypeManager.IsGenericMethod (method))
2483 ParameterData pd = TypeManager.GetParameterData (method);
2484 if (apd.Count != pd.Count)
2487 Type[] method_args = method.GetGenericArguments ();
2488 Type[] infered_types = new Type [method_args.Length];
2490 Type[] param_types = new Type [pd.Count];
2491 Type[] arg_types = new Type [pd.Count];
2493 for (int i = 0; i < apd.Count; i++) {
2494 param_types [i] = pd.ParameterType (i);
2495 arg_types [i] = apd.ParameterType (i);
2498 if (!InferTypeArguments (param_types, arg_types, infered_types))
2501 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2506 public abstract class Nullable
2508 public sealed class NullableInfo
2510 public readonly Type Type;
2511 public readonly Type UnderlyingType;
2512 public readonly MethodInfo HasValue;
2513 public readonly MethodInfo Value;
2514 public readonly ConstructorInfo Constructor;
2516 public NullableInfo (Type type)
2519 UnderlyingType = TypeManager.GetTypeArguments (type) [0];
2521 PropertyInfo has_value_pi = TypeManager.GetProperty (type, "HasValue");
2522 PropertyInfo value_pi = TypeManager.GetProperty (type, "Value");
2524 HasValue = has_value_pi.GetGetMethod (false);
2525 Value = value_pi.GetGetMethod (false);
2526 Constructor = type.GetConstructor (new Type[] { UnderlyingType });
2530 public class Unwrap : Expression, IMemoryLocation, IAssignMethod
2535 LocalTemporary temp;
2538 protected Unwrap (Expression expr)
2541 this.loc = expr.Location;
2544 public static Unwrap Create (Expression expr, EmitContext ec)
2546 return new Unwrap (expr).Resolve (ec) as Unwrap;
2549 public override Expression DoResolve (EmitContext ec)
2551 expr = expr.Resolve (ec);
2555 temp = new LocalTemporary (expr.Type);
2557 info = new NullableInfo (expr.Type);
2558 type = info.UnderlyingType;
2559 eclass = expr.eclass;
2563 public override void Emit (EmitContext ec)
2565 AddressOf (ec, AddressOp.LoadStore);
2566 ec.ig.EmitCall (OpCodes.Call, info.Value, null);
2569 public void EmitCheck (EmitContext ec)
2571 AddressOf (ec, AddressOp.LoadStore);
2572 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
2575 public void Store (EmitContext ec)
2580 void create_temp (EmitContext ec)
2582 if ((temp != null) && !has_temp) {
2589 public void AddressOf (EmitContext ec, AddressOp mode)
2593 temp.AddressOf (ec, AddressOp.LoadStore);
2595 ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
2598 public void Emit (EmitContext ec, bool leave_copy)
2611 public void EmitAssign (EmitContext ec, Expression source,
2612 bool leave_copy, bool prepare_for_load)
2614 InternalWrap wrap = new InternalWrap (source, info, loc);
2615 ((IAssignMethod) expr).EmitAssign (ec, wrap, leave_copy, false);
2618 protected class InternalWrap : Expression
2620 public Expression expr;
2621 public NullableInfo info;
2623 public InternalWrap (Expression expr, NullableInfo info, Location loc)
2630 eclass = ExprClass.Value;
2633 public override Expression DoResolve (EmitContext ec)
2638 public override void Emit (EmitContext ec)
2641 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2646 public class Wrap : Expression
2651 protected Wrap (Expression expr)
2654 this.loc = expr.Location;
2657 public static Wrap Create (Expression expr, EmitContext ec)
2659 return new Wrap (expr).Resolve (ec) as Wrap;
2662 public override Expression DoResolve (EmitContext ec)
2664 expr = expr.Resolve (ec);
2668 TypeExpr target_type = new NullableType (expr.Type, loc);
2669 target_type = target_type.ResolveAsTypeTerminal (ec, false);
2670 if (target_type == null)
2673 type = target_type.Type;
2674 info = new NullableInfo (type);
2675 eclass = ExprClass.Value;
2679 public override void Emit (EmitContext ec)
2682 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2686 public class NullableLiteral : NullLiteral, IMemoryLocation {
2687 public NullableLiteral (Type target_type, Location loc)
2690 this.type = target_type;
2692 eclass = ExprClass.Value;
2695 public override Expression DoResolve (EmitContext ec)
2700 public override void Emit (EmitContext ec)
2702 LocalTemporary value_target = new LocalTemporary (type);
2704 value_target.AddressOf (ec, AddressOp.Store);
2705 ec.ig.Emit (OpCodes.Initobj, type);
2706 value_target.Emit (ec);
2709 public void AddressOf (EmitContext ec, AddressOp Mode)
2711 LocalTemporary value_target = new LocalTemporary (type);
2713 value_target.AddressOf (ec, AddressOp.Store);
2714 ec.ig.Emit (OpCodes.Initobj, type);
2715 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
2719 public abstract class Lifted : Expression, IMemoryLocation
2721 Expression expr, underlying, wrap, null_value;
2724 protected Lifted (Expression expr, Location loc)
2730 public override Expression DoResolve (EmitContext ec)
2732 expr = expr.Resolve (ec);
2736 unwrap = Unwrap.Create (expr, ec);
2740 underlying = ResolveUnderlying (unwrap, ec);
2741 if (underlying == null)
2744 wrap = Wrap.Create (underlying, ec);
2748 null_value = new NullableLiteral (wrap.Type, loc).Resolve (ec);
2749 if (null_value == null)
2753 eclass = ExprClass.Value;
2757 protected abstract Expression ResolveUnderlying (Expression unwrap, EmitContext ec);
2759 public override void Emit (EmitContext ec)
2761 ILGenerator ig = ec.ig;
2762 Label is_null_label = ig.DefineLabel ();
2763 Label end_label = ig.DefineLabel ();
2765 unwrap.EmitCheck (ec);
2766 ig.Emit (OpCodes.Brfalse, is_null_label);
2769 ig.Emit (OpCodes.Br, end_label);
2771 ig.MarkLabel (is_null_label);
2772 null_value.Emit (ec);
2774 ig.MarkLabel (end_label);
2777 public void AddressOf (EmitContext ec, AddressOp mode)
2779 unwrap.AddressOf (ec, mode);
2783 public class LiftedConversion : Lifted
2785 public readonly bool IsUser;
2786 public readonly bool IsExplicit;
2787 public readonly Type TargetType;
2789 public LiftedConversion (Expression expr, Type target_type, bool is_user,
2790 bool is_explicit, Location loc)
2793 this.IsUser = is_user;
2794 this.IsExplicit = is_explicit;
2795 this.TargetType = target_type;
2798 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2800 Type type = TypeManager.GetTypeArguments (TargetType) [0];
2803 return Convert.UserDefinedConversion (ec, unwrap, type, loc, IsExplicit);
2806 return Convert.ExplicitConversion (ec, unwrap, type, loc);
2808 return Convert.ImplicitConversion (ec, unwrap, type, loc);
2813 public class LiftedUnaryOperator : Lifted
2815 public readonly Unary.Operator Oper;
2817 public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
2823 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2825 return new Unary (Oper, unwrap, loc);
2829 public class LiftedConditional : Lifted
2831 Expression true_expr, false_expr;
2833 public LiftedConditional (Expression expr, Expression true_expr, Expression false_expr,
2837 this.true_expr = true_expr;
2838 this.false_expr = false_expr;
2841 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2843 return new Conditional (unwrap, true_expr, false_expr);
2847 public class LiftedBinaryOperator : Expression
2849 public readonly Binary.Operator Oper;
2851 Expression left, right, original_left, original_right;
2852 Expression underlying, null_value, bool_wrap;
2853 Unwrap left_unwrap, right_unwrap;
2854 bool is_equality, is_comparision, is_boolean;
2856 public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
2860 this.left = original_left = left;
2861 this.right = original_right = right;
2865 public override Expression DoResolve (EmitContext ec)
2867 if (TypeManager.IsNullableType (left.Type)) {
2868 left = left_unwrap = Unwrap.Create (left, ec);
2873 if (TypeManager.IsNullableType (right.Type)) {
2874 right = right_unwrap = Unwrap.Create (right, ec);
2879 if ((Oper == Binary.Operator.LogicalAnd) ||
2880 (Oper == Binary.Operator.LogicalOr)) {
2881 Binary.Error_OperatorCannotBeApplied (
2882 loc, Binary.OperName (Oper),
2883 original_left.GetSignatureForError (),
2884 original_right.GetSignatureForError ());
2888 if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr)) &&
2889 ((left.Type == TypeManager.bool_type) && (right.Type == TypeManager.bool_type))) {
2890 Expression empty = new EmptyExpression (TypeManager.bool_type);
2891 bool_wrap = Wrap.Create (empty, ec);
2892 null_value = new NullableLiteral (bool_wrap.Type, loc).Resolve (ec);
2894 type = bool_wrap.Type;
2896 } else if ((Oper == Binary.Operator.Equality) || (Oper == Binary.Operator.Inequality)) {
2897 if (!(left is NullLiteral) && !(right is NullLiteral)) {
2898 underlying = new Binary (Oper, left, right).Resolve (ec);
2899 if (underlying == null)
2903 type = TypeManager.bool_type;
2905 } else if ((Oper == Binary.Operator.LessThan) ||
2906 (Oper == Binary.Operator.GreaterThan) ||
2907 (Oper == Binary.Operator.LessThanOrEqual) ||
2908 (Oper == Binary.Operator.GreaterThanOrEqual)) {
2909 underlying = new Binary (Oper, left, right).Resolve (ec);
2910 if (underlying == null)
2913 type = TypeManager.bool_type;
2914 is_comparision = true;
2916 underlying = new Binary (Oper, left, right).Resolve (ec);
2917 if (underlying == null)
2920 underlying = Wrap.Create (underlying, ec);
2921 if (underlying == null)
2924 type = underlying.Type;
2925 null_value = new NullableLiteral (type, loc).Resolve (ec);
2928 eclass = ExprClass.Value;
2932 void EmitBoolean (EmitContext ec)
2934 ILGenerator ig = ec.ig;
2936 Label left_is_null_label = ig.DefineLabel ();
2937 Label right_is_null_label = ig.DefineLabel ();
2938 Label is_null_label = ig.DefineLabel ();
2939 Label wrap_label = ig.DefineLabel ();
2940 Label end_label = ig.DefineLabel ();
2942 if (left_unwrap != null) {
2943 left_unwrap.EmitCheck (ec);
2944 ig.Emit (OpCodes.Brfalse, left_is_null_label);
2948 ig.Emit (OpCodes.Dup);
2949 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
2950 ig.Emit (OpCodes.Brtrue, wrap_label);
2952 ig.Emit (OpCodes.Brfalse, wrap_label);
2954 if (right_unwrap != null) {
2955 right_unwrap.EmitCheck (ec);
2956 ig.Emit (OpCodes.Brfalse, right_is_null_label);
2959 if ((Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr))
2960 ig.Emit (OpCodes.Pop);
2963 if (Oper == Binary.Operator.BitwiseOr)
2964 ig.Emit (OpCodes.Or);
2965 else if (Oper == Binary.Operator.BitwiseAnd)
2966 ig.Emit (OpCodes.And);
2967 ig.Emit (OpCodes.Br, wrap_label);
2969 ig.MarkLabel (left_is_null_label);
2970 if (right_unwrap != null) {
2971 right_unwrap.EmitCheck (ec);
2972 ig.Emit (OpCodes.Brfalse, is_null_label);
2976 ig.Emit (OpCodes.Dup);
2977 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
2978 ig.Emit (OpCodes.Brtrue, wrap_label);
2980 ig.Emit (OpCodes.Brfalse, wrap_label);
2982 ig.MarkLabel (right_is_null_label);
2983 ig.Emit (OpCodes.Pop);
2984 ig.MarkLabel (is_null_label);
2985 null_value.Emit (ec);
2986 ig.Emit (OpCodes.Br, end_label);
2988 ig.MarkLabel (wrap_label);
2989 ig.Emit (OpCodes.Nop);
2990 bool_wrap.Emit (ec);
2991 ig.Emit (OpCodes.Nop);
2993 ig.MarkLabel (end_label);
2996 void EmitEquality (EmitContext ec)
2998 ILGenerator ig = ec.ig;
3000 // Given 'X? x;' for any value type X: 'x != null' is the same as 'x.HasValue'
3001 if (left is NullLiteral) {
3002 if (right_unwrap == null)
3003 throw new InternalErrorException ();
3004 right_unwrap.EmitCheck (ec);
3005 if (Oper == Binary.Operator.Equality) {
3006 ig.Emit (OpCodes.Ldc_I4_0);
3007 ig.Emit (OpCodes.Ceq);
3012 if (right is NullLiteral) {
3013 if (left_unwrap == null)
3014 throw new InternalErrorException ();
3015 left_unwrap.EmitCheck (ec);
3016 if (Oper == Binary.Operator.Equality) {
3017 ig.Emit (OpCodes.Ldc_I4_0);
3018 ig.Emit (OpCodes.Ceq);
3023 Label both_have_value_label = ig.DefineLabel ();
3024 Label end_label = ig.DefineLabel ();
3026 if (left_unwrap != null && right_unwrap != null) {
3027 Label dissimilar_label = ig.DefineLabel ();
3029 left_unwrap.EmitCheck (ec);
3030 ig.Emit (OpCodes.Dup);
3031 right_unwrap.EmitCheck (ec);
3032 ig.Emit (OpCodes.Bne_Un, dissimilar_label);
3034 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3037 if (Oper == Binary.Operator.Equality)
3038 ig.Emit (OpCodes.Ldc_I4_1);
3040 ig.Emit (OpCodes.Ldc_I4_0);
3041 ig.Emit (OpCodes.Br, end_label);
3043 ig.MarkLabel (dissimilar_label);
3044 ig.Emit (OpCodes.Pop);
3045 } else if (left_unwrap != null) {
3046 left_unwrap.EmitCheck (ec);
3047 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3048 } else if (right_unwrap != null) {
3049 right_unwrap.EmitCheck (ec);
3050 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3052 throw new InternalErrorException ("shouldn't get here");
3055 // one is null while the other isn't
3056 if (Oper == Binary.Operator.Equality)
3057 ig.Emit (OpCodes.Ldc_I4_0);
3059 ig.Emit (OpCodes.Ldc_I4_1);
3060 ig.Emit (OpCodes.Br, end_label);
3062 ig.MarkLabel (both_have_value_label);
3063 underlying.Emit (ec);
3065 ig.MarkLabel (end_label);
3068 void EmitComparision (EmitContext ec)
3070 ILGenerator ig = ec.ig;
3072 Label is_null_label = ig.DefineLabel ();
3073 Label end_label = ig.DefineLabel ();
3075 if (left_unwrap != null) {
3076 left_unwrap.EmitCheck (ec);
3077 ig.Emit (OpCodes.Brfalse, is_null_label);
3080 if (right_unwrap != null) {
3081 right_unwrap.EmitCheck (ec);
3082 ig.Emit (OpCodes.Brfalse, is_null_label);
3085 underlying.Emit (ec);
3086 ig.Emit (OpCodes.Br, end_label);
3088 ig.MarkLabel (is_null_label);
3089 ig.Emit (OpCodes.Ldc_I4_0);
3091 ig.MarkLabel (end_label);
3094 public override void Emit (EmitContext ec)
3096 if (left_unwrap != null)
3097 left_unwrap.Store (ec);
3098 if (right_unwrap != null)
3099 right_unwrap.Store (ec);
3104 } else if (is_equality) {
3107 } else if (is_comparision) {
3108 EmitComparision (ec);
3112 ILGenerator ig = ec.ig;
3114 Label is_null_label = ig.DefineLabel ();
3115 Label end_label = ig.DefineLabel ();
3117 if (left_unwrap != null) {
3118 left_unwrap.EmitCheck (ec);
3119 ig.Emit (OpCodes.Brfalse, is_null_label);
3122 if (right_unwrap != null) {
3123 right_unwrap.EmitCheck (ec);
3124 ig.Emit (OpCodes.Brfalse, is_null_label);
3127 underlying.Emit (ec);
3128 ig.Emit (OpCodes.Br, end_label);
3130 ig.MarkLabel (is_null_label);
3131 null_value.Emit (ec);
3133 ig.MarkLabel (end_label);
3137 public class OperatorTrueOrFalse : Expression
3139 public readonly bool IsTrue;
3144 public OperatorTrueOrFalse (Expression expr, bool is_true, Location loc)
3146 this.IsTrue = is_true;
3151 public override Expression DoResolve (EmitContext ec)
3153 unwrap = Unwrap.Create (expr, ec);
3157 if (unwrap.Type != TypeManager.bool_type)
3160 type = TypeManager.bool_type;
3161 eclass = ExprClass.Value;
3165 public override void Emit (EmitContext ec)
3167 ILGenerator ig = ec.ig;
3169 Label is_null_label = ig.DefineLabel ();
3170 Label end_label = ig.DefineLabel ();
3172 unwrap.EmitCheck (ec);
3173 ig.Emit (OpCodes.Brfalse, is_null_label);
3177 ig.Emit (OpCodes.Ldc_I4_0);
3178 ig.Emit (OpCodes.Ceq);
3180 ig.Emit (OpCodes.Br, end_label);
3182 ig.MarkLabel (is_null_label);
3183 ig.Emit (OpCodes.Ldc_I4_0);
3185 ig.MarkLabel (end_label);
3189 public class NullCoalescingOperator : Expression
3191 Expression left, right;
3195 public NullCoalescingOperator (Expression left, Expression right, Location loc)
3201 eclass = ExprClass.Value;
3204 public override Expression DoResolve (EmitContext ec)
3209 left = left.Resolve (ec);
3213 right = right.Resolve (ec);
3217 Type ltype = left.Type, rtype = right.Type;
3219 if (!TypeManager.IsNullableType (ltype) && ltype.IsValueType) {
3220 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3224 if (TypeManager.IsNullableType (ltype)) {
3225 NullableInfo info = new NullableInfo (ltype);
3227 unwrap = Unwrap.Create (left, ec);
3231 expr = Convert.ImplicitConversion (ec, right, info.UnderlyingType, loc);
3239 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
3245 if (unwrap != null) {
3246 expr = Convert.ImplicitConversion (ec, unwrap, rtype, loc);
3255 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3259 public override void Emit (EmitContext ec)
3261 ILGenerator ig = ec.ig;
3263 Label is_null_label = ig.DefineLabel ();
3264 Label end_label = ig.DefineLabel ();
3266 if (unwrap != null) {
3267 unwrap.EmitCheck (ec);
3268 ig.Emit (OpCodes.Brfalse, is_null_label);
3271 ig.Emit (OpCodes.Br, end_label);
3273 ig.MarkLabel (is_null_label);
3276 ig.MarkLabel (end_label);
3279 ig.Emit (OpCodes.Dup);
3280 ig.Emit (OpCodes.Brtrue, end_label);
3282 ig.MarkLabel (is_null_label);
3284 ig.Emit (OpCodes.Pop);
3287 ig.MarkLabel (end_label);
3292 public class LiftedUnaryMutator : ExpressionStatement
3294 public readonly UnaryMutator.Mode Mode;
3295 Expression expr, null_value;
3296 UnaryMutator underlying;
3299 public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
3305 eclass = ExprClass.Value;
3308 public override Expression DoResolve (EmitContext ec)
3310 expr = expr.Resolve (ec);
3314 unwrap = Unwrap.Create (expr, ec);
3318 underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
3319 if (underlying == null)
3322 null_value = new NullableLiteral (expr.Type, loc).Resolve (ec);
3323 if (null_value == null)
3330 void DoEmit (EmitContext ec, bool is_expr)
3332 ILGenerator ig = ec.ig;
3333 Label is_null_label = ig.DefineLabel ();
3334 Label end_label = ig.DefineLabel ();
3336 unwrap.EmitCheck (ec);
3337 ig.Emit (OpCodes.Brfalse, is_null_label);
3340 underlying.Emit (ec);
3342 underlying.EmitStatement (ec);
3343 ig.Emit (OpCodes.Br, end_label);
3345 ig.MarkLabel (is_null_label);
3347 null_value.Emit (ec);
3349 ig.MarkLabel (end_label);
3352 public override void Emit (EmitContext ec)
3357 public override void EmitStatement (EmitContext ec)