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 public Constraints Clone ()
161 return new Constraints (name, constraints, loc);
164 GenericParameterAttributes attrs;
165 TypeExpr class_constraint;
166 ArrayList iface_constraints;
167 ArrayList type_param_constraints;
169 Type class_constraint_type;
170 Type[] iface_constraint_types;
171 Type effective_base_type;
176 /// Resolve the constraints - but only resolve things into Expression's, not
177 /// into actual types.
179 public bool Resolve (IResolveContext ec)
184 iface_constraints = new ArrayList ();
185 type_param_constraints = new ArrayList ();
187 foreach (object obj in constraints) {
188 if (HasConstructorConstraint) {
189 Report.Error (401, loc,
190 "The new() constraint must be the last constraint specified");
194 if (obj is SpecialConstraint) {
195 SpecialConstraint sc = (SpecialConstraint) obj;
197 if (sc == SpecialConstraint.Constructor) {
198 if (!HasValueTypeConstraint) {
199 attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
203 Report.Error (451, loc, "The `new()' constraint " +
204 "cannot be used with the `struct' constraint");
208 if ((num_constraints > 0) || HasReferenceTypeConstraint || HasValueTypeConstraint) {
209 Report.Error (449, loc, "The `class' or `struct' " +
210 "constraint must be the first constraint specified");
214 if (sc == SpecialConstraint.ReferenceType)
215 attrs |= GenericParameterAttributes.ReferenceTypeConstraint;
217 attrs |= GenericParameterAttributes.NotNullableValueTypeConstraint;
221 int errors = Report.Errors;
222 FullNamedExpression fn = ((Expression) obj).ResolveAsTypeStep (ec, false);
225 if (errors != Report.Errors)
228 NamespaceEntry.Error_NamespaceNotFound (loc, ((Expression)obj).GetSignatureForError ());
233 ConstructedType cexpr = fn as ConstructedType;
235 if (!cexpr.ResolveConstructedType (ec))
240 expr = ((Expression) obj).ResolveAsTypeTerminal (ec, false);
242 if ((expr == null) || (expr.Type == null))
245 // TODO: It's aleady done in ResolveAsBaseTerminal
246 if (!ec.GenericDeclContainer.AsAccessible (fn.Type, ec.GenericDeclContainer.ModFlags)) {
247 Report.SymbolRelatedToPreviousError (fn.Type);
248 Report.Error (703, loc,
249 "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
250 fn.GetSignatureForError (), ec.GenericDeclContainer.GetSignatureForError ());
254 TypeParameterExpr texpr = expr as TypeParameterExpr;
256 type_param_constraints.Add (expr);
257 else if (expr.IsInterface)
258 iface_constraints.Add (expr);
259 else if (class_constraint != null) {
260 Report.Error (406, loc,
261 "`{0}': the class constraint for `{1}' " +
262 "must come before any other constraints.",
265 } else if (HasReferenceTypeConstraint || HasValueTypeConstraint) {
266 Report.Error (450, loc, "`{0}': cannot specify both " +
267 "a constraint class and the `class' " +
268 "or `struct' constraint", expr.GetSignatureForError ());
271 class_constraint = expr;
276 ArrayList list = new ArrayList ();
277 foreach (TypeExpr iface_constraint in iface_constraints) {
278 foreach (Type type in list) {
279 if (!type.Equals (iface_constraint.Type))
282 Report.Error (405, loc,
283 "Duplicate constraint `{0}' for type " +
284 "parameter `{1}'.", iface_constraint.GetSignatureForError (),
289 list.Add (iface_constraint.Type);
292 foreach (TypeParameterExpr expr in type_param_constraints) {
293 foreach (Type type in list) {
294 if (!type.Equals (expr.Type))
297 Report.Error (405, loc,
298 "Duplicate constraint `{0}' for type " +
299 "parameter `{1}'.", expr.GetSignatureForError (), name);
303 list.Add (expr.Type);
306 iface_constraint_types = new Type [list.Count];
307 list.CopyTo (iface_constraint_types, 0);
309 if (class_constraint != null) {
310 class_constraint_type = class_constraint.Type;
311 if (class_constraint_type == null)
314 if (class_constraint_type.IsSealed) {
315 if (class_constraint_type.IsAbstract)
317 Report.Error (717, loc, "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
318 TypeManager.CSharpName (class_constraint_type));
322 Report.Error (701, loc, "`{0}' is not a valid constraint. A constraint must be an interface, " +
323 "a non-sealed class or a type parameter", TypeManager.CSharpName(class_constraint_type));
328 if ((class_constraint_type == TypeManager.array_type) ||
329 (class_constraint_type == TypeManager.delegate_type) ||
330 (class_constraint_type == TypeManager.enum_type) ||
331 (class_constraint_type == TypeManager.value_type) ||
332 (class_constraint_type == TypeManager.object_type)) {
333 Report.Error (702, loc,
334 "Bound cannot be special class `{0}'",
335 TypeManager.CSharpName (class_constraint_type));
340 if (class_constraint_type != null)
341 effective_base_type = class_constraint_type;
342 else if (HasValueTypeConstraint)
343 effective_base_type = TypeManager.value_type;
345 effective_base_type = TypeManager.object_type;
351 bool CheckTypeParameterConstraints (TypeParameter tparam, Hashtable seen)
353 seen.Add (tparam, true);
355 Constraints constraints = tparam.Constraints;
356 if (constraints == null)
359 if (constraints.HasValueTypeConstraint) {
360 Report.Error (456, loc, "Type parameter `{0}' has " +
361 "the `struct' constraint, so it cannot " +
362 "be used as a constraint for `{1}'",
367 if (constraints.type_param_constraints == null)
370 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
371 if (seen.Contains (expr.TypeParameter)) {
372 Report.Error (454, loc, "Circular constraint " +
373 "dependency involving `{0}' and `{1}'",
374 tparam.Name, expr.Name);
378 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
386 /// Resolve the constraints into actual types.
388 public bool ResolveTypes (IResolveContext ec)
393 resolved_types = true;
395 foreach (object obj in constraints) {
396 ConstructedType cexpr = obj as ConstructedType;
400 if (!cexpr.CheckConstraints (ec))
404 foreach (TypeParameterExpr expr in type_param_constraints) {
405 Hashtable seen = new Hashtable ();
406 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
410 for (int i = 0; i < iface_constraints.Count; ++i) {
411 TypeExpr iface_constraint = (TypeExpr) iface_constraints [i];
412 iface_constraint = iface_constraint.ResolveAsTypeTerminal (ec, false);
413 if (iface_constraint == null)
415 iface_constraints [i] = iface_constraint;
418 if (class_constraint != null) {
419 class_constraint = class_constraint.ResolveAsTypeTerminal (ec, false);
420 if (class_constraint == null)
428 /// Check whether there are no conflicts in our type parameter constraints.
430 /// This is an example:
434 /// where U : T, struct
436 public bool CheckDependencies ()
438 foreach (TypeParameterExpr expr in type_param_constraints) {
439 if (!CheckDependencies (expr.TypeParameter))
446 bool CheckDependencies (TypeParameter tparam)
448 Constraints constraints = tparam.Constraints;
449 if (constraints == null)
452 if (HasValueTypeConstraint && constraints.HasClassConstraint) {
453 Report.Error (455, loc, "Type parameter `{0}' inherits " +
454 "conflicting constraints `{1}' and `{2}'",
455 name, TypeManager.CSharpName (constraints.ClassConstraint),
460 if (HasClassConstraint && constraints.HasClassConstraint) {
461 Type t1 = ClassConstraint;
462 TypeExpr e1 = class_constraint;
463 Type t2 = constraints.ClassConstraint;
464 TypeExpr e2 = constraints.class_constraint;
466 if (!Convert.ImplicitReferenceConversionExists (e1, t2) &&
467 !Convert.ImplicitReferenceConversionExists (e2, t1)) {
468 Report.Error (455, loc,
469 "Type parameter `{0}' inherits " +
470 "conflicting constraints `{1}' and `{2}'",
471 name, TypeManager.CSharpName (t1), TypeManager.CSharpName (t2));
476 if (constraints.type_param_constraints == null)
479 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
480 if (!CheckDependencies (expr.TypeParameter))
487 public override GenericParameterAttributes Attributes {
488 get { return attrs; }
491 public override bool HasClassConstraint {
492 get { return class_constraint != null; }
495 public override Type ClassConstraint {
496 get { return class_constraint_type; }
499 public override Type[] InterfaceConstraints {
500 get { return iface_constraint_types; }
503 public override Type EffectiveBaseClass {
504 get { return effective_base_type; }
507 public bool IsSubclassOf (Type t)
509 if ((class_constraint_type != null) &&
510 class_constraint_type.IsSubclassOf (t))
513 if (iface_constraint_types == null)
516 foreach (Type iface in iface_constraint_types) {
517 if (TypeManager.IsSubclassOf (iface, t))
524 public Location Location {
531 /// This is used when we're implementing a generic interface method.
532 /// Each method type parameter in implementing method must have the same
533 /// constraints than the corresponding type parameter in the interface
534 /// method. To do that, we're called on each of the implementing method's
537 public bool CheckInterfaceMethod (GenericConstraints gc)
539 if (gc.Attributes != attrs)
542 if (HasClassConstraint != gc.HasClassConstraint)
544 if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
547 int gc_icount = gc.InterfaceConstraints != null ?
548 gc.InterfaceConstraints.Length : 0;
549 int icount = InterfaceConstraints != null ?
550 InterfaceConstraints.Length : 0;
552 if (gc_icount != icount)
555 foreach (Type iface in gc.InterfaceConstraints) {
557 foreach (Type check in InterfaceConstraints) {
558 if (TypeManager.IsEqual (iface, check)) {
571 public void VerifyClsCompliance ()
573 if (class_constraint_type != null && !AttributeTester.IsClsCompliant (class_constraint_type))
574 Warning_ConstrainIsNotClsCompliant (class_constraint_type, class_constraint.Location);
576 if (iface_constraint_types != null) {
577 for (int i = 0; i < iface_constraint_types.Length; ++i) {
578 if (!AttributeTester.IsClsCompliant (iface_constraint_types [i]))
579 Warning_ConstrainIsNotClsCompliant (iface_constraint_types [i],
580 ((TypeExpr)iface_constraints [i]).Location);
585 void Warning_ConstrainIsNotClsCompliant (Type t, Location loc)
587 Report.SymbolRelatedToPreviousError (t);
588 Report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
589 TypeManager.CSharpName (t));
594 /// A type parameter from a generic type definition.
596 public class TypeParameter : MemberCore, IMemberContainer {
599 GenericConstraints gc;
600 Constraints constraints;
602 GenericTypeParameterBuilder type;
603 MemberCache member_cache;
605 public TypeParameter (DeclSpace parent, DeclSpace decl, string name,
606 Constraints constraints, Attributes attrs, Location loc)
607 : base (parent, new MemberName (name, loc), attrs)
611 this.constraints = constraints;
615 public GenericConstraints GenericConstraints {
616 get { return gc != null ? gc : constraints; }
619 public Constraints Constraints {
620 get { return constraints; }
623 public DeclSpace DeclSpace {
632 /// This is the first method which is called during the resolving
633 /// process; we're called immediately after creating the type parameters
634 /// with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
637 /// We're either called from TypeContainer.DefineType() or from
638 /// GenericMethod.Define() (called from Method.Define()).
640 public void Define (GenericTypeParameterBuilder type)
642 if (this.type != null)
643 throw new InvalidOperationException ();
646 TypeManager.AddTypeParameter (type, this);
650 /// This is the second method which is called during the resolving
651 /// process - in case of class type parameters, we're called from
652 /// TypeContainer.ResolveType() - after it resolved the class'es
653 /// base class and interfaces. For method type parameters, we're
654 /// called immediately after Define().
656 /// We're just resolving the constraints into expressions here, we
657 /// don't resolve them into actual types.
659 /// Note that in the special case of partial generic classes, we may be
660 /// called _before_ Define() and we may also be called multiple types.
662 public bool Resolve (DeclSpace ds)
664 if (constraints != null) {
665 if (!constraints.Resolve (ds)) {
675 /// This is the third method which is called during the resolving
676 /// process. We're called immediately after calling DefineConstraints()
677 /// on all of the current class'es type parameters.
679 /// Our job is to resolve the constraints to actual types.
681 /// Note that we may have circular dependencies on type parameters - this
682 /// is why Resolve() and ResolveType() are separate.
684 public bool ResolveType (IResolveContext ec)
686 if (constraints != null) {
687 if (!constraints.ResolveTypes (ec)) {
697 /// This is the fourth and last method which is called during the resolving
698 /// process. We're called after everything is fully resolved and actually
699 /// register the constraints with SRE and the TypeManager.
701 public bool DefineType (IResolveContext ec)
703 return DefineType (ec, null, null, false);
707 /// This is the fith and last method which is called during the resolving
708 /// process. We're called after everything is fully resolved and actually
709 /// register the constraints with SRE and the TypeManager.
711 /// The `builder', `implementing' and `is_override' arguments are only
712 /// applicable to method type parameters.
714 public bool DefineType (IResolveContext ec, MethodBuilder builder,
715 MethodInfo implementing, bool is_override)
717 if (!ResolveType (ec))
720 if (implementing != null) {
721 if (is_override && (constraints != null)) {
722 Report.Error (460, loc,
723 "`{0}': Cannot specify constraints for overrides or explicit interface implementation methods",
724 TypeManager.CSharpSignature (builder));
728 MethodBase mb = TypeManager.DropGenericMethodArguments (implementing);
730 int pos = type.GenericParameterPosition;
731 Type mparam = mb.GetGenericArguments () [pos];
732 GenericConstraints temp_gc = ReflectionConstraints.GetConstraints (mparam);
735 gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
736 else if (constraints != null)
737 gc = new InflatedConstraints (constraints, implementing.DeclaringType);
740 if (constraints != null) {
743 else if (!constraints.CheckInterfaceMethod (gc))
746 if (!is_override && (temp_gc != null))
751 Report.SymbolRelatedToPreviousError (implementing);
754 425, loc, "The constraints for type " +
755 "parameter `{0}' of method `{1}' must match " +
756 "the constraints for type parameter `{2}' " +
757 "of interface method `{3}'. Consider using " +
758 "an explicit interface implementation instead",
759 Name, TypeManager.CSharpSignature (builder),
760 TypeManager.CSharpName (mparam), TypeManager.CSharpSignature (mb));
763 } else if (DeclSpace is CompilerGeneratedClass) {
764 TypeParameter[] tparams = DeclSpace.TypeParameters;
765 Type[] types = new Type [tparams.Length];
766 for (int i = 0; i < tparams.Length; i++)
767 types [i] = tparams [i].Type;
769 if (constraints != null)
770 gc = new InflatedConstraints (constraints, types);
772 gc = (GenericConstraints) constraints;
778 if (gc.HasClassConstraint)
779 type.SetBaseTypeConstraint (gc.ClassConstraint);
781 type.SetInterfaceConstraints (gc.InterfaceConstraints);
782 type.SetGenericParameterAttributes (gc.Attributes);
783 TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
789 /// Check whether there are no conflicts in our type parameter constraints.
791 /// This is an example:
795 /// where U : T, struct
797 public bool CheckDependencies ()
799 if (constraints != null)
800 return constraints.CheckDependencies ();
806 /// This is called for each part of a partial generic type definition.
808 /// If `new_constraints' is not null and we don't already have constraints,
809 /// they become our constraints. If we already have constraints, we must
810 /// check that they're the same.
813 public bool UpdateConstraints (IResolveContext ec, Constraints new_constraints)
816 throw new InvalidOperationException ();
818 if (new_constraints == null)
821 if (!new_constraints.Resolve (ec))
823 if (!new_constraints.ResolveTypes (ec))
826 if (constraints != null)
827 return constraints.CheckInterfaceMethod (new_constraints);
829 constraints = new_constraints;
833 public void EmitAttributes ()
835 if (OptAttributes != null)
836 OptAttributes.Emit ();
839 public override string DocCommentHeader {
841 throw new InvalidOperationException (
842 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
850 public override bool Define ()
855 public override void ApplyAttributeBuilder (Attribute a,
856 CustomAttributeBuilder cb)
858 type.SetCustomAttribute (cb);
861 public override AttributeTargets AttributeTargets {
863 return (AttributeTargets) AttributeTargets.GenericParameter;
867 public override string[] ValidAttributeTargets {
869 return new string [] { "type parameter" };
877 string IMemberContainer.Name {
881 MemberCache IMemberContainer.BaseCache {
886 if (gc.EffectiveBaseClass.BaseType == null)
889 return TypeManager.LookupMemberCache (gc.EffectiveBaseClass.BaseType);
893 bool IMemberContainer.IsInterface {
894 get { return false; }
897 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
899 return FindMembers (mt, bf, null, null);
902 public MemberCache MemberCache {
904 if (member_cache != null)
910 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
911 member_cache = new MemberCache (this, gc.EffectiveBaseClass, ifaces);
917 public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
918 MemberFilter filter, object criteria)
921 return MemberList.Empty;
923 ArrayList members = new ArrayList ();
925 if (gc.HasClassConstraint) {
926 MemberList list = TypeManager.FindMembers (
927 gc.ClassConstraint, mt, bf, filter, criteria);
929 members.AddRange (list);
932 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
933 foreach (Type t in ifaces) {
934 MemberList list = TypeManager.FindMembers (
935 t, mt, bf, filter, criteria);
937 members.AddRange (list);
940 return new MemberList (members);
943 public bool IsSubclassOf (Type t)
948 if (constraints != null)
949 return constraints.IsSubclassOf (t);
954 public override string ToString ()
956 return "TypeParameter[" + name + "]";
959 public static string GetSignatureForError (TypeParameter[] tp)
961 if (tp == null || tp.Length == 0)
964 StringBuilder sb = new StringBuilder ("<");
965 for (int i = 0; i < tp.Length; ++i) {
968 sb.Append (tp[i].GetSignatureForError ());
971 return sb.ToString ();
974 public void InflateConstraints (Type declaring)
976 if (constraints != null)
977 gc = new InflatedConstraints (constraints, declaring);
980 protected class InflatedConstraints : GenericConstraints
982 GenericConstraints gc;
984 Type class_constraint;
985 Type[] iface_constraints;
988 public InflatedConstraints (GenericConstraints gc, Type declaring)
989 : this (gc, TypeManager.GetTypeArguments (declaring))
992 public InflatedConstraints (GenericConstraints gc, Type[] dargs)
997 ArrayList list = new ArrayList ();
998 if (gc.HasClassConstraint)
999 list.Add (inflate (gc.ClassConstraint));
1000 foreach (Type iface in gc.InterfaceConstraints)
1001 list.Add (inflate (iface));
1003 bool has_class_constr = false;
1004 if (list.Count > 0) {
1005 Type first = (Type) list [0];
1006 has_class_constr = !first.IsInterface && !first.IsGenericParameter;
1009 if ((list.Count > 0) && has_class_constr) {
1010 class_constraint = (Type) list [0];
1011 iface_constraints = new Type [list.Count - 1];
1012 list.CopyTo (1, iface_constraints, 0, list.Count - 1);
1014 iface_constraints = new Type [list.Count];
1015 list.CopyTo (iface_constraints, 0);
1018 if (HasValueTypeConstraint)
1019 base_type = TypeManager.value_type;
1020 else if (class_constraint != null)
1021 base_type = class_constraint;
1023 base_type = TypeManager.object_type;
1026 Type inflate (Type t)
1030 if (t.IsGenericParameter)
1031 return dargs [t.GenericParameterPosition];
1032 if (t.IsGenericType) {
1033 Type[] args = t.GetGenericArguments ();
1034 Type[] inflated = new Type [args.Length];
1036 for (int i = 0; i < args.Length; i++)
1037 inflated [i] = inflate (args [i]);
1039 t = t.GetGenericTypeDefinition ();
1040 t = t.MakeGenericType (inflated);
1046 public override string TypeParameter {
1047 get { return gc.TypeParameter; }
1050 public override GenericParameterAttributes Attributes {
1051 get { return gc.Attributes; }
1054 public override Type ClassConstraint {
1055 get { return class_constraint; }
1058 public override Type EffectiveBaseClass {
1059 get { return base_type; }
1062 public override Type[] InterfaceConstraints {
1063 get { return iface_constraints; }
1069 /// A TypeExpr which already resolved to a type parameter.
1071 public class TypeParameterExpr : TypeExpr {
1072 TypeParameter type_parameter;
1074 public override string Name {
1076 return type_parameter.Name;
1080 public override string FullName {
1082 return type_parameter.Name;
1086 public TypeParameter TypeParameter {
1088 return type_parameter;
1092 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1094 this.type_parameter = type_parameter;
1098 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1100 type = type_parameter.Type;
1105 public override bool IsInterface {
1106 get { return false; }
1109 public override bool CheckAccessLevel (DeclSpace ds)
1114 public void Error_CannotUseAsUnmanagedType (Location loc)
1116 Report.Error (-203, loc, "Can not use type parameter as unmanaged type");
1121 /// Tracks the type arguments when instantiating a generic type. We're used in
1122 /// ConstructedType.
1124 public class TypeArguments {
1125 public readonly Location Location;
1132 public TypeArguments (Location loc)
1134 args = new ArrayList ();
1135 this.Location = loc;
1138 public TypeArguments (int dimension, Location loc)
1140 this.dimension = dimension;
1141 this.Location = loc;
1144 public void Add (Expression type)
1147 throw new InvalidOperationException ();
1152 public void Add (TypeArguments new_args)
1155 throw new InvalidOperationException ();
1157 args.AddRange (new_args.args);
1161 /// We're used during the parsing process: the parser can't distinguish
1162 /// between type parameters and type arguments. Because of that, the
1163 /// parser creates a `MemberName' with `TypeArguments' for both cases and
1164 /// in case of a generic type definition, we call GetDeclarations().
1166 public TypeParameterName[] GetDeclarations ()
1168 TypeParameterName[] ret = new TypeParameterName [args.Count];
1169 for (int i = 0; i < args.Count; i++) {
1170 TypeParameterName name = args [i] as TypeParameterName;
1175 SimpleName sn = args [i] as SimpleName;
1177 ret [i] = new TypeParameterName (sn.Name, null, sn.Location);
1181 Report.Error (81, Location, "Type parameter declaration " +
1182 "must be an identifier not a type");
1189 /// We may only be used after Resolve() is called and return the fully
1192 public Type[] Arguments {
1198 public bool HasTypeArguments {
1200 return has_type_args;
1213 public bool IsUnbound {
1215 return dimension > 0;
1219 public override string ToString ()
1221 StringBuilder s = new StringBuilder ();
1224 for (int i = 0; i < count; i++){
1226 // FIXME: Use TypeManager.CSharpname once we have the type
1229 s.Append (args [i].ToString ());
1233 return s.ToString ();
1236 public string GetSignatureForError()
1238 StringBuilder sb = new StringBuilder();
1239 for (int i = 0; i < Count; ++i)
1241 Expression expr = (Expression)args [i];
1242 sb.Append(expr.GetSignatureForError());
1246 return sb.ToString();
1250 /// Resolve the type arguments.
1252 public bool Resolve (IResolveContext ec)
1254 int count = args.Count;
1257 atypes = new Type [count];
1259 for (int i = 0; i < count; i++){
1260 TypeExpr te = ((Expression) args [i]).ResolveAsTypeTerminal (ec, false);
1266 atypes[i] = te.Type;
1268 if (te is TypeParameterExpr) {
1269 has_type_args = true;
1273 if (te.Type.IsSealed && te.Type.IsAbstract) {
1274 Report.Error (718, Location, "`{0}': static classes cannot be used as generic arguments",
1275 te.GetSignatureForError ());
1279 if (te.Type.IsPointer) {
1280 Report.Error (306, Location, "The type `{0}' may not be used " +
1281 "as a type argument", TypeManager.CSharpName (te.Type));
1285 if (te.Type == TypeManager.void_type) {
1286 Expression.Error_VoidInvalidInTheContext (Location);
1293 public TypeArguments Clone ()
1295 TypeArguments copy = new TypeArguments (Location);
1296 foreach (Expression ta in args)
1303 public class TypeParameterName : SimpleName
1305 Attributes attributes;
1307 public TypeParameterName (string name, Attributes attrs, Location loc)
1313 public Attributes OptAttributes {
1321 /// An instantiation of a generic type.
1323 public class ConstructedType : TypeExpr {
1325 FullNamedExpression name;
1327 Type[] gen_params, atypes;
1331 /// Instantiate the generic type `fname' with the type arguments `args'.
1333 public ConstructedType (FullNamedExpression fname, TypeArguments args, Location l)
1339 eclass = ExprClass.Type;
1340 full_name = name + "<" + args.ToString () + ">";
1343 protected ConstructedType (TypeArguments args, Location l)
1348 eclass = ExprClass.Type;
1351 protected ConstructedType (TypeParameter[] type_params, Location l)
1355 args = new TypeArguments (l);
1356 foreach (TypeParameter type_param in type_params)
1357 args.Add (new TypeParameterExpr (type_param, l));
1359 eclass = ExprClass.Type;
1363 /// This is used to construct the `this' type inside a generic type definition.
1365 public ConstructedType (Type t, TypeParameter[] type_params, Location l)
1366 : this (type_params, l)
1368 gt = t.GetGenericTypeDefinition ();
1370 this.name = new TypeExpression (gt, l);
1371 full_name = gt.FullName + "<" + args.ToString () + ">";
1375 /// Instantiate the generic type `t' with the type arguments `args'.
1376 /// Use this constructor if you already know the fully resolved
1379 public ConstructedType (Type t, TypeArguments args, Location l)
1382 gt = t.GetGenericTypeDefinition ();
1384 this.name = new TypeExpression (gt, l);
1385 full_name = gt.FullName + "<" + args.ToString () + ">";
1388 public TypeArguments TypeArguments {
1389 get { return args; }
1392 public override string GetSignatureForError ()
1394 return TypeManager.RemoveGenericArity (gt.FullName) + "<" + args.GetSignatureForError () + ">";
1397 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1399 if (!ResolveConstructedType (ec))
1406 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1407 /// after fully resolving the constructed type.
1409 public bool CheckConstraints (IResolveContext ec)
1411 return ConstraintChecker.CheckConstraints (ec, gt, gen_params, atypes, loc);
1415 /// Resolve the constructed type, but don't check the constraints.
1417 public bool ResolveConstructedType (IResolveContext ec)
1421 // If we already know the fully resolved generic type.
1423 return DoResolveType (ec);
1429 Report.Error (246, loc, "Cannot find type `{0}'<...>", Name);
1433 num_args = TypeManager.GetNumberOfTypeArguments (t);
1434 if (num_args == 0) {
1435 Report.Error (308, loc,
1436 "The non-generic type `{0}' cannot " +
1437 "be used with type arguments.",
1438 TypeManager.CSharpName (t));
1442 gt = t.GetGenericTypeDefinition ();
1443 return DoResolveType (ec);
1446 bool DoResolveType (IResolveContext ec)
1449 // Resolve the arguments.
1451 if (args.Resolve (ec) == false)
1454 gen_params = gt.GetGenericArguments ();
1455 atypes = args.Arguments;
1457 if (atypes.Length != gen_params.Length) {
1458 Report.Error (305, loc,
1459 "Using the generic type `{0}' " +
1460 "requires {1} type arguments",
1461 TypeManager.CSharpName (gt),
1462 gen_params.Length.ToString ());
1467 // Now bind the parameters.
1469 type = gt.MakeGenericType (atypes);
1473 public Expression GetSimpleName (EmitContext ec)
1478 public override bool CheckAccessLevel (DeclSpace ds)
1480 return ds.CheckAccessLevel (gt);
1483 public override bool AsAccessible (DeclSpace ds, int flags)
1485 foreach (Type t in atypes) {
1486 if (!ds.AsAccessible (t, flags))
1490 return ds.AsAccessible (gt, flags);
1493 public override bool IsClass {
1494 get { return gt.IsClass; }
1497 public override bool IsValueType {
1498 get { return gt.IsValueType; }
1501 public override bool IsInterface {
1502 get { return gt.IsInterface; }
1505 public override bool IsSealed {
1506 get { return gt.IsSealed; }
1509 public override bool Equals (object obj)
1511 ConstructedType cobj = obj as ConstructedType;
1515 if ((type == null) || (cobj.type == null))
1518 return type == cobj.type;
1521 public override int GetHashCode ()
1523 return base.GetHashCode ();
1526 public override string Name {
1532 public override string FullName {
1539 public abstract class ConstraintChecker
1541 protected readonly Type[] gen_params;
1542 protected readonly Type[] atypes;
1543 protected readonly Location loc;
1545 protected ConstraintChecker (Type[] gen_params, Type[] atypes, Location loc)
1547 this.gen_params = gen_params;
1548 this.atypes = atypes;
1553 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1554 /// after fully resolving the constructed type.
1556 public bool CheckConstraints (IResolveContext ec)
1558 for (int i = 0; i < gen_params.Length; i++) {
1559 if (!CheckConstraints (ec, i))
1566 protected bool CheckConstraints (IResolveContext ec, int index)
1568 Type atype = atypes [index];
1569 Type ptype = gen_params [index];
1574 Expression aexpr = new EmptyExpression (atype);
1576 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1580 bool is_class, is_struct;
1581 if (atype.IsGenericParameter) {
1582 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1584 if (agc is Constraints)
1585 ((Constraints) agc).Resolve (ec);
1586 is_class = agc.IsReferenceType;
1587 is_struct = agc.IsValueType;
1589 is_class = is_struct = false;
1594 if (!atype.IsGenericType)
1596 is_class = atype.IsClass || atype.IsInterface;
1597 is_struct = atype.IsValueType && !TypeManager.IsNullableType (atype);
1601 // First, check the `class' and `struct' constraints.
1603 if (gc.HasReferenceTypeConstraint && !is_class) {
1604 Report.Error (452, loc, "The type `{0}' must be " +
1605 "a reference type in order to use it " +
1606 "as type parameter `{1}' in the " +
1607 "generic type or method `{2}'.",
1608 TypeManager.CSharpName (atype),
1609 TypeManager.CSharpName (ptype),
1610 GetSignatureForError ());
1612 } else if (gc.HasValueTypeConstraint && !is_struct) {
1613 Report.Error (453, loc, "The type `{0}' must be a " +
1614 "non-nullable value type in order to use it " +
1615 "as type parameter `{1}' in the " +
1616 "generic type or method `{2}'.",
1617 TypeManager.CSharpName (atype),
1618 TypeManager.CSharpName (ptype),
1619 GetSignatureForError ());
1624 // The class constraint comes next.
1626 if (gc.HasClassConstraint) {
1627 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint))
1632 // Now, check the interface constraints.
1634 if (gc.InterfaceConstraints != null) {
1635 foreach (Type it in gc.InterfaceConstraints) {
1636 if (!CheckConstraint (ec, ptype, aexpr, it))
1642 // Finally, check the constructor constraint.
1645 if (!gc.HasConstructorConstraint)
1648 if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
1651 if (HasDefaultConstructor (atype))
1654 Report_SymbolRelatedToPreviousError ();
1655 Report.SymbolRelatedToPreviousError (atype);
1656 Report.Error (310, loc, "The type `{0}' must have a public " +
1657 "parameterless constructor in order to use it " +
1658 "as parameter `{1}' in the generic type or " +
1660 TypeManager.CSharpName (atype),
1661 TypeManager.CSharpName (ptype),
1662 GetSignatureForError ());
1666 protected bool CheckConstraint (IResolveContext ec, Type ptype, Expression expr,
1669 if (TypeManager.HasGenericArguments (ctype)) {
1670 Type[] types = TypeManager.GetTypeArguments (ctype);
1672 TypeArguments new_args = new TypeArguments (loc);
1674 for (int i = 0; i < types.Length; i++) {
1677 if (t.IsGenericParameter) {
1678 int pos = t.GenericParameterPosition;
1681 new_args.Add (new TypeExpression (t, loc));
1684 TypeExpr ct = new ConstructedType (ctype, new_args, loc);
1685 if (ct.ResolveAsTypeStep (ec, false) == null)
1688 } else if (ctype.IsGenericParameter) {
1689 int pos = ctype.GenericParameterPosition;
1690 ctype = atypes [pos];
1693 if (Convert.ImplicitStandardConversionExists (expr, ctype))
1696 Error_TypeMustBeConvertible (expr.Type, ctype, ptype);
1700 bool HasDefaultConstructor (Type atype)
1702 if (atype.IsAbstract)
1706 atype = TypeManager.DropGenericTypeArguments (atype);
1707 if (atype is TypeBuilder) {
1708 TypeContainer tc = TypeManager.LookupTypeContainer (atype);
1709 if (tc.InstanceConstructors == null) {
1710 atype = atype.BaseType;
1714 foreach (Constructor c in tc.InstanceConstructors) {
1715 if ((c.ModFlags & Modifiers.PUBLIC) == 0)
1717 if ((c.Parameters.FixedParameters != null) &&
1718 (c.Parameters.FixedParameters.Length != 0))
1720 if (c.Parameters.HasArglist || c.Parameters.HasParams)
1727 TypeParameter tparam = TypeManager.LookupTypeParameter (atype);
1728 if (tparam != null) {
1729 if (tparam.GenericConstraints == null)
1732 return tparam.GenericConstraints.HasConstructorConstraint;
1735 MemberList list = TypeManager.FindMembers (
1736 atype, MemberTypes.Constructor,
1737 BindingFlags.Public | BindingFlags.Instance |
1738 BindingFlags.DeclaredOnly, null, null);
1740 if (atype.IsAbstract || (list == null))
1743 foreach (MethodBase mb in list) {
1744 ParameterData pd = TypeManager.GetParameterData (mb);
1745 if ((pd.Count == 0) && mb.IsPublic && !mb.IsStatic)
1752 protected abstract string GetSignatureForError ();
1753 protected abstract void Report_SymbolRelatedToPreviousError ();
1755 void Error_TypeMustBeConvertible (Type atype, Type gc, Type ptype)
1757 Report_SymbolRelatedToPreviousError ();
1758 Report.SymbolRelatedToPreviousError (atype);
1759 Report.Error (309, loc,
1760 "The type `{0}' must be convertible to `{1}' in order to " +
1761 "use it as parameter `{2}' in the generic type or method `{3}'",
1762 TypeManager.CSharpName (atype), TypeManager.CSharpName (gc),
1763 TypeManager.CSharpName (ptype), GetSignatureForError ());
1766 public static bool CheckConstraints (EmitContext ec, MethodBase definition,
1767 MethodBase instantiated, Location loc)
1769 MethodConstraintChecker checker = new MethodConstraintChecker (
1770 definition, definition.GetGenericArguments (),
1771 instantiated.GetGenericArguments (), loc);
1773 return checker.CheckConstraints (ec);
1776 public static bool CheckConstraints (IResolveContext ec, Type gt, Type[] gen_params,
1777 Type[] atypes, Location loc)
1779 TypeConstraintChecker checker = new TypeConstraintChecker (
1780 gt, gen_params, atypes, loc);
1782 return checker.CheckConstraints (ec);
1785 protected class MethodConstraintChecker : ConstraintChecker
1787 MethodBase definition;
1789 public MethodConstraintChecker (MethodBase definition, Type[] gen_params,
1790 Type[] atypes, Location loc)
1791 : base (gen_params, atypes, loc)
1793 this.definition = definition;
1796 protected override string GetSignatureForError ()
1798 return TypeManager.CSharpSignature (definition);
1801 protected override void Report_SymbolRelatedToPreviousError ()
1803 Report.SymbolRelatedToPreviousError (definition);
1807 protected class TypeConstraintChecker : ConstraintChecker
1811 public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
1813 : base (gen_params, atypes, loc)
1818 protected override string GetSignatureForError ()
1820 return TypeManager.CSharpName (gt);
1823 protected override void Report_SymbolRelatedToPreviousError ()
1825 Report.SymbolRelatedToPreviousError (gt);
1831 /// A generic method definition.
1833 public class GenericMethod : DeclSpace
1835 Expression return_type;
1836 Parameters parameters;
1838 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
1839 Expression return_type, Parameters parameters)
1840 : base (ns, parent, name, null)
1842 this.return_type = return_type;
1843 this.parameters = parameters;
1846 public override TypeBuilder DefineType ()
1848 throw new Exception ();
1851 public override bool Define ()
1853 for (int i = 0; i < TypeParameters.Length; i++)
1854 if (!TypeParameters [i].Resolve (this))
1861 /// Define and resolve the type parameters.
1862 /// We're called from Method.Define().
1864 public bool Define (MethodBuilder mb, ToplevelBlock block)
1866 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1867 string[] snames = new string [names.Length];
1868 for (int i = 0; i < names.Length; i++) {
1869 string type_argument_name = names[i].Name;
1870 Parameter p = parameters.GetParameterByName (type_argument_name);
1872 Error_ParameterNameCollision (p.Location, type_argument_name, "method parameter");
1875 if (block != null) {
1876 LocalInfo li = (LocalInfo)block.Variables[type_argument_name];
1878 Error_ParameterNameCollision (li.Location, type_argument_name, "local variable");
1882 snames[i] = type_argument_name;
1885 GenericTypeParameterBuilder[] gen_params = mb.DefineGenericParameters (snames);
1886 for (int i = 0; i < TypeParameters.Length; i++)
1887 TypeParameters [i].Define (gen_params [i]);
1892 for (int i = 0; i < TypeParameters.Length; i++) {
1893 if (!TypeParameters [i].ResolveType (this))
1900 static void Error_ParameterNameCollision (Location loc, string name, string collisionWith)
1902 Report.Error (412, loc, "The type parameter name `{0}' is the same as `{1}'",
1903 name, collisionWith);
1907 /// We're called from MethodData.Define() after creating the MethodBuilder.
1909 public bool DefineType (EmitContext ec, MethodBuilder mb,
1910 MethodInfo implementing, bool is_override)
1912 for (int i = 0; i < TypeParameters.Length; i++)
1913 if (!TypeParameters [i].DefineType (
1914 ec, mb, implementing, is_override))
1918 foreach (Parameter p in parameters.FixedParameters){
1919 if (!p.Resolve (ec))
1922 if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec, false) == null))
1928 public void EmitAttributes ()
1930 for (int i = 0; i < TypeParameters.Length; i++)
1931 TypeParameters [i].EmitAttributes ();
1933 if (OptAttributes != null)
1934 OptAttributes.Emit ();
1937 public override bool DefineMembers ()
1942 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1943 MemberFilter filter, object criteria)
1945 throw new Exception ();
1948 public override MemberCache MemberCache {
1954 public override AttributeTargets AttributeTargets {
1956 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1960 public override string DocCommentHeader {
1961 get { return "M:"; }
1964 public new void VerifyClsCompliance ()
1966 foreach (TypeParameter tp in TypeParameters) {
1967 if (tp.Constraints == null)
1970 tp.Constraints.VerifyClsCompliance ();
1975 public class DefaultValueExpression : Expression
1979 public DefaultValueExpression (Expression expr, Location loc)
1985 public override Expression DoResolve (EmitContext ec)
1987 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
1993 if (type == TypeManager.void_type) {
1994 Error_VoidInvalidInTheContext (loc);
1998 if (type.IsGenericParameter)
2000 GenericConstraints constraints = TypeManager.GetTypeParameterConstraints(type);
2001 if (constraints != null && constraints.IsReferenceType)
2002 return new NullDefault (new NullLiteral (Location), type);
2006 Constant c = New.Constantify(type);
2008 return new NullDefault (c, type);
2010 if (!TypeManager.IsValueType (type))
2011 return new NullDefault (new NullLiteral (Location), type);
2013 eclass = ExprClass.Variable;
2017 public override void Emit (EmitContext ec)
2019 LocalTemporary temp_storage = new LocalTemporary(type);
2021 temp_storage.AddressOf(ec, AddressOp.LoadStore);
2022 ec.ig.Emit(OpCodes.Initobj, type);
2023 temp_storage.Emit(ec);
2027 public class NullableType : TypeExpr
2029 Expression underlying;
2031 public NullableType (Expression underlying, Location l)
2033 this.underlying = underlying;
2036 eclass = ExprClass.Type;
2039 public NullableType (Type type, Location loc)
2040 : this (new TypeExpression (type, loc), loc)
2043 public override string Name {
2044 get { return underlying.ToString () + "?"; }
2047 public override string FullName {
2048 get { return underlying.ToString () + "?"; }
2051 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
2053 TypeArguments args = new TypeArguments (loc);
2054 args.Add (underlying);
2056 ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
2057 return ctype.ResolveAsTypeTerminal (ec, false);
2061 public partial class TypeManager
2064 // A list of core types that the compiler requires or uses
2066 static public Type activator_type;
2067 static public Type generic_ilist_type;
2068 static public Type generic_icollection_type;
2069 static public Type generic_ienumerator_type;
2070 static public Type generic_ienumerable_type;
2071 static public Type generic_nullable_type;
2074 // These methods are called by code generated by the compiler
2076 static public MethodInfo activator_create_instance;
2078 static void InitGenericCoreTypes ()
2080 activator_type = CoreLookupType ("System", "Activator");
2082 generic_ilist_type = CoreLookupType (
2083 "System.Collections.Generic", "IList", 1);
2084 generic_icollection_type = CoreLookupType (
2085 "System.Collections.Generic", "ICollection", 1);
2086 generic_ienumerator_type = CoreLookupType (
2087 "System.Collections.Generic", "IEnumerator", 1);
2088 generic_ienumerable_type = CoreLookupType (
2089 "System.Collections.Generic", "IEnumerable", 1);
2090 generic_nullable_type = CoreLookupType (
2091 "System", "Nullable", 1);
2094 static void InitGenericCodeHelpers ()
2097 Type [] type_arg = { type_type };
2098 activator_create_instance = GetMethod (
2099 activator_type, "CreateInstance", type_arg);
2102 static Type CoreLookupType (string ns, string name, int arity)
2104 return CoreLookupType (ns, MemberName.MakeName (name, arity));
2107 public static TypeContainer LookupGenericTypeContainer (Type t)
2109 t = DropGenericTypeArguments (t);
2110 return LookupTypeContainer (t);
2113 public static GenericConstraints GetTypeParameterConstraints (Type t)
2115 if (!t.IsGenericParameter)
2116 throw new InvalidOperationException ();
2118 TypeParameter tparam = LookupTypeParameter (t);
2120 return tparam.GenericConstraints;
2122 return ReflectionConstraints.GetConstraints (t);
2126 /// Check whether `a' and `b' may become equal generic types.
2127 /// The algorithm to do that is a little bit complicated.
2129 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_inferred,
2130 Type[] method_inferred)
2132 if (a.IsGenericParameter) {
2134 // If a is an array of a's type, they may never
2138 b = b.GetElementType ();
2144 // If b is a generic parameter or an actual type,
2145 // they may become equal:
2147 // class X<T,U> : I<T>, I<U>
2148 // class X<T> : I<T>, I<float>
2150 if (b.IsGenericParameter || !b.IsGenericType) {
2151 int pos = a.GenericParameterPosition;
2152 Type[] args = a.DeclaringMethod != null ? method_inferred : class_inferred;
2153 if (args [pos] == null) {
2158 return args [pos] == a;
2162 // We're now comparing a type parameter with a
2163 // generic instance. They may become equal unless
2164 // the type parameter appears anywhere in the
2165 // generic instance:
2167 // class X<T,U> : I<T>, I<X<U>>
2168 // -> error because you could instanciate it as
2171 // class X<T> : I<T>, I<X<T>> -> ok
2174 Type[] bargs = GetTypeArguments (b);
2175 for (int i = 0; i < bargs.Length; i++) {
2176 if (a.Equals (bargs [i]))
2183 if (b.IsGenericParameter)
2184 return MayBecomeEqualGenericTypes (b, a, class_inferred, method_inferred);
2187 // At this point, neither a nor b are a type parameter.
2189 // If one of them is a generic instance, let
2190 // MayBecomeEqualGenericInstances() compare them (if the
2191 // other one is not a generic instance, they can never
2195 if (a.IsGenericType || b.IsGenericType)
2196 return MayBecomeEqualGenericInstances (a, b, class_inferred, method_inferred);
2199 // If both of them are arrays.
2202 if (a.IsArray && b.IsArray) {
2203 if (a.GetArrayRank () != b.GetArrayRank ())
2206 a = a.GetElementType ();
2207 b = b.GetElementType ();
2209 return MayBecomeEqualGenericTypes (a, b, class_inferred, method_inferred);
2213 // Ok, two ordinary types.
2216 return a.Equals (b);
2220 // Checks whether two generic instances may become equal for some
2221 // particular instantiation (26.3.1).
2223 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
2224 Type[] class_inferred,
2225 Type[] method_inferred)
2227 if (!a.IsGenericType || !b.IsGenericType)
2229 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2232 return MayBecomeEqualGenericInstances (
2233 GetTypeArguments (a), GetTypeArguments (b), class_inferred, method_inferred);
2236 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
2237 Type[] class_inferred,
2238 Type[] method_inferred)
2240 if (aargs.Length != bargs.Length)
2243 for (int i = 0; i < aargs.Length; i++) {
2244 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_inferred, method_inferred))
2251 static bool UnifyType (Type pt, Type at, Type[] inferred)
2253 if (pt.IsGenericParameter) {
2254 if (pt.DeclaringMethod == null)
2257 int pos = pt.GenericParameterPosition;
2259 if (inferred [pos] == null)
2260 inferred [pos] = at;
2262 return inferred [pos] == at;
2265 if (!pt.ContainsGenericParameters) {
2266 if (at.ContainsGenericParameters)
2267 return UnifyType (at, pt, inferred);
2274 if (at.GetArrayRank () != pt.GetArrayRank ())
2277 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2280 if (!pt.IsGenericType)
2283 Type gt = pt.GetGenericTypeDefinition ();
2284 if ((gt != generic_ilist_type) && (gt != generic_icollection_type) &&
2285 (gt != generic_ienumerable_type))
2288 Type[] args = GetTypeArguments (pt);
2289 return UnifyType (args [0], at.GetElementType (), inferred);
2294 (pt.GetArrayRank () != at.GetArrayRank ()))
2297 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2300 if (pt.IsByRef && at.IsByRef)
2301 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2302 ArrayList list = new ArrayList ();
2303 if (at.IsGenericType)
2305 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
2308 list.AddRange (TypeManager.GetInterfaces (at));
2310 foreach (Type type in list) {
2311 if (!type.IsGenericType)
2314 if (DropGenericTypeArguments (pt) != DropGenericTypeArguments (type))
2317 if (!UnifyTypes (pt.GetGenericArguments (), type.GetGenericArguments (), inferred))
2324 static bool UnifyTypes (Type[] pts, Type [] ats, Type [] inferred)
2326 for (int i = 0; i < ats.Length; i++) {
2327 if (!UnifyType (pts [i], ats [i], inferred))
2334 /// Type inference. Try to infer the type arguments from the params method
2335 /// `method', which is invoked with the arguments `arguments'. This is used
2336 /// when resolving an Invocation or a DelegateInvocation and the user
2337 /// did not explicitly specify type arguments.
2339 public static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
2340 ref MethodBase method)
2342 if (!TypeManager.IsGenericMethod (method))
2345 // if there are no arguments, there's no way to infer the type-arguments
2346 if (arguments == null || arguments.Count == 0)
2349 ParameterData pd = TypeManager.GetParameterData (method);
2350 int pd_count = pd.Count;
2351 int arg_count = arguments.Count;
2356 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2359 if (pd_count - 1 > arg_count)
2362 Type[] method_args = method.GetGenericArguments ();
2363 Type[] inferred_types = new Type [method_args.Length];
2366 // If we have come this far, the case which
2367 // remains is when the number of parameters is
2368 // less than or equal to the argument count.
2370 for (int i = 0; i < pd_count - 1; ++i) {
2371 Argument a = (Argument) arguments [i];
2373 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2376 Type pt = pd.ParameterType (i);
2379 if (!UnifyType (pt, at, inferred_types))
2383 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
2385 for (int i = pd_count - 1; i < arg_count; i++) {
2386 Argument a = (Argument) arguments [i];
2388 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2391 if (!UnifyType (element_type, a.Type, inferred_types))
2395 for (int i = 0; i < inferred_types.Length; i++)
2396 if (inferred_types [i] == null)
2399 method = ((MethodInfo)method).MakeGenericMethod (inferred_types);
2403 static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
2404 Type[] inferred_types)
2406 for (int i = 0; i < arg_types.Length; i++) {
2407 if (arg_types [i] == null)
2410 if (!UnifyType (param_types [i], arg_types [i], inferred_types))
2414 for (int i = 0; i < inferred_types.Length; i++)
2415 if (inferred_types [i] == null)
2422 // Infers the remaining inferred_types from lambda expressions contained in the
2425 static bool LambdaInfer (EmitContext ec, ArrayList arguments,
2426 Type[] param_types, Type[] arg_types, Type[] inferred_types)
2428 int arg_count = arg_types.Length;
2430 for (int i = 0; i < arg_count; i++){
2431 Argument a = (Argument) arguments [i];
2433 LambdaExpression le = a.Expr as LambdaExpression;
2439 // TODO: "The argument is a lambda expression, in
2440 // the following called L, from which no inferences
2441 // have yet been made."
2445 // "The corresponding parameter’s type, in the
2446 // following called P, is a delegate type with a
2447 // return type that involves one or more method type
2451 if (!TypeManager.IsDelegateType (param_types [i]))
2454 Type p_type = param_types [i];
2455 MethodGroupExpr method_group = Expression.MemberLookup (
2456 ec.ContainerType, p_type, "Invoke", MemberTypes.Method,
2457 Expression.AllBindingFlags, Location.Null) as MethodGroupExpr;
2459 if (method_group == null){
2460 // This we report elsewhere as -200, but here we can ignore
2463 MethodInfo delegate_method = method_group.Methods [0] as MethodInfo;
2464 if (delegate_method == null){
2465 // This should not happen.
2469 Type return_type = delegate_method.ReturnType;
2470 if (!return_type.IsGenericParameter)
2474 // P and L have the same number of parameters, and
2475 // each parameter in P has the same modifiers as the
2476 // corresponding parameter in L, or no modifiers if
2477 // L has an implicitly typed parameter list.
2479 ParameterData delegate_pd = TypeManager.GetParameterData (delegate_method);
2480 int delegate_pc = delegate_pd.Count;
2481 if (delegate_pc != le.Parameters.Count)
2486 if (le.HasExplicitParameters){
2487 for (int j = 0; j < delegate_pc; j++){
2488 if (delegate_pd.ParameterModifier [j] !=
2489 le.Parameters.ParameterModifier[j])
2493 for (int j = 0; j < delegate_pc; j++)
2494 if (le.Parameters.ParameterModifier [j] != Parameter.Modifier.NONE)
2500 // TODO: P’s parameter types involve no method type
2501 // parameters or involve only method type parameters
2502 // for which a consistent set of inferences have
2503 // already been made.
2506 if (le.HasExplicitParameters){
2508 // TODO: If L has an explicitly typed parameter
2509 // list, when inferred types are substituted for
2510 // method type parameters in P, each parameter in P
2511 // has the same type as the corresponding parameter
2516 // TODO: If L has an implicitly typed parameter
2517 // list, when inferred types are substituted for
2518 // method type parameters in P and the resulting
2519 // parameter types are given to the parameters of L,
2520 // the body of L is a valid expression or statement
2532 /// Type inference. Try to infer the type arguments from `method',
2533 /// which is invoked with the arguments `arguments'. This is used
2534 /// when resolving an Invocation or a DelegateInvocation and the user
2535 /// did not explicitly specify type arguments.
2537 public static bool InferTypeArguments (EmitContext ec,
2538 ArrayList arguments,
2539 ref MethodBase method)
2541 if (!TypeManager.IsGenericMethod (method))
2545 if (arguments != null)
2546 arg_count = arguments.Count;
2550 ParameterData pd = TypeManager.GetParameterData (method);
2551 if (arg_count != pd.Count)
2554 Type[] method_args = method.GetGenericArguments ();
2556 bool is_open = false;
2557 for (int i = 0; i < method_args.Length; i++) {
2558 if (method_args [i].IsGenericParameter) {
2564 // If none of the method parameters mention a generic parameter, we can't infer the generic parameters
2566 return !TypeManager.IsGenericMethodDefinition (method);
2568 Type[] inferred_types = new Type [method_args.Length];
2570 Type[] param_types = new Type [pd.Count];
2571 Type[] arg_types = new Type [pd.Count];
2574 for (int i = 0; i < arg_count; i++) {
2575 param_types [i] = pd.ParameterType (i);
2577 Argument a = (Argument) arguments [i];
2578 if (a.Expr is LambdaExpression)
2581 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr) ||
2582 (a.Expr is AnonymousMethodExpression))
2585 arg_types [i] = a.Type;
2588 if (!InferTypeArguments (param_types, arg_types, inferred_types)){
2593 if (!LambdaInfer (ec, arguments, param_types, arg_types, inferred_types))
2597 method = ((MethodInfo)method).MakeGenericMethod (inferred_types);
2604 public static bool InferTypeArguments (ParameterData apd,
2605 ref MethodBase method)
2607 if (!TypeManager.IsGenericMethod (method))
2610 ParameterData pd = TypeManager.GetParameterData (method);
2611 if (apd.Count != pd.Count)
2614 Type[] method_args = method.GetGenericArguments ();
2615 Type[] inferred_types = new Type [method_args.Length];
2617 Type[] param_types = new Type [pd.Count];
2618 Type[] arg_types = new Type [pd.Count];
2620 for (int i = 0; i < apd.Count; i++) {
2621 param_types [i] = pd.ParameterType (i);
2622 arg_types [i] = apd.ParameterType (i);
2625 if (!InferTypeArguments (param_types, arg_types, inferred_types))
2628 method = ((MethodInfo)method).MakeGenericMethod (inferred_types);
2633 public abstract class Nullable
2635 public sealed class NullableInfo
2637 public readonly Type Type;
2638 public readonly Type UnderlyingType;
2639 public readonly MethodInfo HasValue;
2640 public readonly MethodInfo Value;
2641 public readonly ConstructorInfo Constructor;
2643 public NullableInfo (Type type)
2646 UnderlyingType = TypeManager.GetTypeArguments (type) [0];
2648 PropertyInfo has_value_pi = TypeManager.GetProperty (type, "HasValue");
2649 PropertyInfo value_pi = TypeManager.GetProperty (type, "Value");
2651 HasValue = has_value_pi.GetGetMethod (false);
2652 Value = value_pi.GetGetMethod (false);
2653 Constructor = type.GetConstructor (new Type[] { UnderlyingType });
2657 public class Unwrap : Expression, IMemoryLocation, IAssignMethod
2662 LocalTemporary temp;
2665 protected Unwrap (Expression expr)
2668 this.loc = expr.Location;
2671 public static Unwrap Create (Expression expr, EmitContext ec)
2673 return new Unwrap (expr).Resolve (ec) as Unwrap;
2676 public override Expression DoResolve (EmitContext ec)
2678 expr = expr.Resolve (ec);
2682 temp = new LocalTemporary (expr.Type);
2684 info = new NullableInfo (expr.Type);
2685 type = info.UnderlyingType;
2686 eclass = expr.eclass;
2690 public override void Emit (EmitContext ec)
2692 AddressOf (ec, AddressOp.LoadStore);
2693 ec.ig.EmitCall (OpCodes.Call, info.Value, null);
2696 public void EmitCheck (EmitContext ec)
2698 AddressOf (ec, AddressOp.LoadStore);
2699 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
2702 public void Store (EmitContext ec)
2707 void create_temp (EmitContext ec)
2709 if ((temp != null) && !has_temp) {
2716 public void AddressOf (EmitContext ec, AddressOp mode)
2720 temp.AddressOf (ec, AddressOp.LoadStore);
2722 ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
2725 public void Emit (EmitContext ec, bool leave_copy)
2738 public void EmitAssign (EmitContext ec, Expression source,
2739 bool leave_copy, bool prepare_for_load)
2741 InternalWrap wrap = new InternalWrap (source, info, loc);
2742 ((IAssignMethod) expr).EmitAssign (ec, wrap, leave_copy, false);
2745 protected class InternalWrap : Expression
2747 public Expression expr;
2748 public NullableInfo info;
2750 public InternalWrap (Expression expr, NullableInfo info, Location loc)
2757 eclass = ExprClass.Value;
2760 public override Expression DoResolve (EmitContext ec)
2765 public override void Emit (EmitContext ec)
2768 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2773 public class Wrap : Expression
2778 protected Wrap (Expression expr)
2781 this.loc = expr.Location;
2784 public static Wrap Create (Expression expr, EmitContext ec)
2786 return new Wrap (expr).Resolve (ec) as Wrap;
2789 public override Expression DoResolve (EmitContext ec)
2791 expr = expr.Resolve (ec);
2795 TypeExpr target_type = new NullableType (expr.Type, loc);
2796 target_type = target_type.ResolveAsTypeTerminal (ec, false);
2797 if (target_type == null)
2800 type = target_type.Type;
2801 info = new NullableInfo (type);
2802 eclass = ExprClass.Value;
2806 public override void Emit (EmitContext ec)
2809 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2813 public class NullableLiteral : NullLiteral, IMemoryLocation {
2814 public NullableLiteral (Type target_type, Location loc)
2817 this.type = target_type;
2819 eclass = ExprClass.Value;
2822 public override Expression DoResolve (EmitContext ec)
2827 public override void Emit (EmitContext ec)
2829 LocalTemporary value_target = new LocalTemporary (type);
2831 value_target.AddressOf (ec, AddressOp.Store);
2832 ec.ig.Emit (OpCodes.Initobj, type);
2833 value_target.Emit (ec);
2836 public void AddressOf (EmitContext ec, AddressOp Mode)
2838 LocalTemporary value_target = new LocalTemporary (type);
2840 value_target.AddressOf (ec, AddressOp.Store);
2841 ec.ig.Emit (OpCodes.Initobj, type);
2842 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
2846 public abstract class Lifted : Expression, IMemoryLocation
2848 Expression expr, underlying, wrap, null_value;
2851 protected Lifted (Expression expr, Location loc)
2857 public override Expression DoResolve (EmitContext ec)
2859 expr = expr.Resolve (ec);
2863 unwrap = Unwrap.Create (expr, ec);
2867 underlying = ResolveUnderlying (unwrap, ec);
2868 if (underlying == null)
2871 wrap = Wrap.Create (underlying, ec);
2875 null_value = new NullableLiteral (wrap.Type, loc).Resolve (ec);
2876 if (null_value == null)
2880 eclass = ExprClass.Value;
2884 protected abstract Expression ResolveUnderlying (Expression unwrap, EmitContext ec);
2886 public override void Emit (EmitContext ec)
2888 ILGenerator ig = ec.ig;
2889 Label is_null_label = ig.DefineLabel ();
2890 Label end_label = ig.DefineLabel ();
2892 unwrap.EmitCheck (ec);
2893 ig.Emit (OpCodes.Brfalse, is_null_label);
2896 ig.Emit (OpCodes.Br, end_label);
2898 ig.MarkLabel (is_null_label);
2899 null_value.Emit (ec);
2901 ig.MarkLabel (end_label);
2904 public void AddressOf (EmitContext ec, AddressOp mode)
2906 unwrap.AddressOf (ec, mode);
2910 public class LiftedConversion : Lifted
2912 public readonly bool IsUser;
2913 public readonly bool IsExplicit;
2914 public readonly Type TargetType;
2916 public LiftedConversion (Expression expr, Type target_type, bool is_user,
2917 bool is_explicit, Location loc)
2920 this.IsUser = is_user;
2921 this.IsExplicit = is_explicit;
2922 this.TargetType = target_type;
2925 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2927 Type type = TypeManager.GetTypeArguments (TargetType) [0];
2930 return Convert.UserDefinedConversion (ec, unwrap, type, loc, IsExplicit);
2933 return Convert.ExplicitConversion (ec, unwrap, type, loc);
2935 return Convert.ImplicitConversion (ec, unwrap, type, loc);
2940 public class LiftedUnaryOperator : Lifted
2942 public readonly Unary.Operator Oper;
2944 public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
2950 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2952 return new Unary (Oper, unwrap, loc);
2956 public class LiftedConditional : Lifted
2958 Expression true_expr, false_expr;
2960 public LiftedConditional (Expression expr, Expression true_expr, Expression false_expr,
2964 this.true_expr = true_expr;
2965 this.false_expr = false_expr;
2968 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2970 return new Conditional (unwrap, true_expr, false_expr);
2974 public class LiftedBinaryOperator : Expression
2976 public readonly Binary.Operator Oper;
2978 Expression left, right, original_left, original_right;
2979 Expression underlying, null_value, bool_wrap;
2980 Unwrap left_unwrap, right_unwrap;
2981 bool is_equality, is_comparision, is_boolean;
2983 public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
2987 this.left = original_left = left;
2988 this.right = original_right = right;
2992 public override Expression DoResolve (EmitContext ec)
2994 if (TypeManager.IsNullableType (left.Type)) {
2995 left = left_unwrap = Unwrap.Create (left, ec);
3000 if (TypeManager.IsNullableType (right.Type)) {
3001 right = right_unwrap = Unwrap.Create (right, ec);
3006 if ((Oper == Binary.Operator.LogicalAnd) ||
3007 (Oper == Binary.Operator.LogicalOr)) {
3008 Binary.Error_OperatorCannotBeApplied (
3009 loc, Binary.OperName (Oper),
3010 original_left.GetSignatureForError (),
3011 original_right.GetSignatureForError ());
3015 if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr)) &&
3016 ((left.Type == TypeManager.bool_type) && (right.Type == TypeManager.bool_type))) {
3017 Expression empty = new EmptyExpression (TypeManager.bool_type);
3018 bool_wrap = Wrap.Create (empty, ec);
3019 null_value = new NullableLiteral (bool_wrap.Type, loc).Resolve (ec);
3021 type = bool_wrap.Type;
3023 } else if ((Oper == Binary.Operator.Equality) || (Oper == Binary.Operator.Inequality)) {
3024 if (!(left is NullLiteral) && !(right is NullLiteral)) {
3025 underlying = new Binary (Oper, left, right).Resolve (ec);
3026 if (underlying == null)
3030 type = TypeManager.bool_type;
3032 } else if ((Oper == Binary.Operator.LessThan) ||
3033 (Oper == Binary.Operator.GreaterThan) ||
3034 (Oper == Binary.Operator.LessThanOrEqual) ||
3035 (Oper == Binary.Operator.GreaterThanOrEqual)) {
3036 underlying = new Binary (Oper, left, right).Resolve (ec);
3037 if (underlying == null)
3040 type = TypeManager.bool_type;
3041 is_comparision = true;
3043 underlying = new Binary (Oper, left, right).Resolve (ec);
3044 if (underlying == null)
3047 underlying = Wrap.Create (underlying, ec);
3048 if (underlying == null)
3051 type = underlying.Type;
3052 null_value = new NullableLiteral (type, loc).Resolve (ec);
3055 eclass = ExprClass.Value;
3059 void EmitBoolean (EmitContext ec)
3061 ILGenerator ig = ec.ig;
3063 Label left_is_null_label = ig.DefineLabel ();
3064 Label right_is_null_label = ig.DefineLabel ();
3065 Label is_null_label = ig.DefineLabel ();
3066 Label wrap_label = ig.DefineLabel ();
3067 Label end_label = ig.DefineLabel ();
3069 if (left_unwrap != null) {
3070 left_unwrap.EmitCheck (ec);
3071 ig.Emit (OpCodes.Brfalse, left_is_null_label);
3075 ig.Emit (OpCodes.Dup);
3076 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3077 ig.Emit (OpCodes.Brtrue, wrap_label);
3079 ig.Emit (OpCodes.Brfalse, wrap_label);
3081 if (right_unwrap != null) {
3082 right_unwrap.EmitCheck (ec);
3083 ig.Emit (OpCodes.Brfalse, right_is_null_label);
3086 if ((Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr))
3087 ig.Emit (OpCodes.Pop);
3090 if (Oper == Binary.Operator.BitwiseOr)
3091 ig.Emit (OpCodes.Or);
3092 else if (Oper == Binary.Operator.BitwiseAnd)
3093 ig.Emit (OpCodes.And);
3094 ig.Emit (OpCodes.Br, wrap_label);
3096 ig.MarkLabel (left_is_null_label);
3097 if (right_unwrap != null) {
3098 right_unwrap.EmitCheck (ec);
3099 ig.Emit (OpCodes.Brfalse, is_null_label);
3103 ig.Emit (OpCodes.Dup);
3104 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3105 ig.Emit (OpCodes.Brtrue, wrap_label);
3107 ig.Emit (OpCodes.Brfalse, wrap_label);
3109 ig.MarkLabel (right_is_null_label);
3110 ig.Emit (OpCodes.Pop);
3111 ig.MarkLabel (is_null_label);
3112 null_value.Emit (ec);
3113 ig.Emit (OpCodes.Br, end_label);
3115 ig.MarkLabel (wrap_label);
3116 ig.Emit (OpCodes.Nop);
3117 bool_wrap.Emit (ec);
3118 ig.Emit (OpCodes.Nop);
3120 ig.MarkLabel (end_label);
3123 void EmitEquality (EmitContext ec)
3125 ILGenerator ig = ec.ig;
3127 // Given 'X? x;' for any value type X: 'x != null' is the same as 'x.HasValue'
3128 if (left is NullLiteral) {
3129 if (right_unwrap == null)
3130 throw new InternalErrorException ();
3131 right_unwrap.EmitCheck (ec);
3132 if (Oper == Binary.Operator.Equality) {
3133 ig.Emit (OpCodes.Ldc_I4_0);
3134 ig.Emit (OpCodes.Ceq);
3139 if (right is NullLiteral) {
3140 if (left_unwrap == null)
3141 throw new InternalErrorException ();
3142 left_unwrap.EmitCheck (ec);
3143 if (Oper == Binary.Operator.Equality) {
3144 ig.Emit (OpCodes.Ldc_I4_0);
3145 ig.Emit (OpCodes.Ceq);
3150 Label both_have_value_label = ig.DefineLabel ();
3151 Label end_label = ig.DefineLabel ();
3153 if (left_unwrap != null && right_unwrap != null) {
3154 Label dissimilar_label = ig.DefineLabel ();
3156 left_unwrap.EmitCheck (ec);
3157 ig.Emit (OpCodes.Dup);
3158 right_unwrap.EmitCheck (ec);
3159 ig.Emit (OpCodes.Bne_Un, dissimilar_label);
3161 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3164 if (Oper == Binary.Operator.Equality)
3165 ig.Emit (OpCodes.Ldc_I4_1);
3167 ig.Emit (OpCodes.Ldc_I4_0);
3168 ig.Emit (OpCodes.Br, end_label);
3170 ig.MarkLabel (dissimilar_label);
3171 ig.Emit (OpCodes.Pop);
3172 } else if (left_unwrap != null) {
3173 left_unwrap.EmitCheck (ec);
3174 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3175 } else if (right_unwrap != null) {
3176 right_unwrap.EmitCheck (ec);
3177 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3179 throw new InternalErrorException ("shouldn't get here");
3182 // one is null while the other isn't
3183 if (Oper == Binary.Operator.Equality)
3184 ig.Emit (OpCodes.Ldc_I4_0);
3186 ig.Emit (OpCodes.Ldc_I4_1);
3187 ig.Emit (OpCodes.Br, end_label);
3189 ig.MarkLabel (both_have_value_label);
3190 underlying.Emit (ec);
3192 ig.MarkLabel (end_label);
3195 void EmitComparision (EmitContext ec)
3197 ILGenerator ig = ec.ig;
3199 Label is_null_label = ig.DefineLabel ();
3200 Label end_label = ig.DefineLabel ();
3202 if (left_unwrap != null) {
3203 left_unwrap.EmitCheck (ec);
3204 ig.Emit (OpCodes.Brfalse, is_null_label);
3207 if (right_unwrap != null) {
3208 right_unwrap.EmitCheck (ec);
3209 ig.Emit (OpCodes.Brfalse, is_null_label);
3212 underlying.Emit (ec);
3213 ig.Emit (OpCodes.Br, end_label);
3215 ig.MarkLabel (is_null_label);
3216 ig.Emit (OpCodes.Ldc_I4_0);
3218 ig.MarkLabel (end_label);
3221 public override void Emit (EmitContext ec)
3223 if (left_unwrap != null)
3224 left_unwrap.Store (ec);
3225 if (right_unwrap != null)
3226 right_unwrap.Store (ec);
3231 } else if (is_equality) {
3234 } else if (is_comparision) {
3235 EmitComparision (ec);
3239 ILGenerator ig = ec.ig;
3241 Label is_null_label = ig.DefineLabel ();
3242 Label end_label = ig.DefineLabel ();
3244 if (left_unwrap != null) {
3245 left_unwrap.EmitCheck (ec);
3246 ig.Emit (OpCodes.Brfalse, is_null_label);
3249 if (right_unwrap != null) {
3250 right_unwrap.EmitCheck (ec);
3251 ig.Emit (OpCodes.Brfalse, is_null_label);
3254 underlying.Emit (ec);
3255 ig.Emit (OpCodes.Br, end_label);
3257 ig.MarkLabel (is_null_label);
3258 null_value.Emit (ec);
3260 ig.MarkLabel (end_label);
3264 public class OperatorTrueOrFalse : Expression
3266 public readonly bool IsTrue;
3271 public OperatorTrueOrFalse (Expression expr, bool is_true, Location loc)
3273 this.IsTrue = is_true;
3278 public override Expression DoResolve (EmitContext ec)
3280 unwrap = Unwrap.Create (expr, ec);
3284 if (unwrap.Type != TypeManager.bool_type)
3287 type = TypeManager.bool_type;
3288 eclass = ExprClass.Value;
3292 public override void Emit (EmitContext ec)
3294 ILGenerator ig = ec.ig;
3296 Label is_null_label = ig.DefineLabel ();
3297 Label end_label = ig.DefineLabel ();
3299 unwrap.EmitCheck (ec);
3300 ig.Emit (OpCodes.Brfalse, is_null_label);
3304 ig.Emit (OpCodes.Ldc_I4_0);
3305 ig.Emit (OpCodes.Ceq);
3307 ig.Emit (OpCodes.Br, end_label);
3309 ig.MarkLabel (is_null_label);
3310 ig.Emit (OpCodes.Ldc_I4_0);
3312 ig.MarkLabel (end_label);
3316 public class NullCoalescingOperator : Expression
3318 Expression left, right;
3322 public NullCoalescingOperator (Expression left, Expression right, Location loc)
3328 eclass = ExprClass.Value;
3331 public override Expression DoResolve (EmitContext ec)
3336 left = left.Resolve (ec);
3340 right = right.Resolve (ec);
3344 Type ltype = left.Type, rtype = right.Type;
3346 if (!TypeManager.IsNullableType (ltype) && ltype.IsValueType) {
3347 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3351 if (TypeManager.IsNullableType (ltype)) {
3352 NullableInfo info = new NullableInfo (ltype);
3354 unwrap = Unwrap.Create (left, ec);
3358 expr = Convert.ImplicitConversion (ec, right, info.UnderlyingType, loc);
3366 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
3372 Expression left_null = unwrap != null ? unwrap : left;
3373 expr = Convert.ImplicitConversion (ec, left_null, rtype, loc);
3381 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3385 public override void Emit (EmitContext ec)
3387 ILGenerator ig = ec.ig;
3389 Label is_null_label = ig.DefineLabel ();
3390 Label end_label = ig.DefineLabel ();
3392 if (unwrap != null) {
3393 unwrap.EmitCheck (ec);
3394 ig.Emit (OpCodes.Brfalse, is_null_label);
3397 ig.Emit (OpCodes.Br, end_label);
3399 ig.MarkLabel (is_null_label);
3402 ig.MarkLabel (end_label);
3405 ig.Emit (OpCodes.Dup);
3406 ig.Emit (OpCodes.Brtrue, end_label);
3408 ig.MarkLabel (is_null_label);
3410 ig.Emit (OpCodes.Pop);
3413 ig.MarkLabel (end_label);
3418 public class LiftedUnaryMutator : ExpressionStatement
3420 public readonly UnaryMutator.Mode Mode;
3421 Expression expr, null_value;
3422 UnaryMutator underlying;
3425 public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
3431 eclass = ExprClass.Value;
3434 public override Expression DoResolve (EmitContext ec)
3436 expr = expr.Resolve (ec);
3440 unwrap = Unwrap.Create (expr, ec);
3444 underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
3445 if (underlying == null)
3448 null_value = new NullableLiteral (expr.Type, loc).Resolve (ec);
3449 if (null_value == null)
3456 void DoEmit (EmitContext ec, bool is_expr)
3458 ILGenerator ig = ec.ig;
3459 Label is_null_label = ig.DefineLabel ();
3460 Label end_label = ig.DefineLabel ();
3462 unwrap.EmitCheck (ec);
3463 ig.Emit (OpCodes.Brfalse, is_null_label);
3466 underlying.Emit (ec);
3468 underlying.EmitStatement (ec);
3469 ig.Emit (OpCodes.Br, end_label);
3471 ig.MarkLabel (is_null_label);
3473 null_value.Emit (ec);
3475 ig.MarkLabel (end_label);
3478 public override void Emit (EmitContext ec)
3483 public override void EmitStatement (EmitContext ec)