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.IsGenericParameter && !first.IsInterface;
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 (Location loc, params Expression[] types)
1140 this.Location = loc;
1141 this.args = new ArrayList (types);
1144 public TypeArguments (int dimension, Location loc)
1146 this.dimension = dimension;
1147 this.Location = loc;
1150 public void Add (Expression type)
1153 throw new InvalidOperationException ();
1158 public void Add (TypeArguments new_args)
1161 throw new InvalidOperationException ();
1163 args.AddRange (new_args.args);
1167 /// We're used during the parsing process: the parser can't distinguish
1168 /// between type parameters and type arguments. Because of that, the
1169 /// parser creates a `MemberName' with `TypeArguments' for both cases and
1170 /// in case of a generic type definition, we call GetDeclarations().
1172 public TypeParameterName[] GetDeclarations ()
1174 TypeParameterName[] ret = new TypeParameterName [args.Count];
1175 for (int i = 0; i < args.Count; i++) {
1176 TypeParameterName name = args [i] as TypeParameterName;
1181 SimpleName sn = args [i] as SimpleName;
1183 ret [i] = new TypeParameterName (sn.Name, null, sn.Location);
1187 Report.Error (81, Location, "Type parameter declaration " +
1188 "must be an identifier not a type");
1195 /// We may only be used after Resolve() is called and return the fully
1198 public Type[] Arguments {
1204 public bool HasTypeArguments {
1206 return has_type_args;
1219 public bool IsUnbound {
1221 return dimension > 0;
1225 public override string ToString ()
1227 StringBuilder s = new StringBuilder ();
1230 for (int i = 0; i < count; i++){
1232 // FIXME: Use TypeManager.CSharpname once we have the type
1235 s.Append (args [i].ToString ());
1239 return s.ToString ();
1242 public string GetSignatureForError()
1244 StringBuilder sb = new StringBuilder();
1245 for (int i = 0; i < Count; ++i)
1247 Expression expr = (Expression)args [i];
1248 sb.Append(expr.GetSignatureForError());
1252 return sb.ToString();
1256 /// Resolve the type arguments.
1258 public bool Resolve (IResolveContext ec)
1260 int count = args.Count;
1263 atypes = new Type [count];
1265 for (int i = 0; i < count; i++){
1266 TypeExpr te = ((Expression) args [i]).ResolveAsTypeTerminal (ec, false);
1272 atypes[i] = te.Type;
1273 if (te.Type.IsGenericParameter) {
1274 if (te is TypeParameterExpr)
1275 has_type_args = true;
1279 if (te.Type.IsSealed && te.Type.IsAbstract) {
1280 Report.Error (718, Location, "`{0}': static classes cannot be used as generic arguments",
1281 te.GetSignatureForError ());
1285 if (te.Type.IsPointer) {
1286 Report.Error (306, Location, "The type `{0}' may not be used " +
1287 "as a type argument", TypeManager.CSharpName (te.Type));
1291 if (te.Type == TypeManager.void_type) {
1292 Expression.Error_VoidInvalidInTheContext (Location);
1299 public TypeArguments Clone ()
1301 TypeArguments copy = new TypeArguments (Location);
1302 foreach (Expression ta in args)
1309 public class TypeParameterName : SimpleName
1311 Attributes attributes;
1313 public TypeParameterName (string name, Attributes attrs, Location loc)
1319 public Attributes OptAttributes {
1327 /// An instantiation of a generic type.
1329 public class ConstructedType : TypeExpr {
1331 FullNamedExpression name;
1333 Type[] gen_params, atypes;
1337 /// Instantiate the generic type `fname' with the type arguments `args'.
1339 public ConstructedType (FullNamedExpression fname, TypeArguments args, Location l)
1345 eclass = ExprClass.Type;
1346 full_name = name + "<" + args.ToString () + ">";
1349 protected ConstructedType (TypeArguments args, Location l)
1354 eclass = ExprClass.Type;
1357 protected ConstructedType (TypeParameter[] type_params, Location l)
1361 args = new TypeArguments (l);
1362 foreach (TypeParameter type_param in type_params)
1363 args.Add (new TypeParameterExpr (type_param, l));
1365 eclass = ExprClass.Type;
1369 /// This is used to construct the `this' type inside a generic type definition.
1371 public ConstructedType (Type t, TypeParameter[] type_params, Location l)
1372 : this (type_params, l)
1374 gt = t.GetGenericTypeDefinition ();
1376 this.name = new TypeExpression (gt, l);
1377 full_name = gt.FullName + "<" + args.ToString () + ">";
1381 /// Instantiate the generic type `t' with the type arguments `args'.
1382 /// Use this constructor if you already know the fully resolved
1385 public ConstructedType (Type t, TypeArguments args, Location l)
1388 gt = t.GetGenericTypeDefinition ();
1390 this.name = new TypeExpression (gt, l);
1391 full_name = gt.FullName + "<" + args.ToString () + ">";
1394 public TypeArguments TypeArguments {
1395 get { return args; }
1398 public override string GetSignatureForError ()
1400 return TypeManager.RemoveGenericArity (gt.FullName) + "<" + args.GetSignatureForError () + ">";
1403 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1405 if (!ResolveConstructedType (ec))
1412 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1413 /// after fully resolving the constructed type.
1415 public bool CheckConstraints (IResolveContext ec)
1417 return ConstraintChecker.CheckConstraints (ec, gt, gen_params, atypes, loc);
1421 /// Resolve the constructed type, but don't check the constraints.
1423 public bool ResolveConstructedType (IResolveContext ec)
1427 // If we already know the fully resolved generic type.
1429 return DoResolveType (ec);
1435 Report.Error (246, loc, "Cannot find type `{0}'<...>", Name);
1439 num_args = TypeManager.GetNumberOfTypeArguments (t);
1440 if (num_args == 0) {
1441 Report.Error (308, loc,
1442 "The non-generic type `{0}' cannot " +
1443 "be used with type arguments.",
1444 TypeManager.CSharpName (t));
1448 gt = t.GetGenericTypeDefinition ();
1449 return DoResolveType (ec);
1452 bool DoResolveType (IResolveContext ec)
1455 // Resolve the arguments.
1457 if (args.Resolve (ec) == false)
1460 gen_params = gt.GetGenericArguments ();
1461 atypes = args.Arguments;
1463 if (atypes.Length != gen_params.Length) {
1464 Report.Error (305, loc,
1465 "Using the generic type `{0}' " +
1466 "requires {1} type arguments",
1467 TypeManager.CSharpName (gt),
1468 gen_params.Length.ToString ());
1473 // Now bind the parameters.
1475 type = gt.MakeGenericType (atypes);
1479 public Expression GetSimpleName (EmitContext ec)
1484 public override bool CheckAccessLevel (DeclSpace ds)
1486 return ds.CheckAccessLevel (gt);
1489 public override bool AsAccessible (DeclSpace ds, int flags)
1491 foreach (Type t in atypes) {
1492 if (!ds.AsAccessible (t, flags))
1496 return ds.AsAccessible (gt, flags);
1499 public override bool IsClass {
1500 get { return gt.IsClass; }
1503 public override bool IsValueType {
1504 get { return gt.IsValueType; }
1507 public override bool IsInterface {
1508 get { return gt.IsInterface; }
1511 public override bool IsSealed {
1512 get { return gt.IsSealed; }
1515 public override bool Equals (object obj)
1517 ConstructedType cobj = obj as ConstructedType;
1521 if ((type == null) || (cobj.type == null))
1524 return type == cobj.type;
1527 public override int GetHashCode ()
1529 return base.GetHashCode ();
1532 public override string Name {
1538 public override string FullName {
1545 public abstract class ConstraintChecker
1547 protected readonly Type[] gen_params;
1548 protected readonly Type[] atypes;
1549 protected readonly Location loc;
1551 protected ConstraintChecker (Type[] gen_params, Type[] atypes, Location loc)
1553 this.gen_params = gen_params;
1554 this.atypes = atypes;
1559 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1560 /// after fully resolving the constructed type.
1562 public bool CheckConstraints (IResolveContext ec)
1564 for (int i = 0; i < gen_params.Length; i++) {
1565 if (!CheckConstraints (ec, i))
1572 protected bool CheckConstraints (IResolveContext ec, int index)
1574 Type atype = atypes [index];
1575 Type ptype = gen_params [index];
1580 Expression aexpr = new EmptyExpression (atype);
1582 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1586 bool is_class, is_struct;
1587 if (atype.IsGenericParameter) {
1588 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1590 if (agc is Constraints)
1591 ((Constraints) agc).Resolve (ec);
1592 is_class = agc.IsReferenceType;
1593 is_struct = agc.IsValueType;
1595 is_class = is_struct = false;
1600 if (!atype.IsGenericType)
1602 is_class = atype.IsClass || atype.IsInterface;
1603 is_struct = atype.IsValueType && !TypeManager.IsNullableType (atype);
1607 // First, check the `class' and `struct' constraints.
1609 if (gc.HasReferenceTypeConstraint && !is_class) {
1610 Report.Error (452, loc, "The type `{0}' must be " +
1611 "a reference type in order to use it " +
1612 "as type parameter `{1}' in the " +
1613 "generic type or method `{2}'.",
1614 TypeManager.CSharpName (atype),
1615 TypeManager.CSharpName (ptype),
1616 GetSignatureForError ());
1618 } else if (gc.HasValueTypeConstraint && !is_struct) {
1619 Report.Error (453, loc, "The type `{0}' must be a " +
1620 "non-nullable value type in order to use it " +
1621 "as type parameter `{1}' in the " +
1622 "generic type or method `{2}'.",
1623 TypeManager.CSharpName (atype),
1624 TypeManager.CSharpName (ptype),
1625 GetSignatureForError ());
1630 // The class constraint comes next.
1632 if (gc.HasClassConstraint) {
1633 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint))
1638 // Now, check the interface constraints.
1640 if (gc.InterfaceConstraints != null) {
1641 foreach (Type it in gc.InterfaceConstraints) {
1642 if (!CheckConstraint (ec, ptype, aexpr, it))
1648 // Finally, check the constructor constraint.
1651 if (!gc.HasConstructorConstraint)
1654 if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
1657 if (HasDefaultConstructor (atype))
1660 Report_SymbolRelatedToPreviousError ();
1661 Report.SymbolRelatedToPreviousError (atype);
1662 Report.Error (310, loc, "The type `{0}' must have a public " +
1663 "parameterless constructor in order to use it " +
1664 "as parameter `{1}' in the generic type or " +
1666 TypeManager.CSharpName (atype),
1667 TypeManager.CSharpName (ptype),
1668 GetSignatureForError ());
1672 protected bool CheckConstraint (IResolveContext ec, Type ptype, Expression expr,
1675 if (TypeManager.HasGenericArguments (ctype)) {
1676 Type[] types = TypeManager.GetTypeArguments (ctype);
1678 TypeArguments new_args = new TypeArguments (loc);
1680 for (int i = 0; i < types.Length; i++) {
1683 if (t.IsGenericParameter) {
1684 int pos = t.GenericParameterPosition;
1687 new_args.Add (new TypeExpression (t, loc));
1690 TypeExpr ct = new ConstructedType (ctype, new_args, loc);
1691 if (ct.ResolveAsTypeStep (ec, false) == null)
1694 } else if (ctype.IsGenericParameter) {
1695 int pos = ctype.GenericParameterPosition;
1696 ctype = atypes [pos];
1699 if (Convert.ImplicitStandardConversionExists (expr, ctype))
1702 Error_TypeMustBeConvertible (expr.Type, ctype, ptype);
1706 bool HasDefaultConstructor (Type atype)
1708 if (atype.IsAbstract)
1712 atype = TypeManager.DropGenericTypeArguments (atype);
1713 if (atype is TypeBuilder) {
1714 TypeContainer tc = TypeManager.LookupTypeContainer (atype);
1715 if (tc.InstanceConstructors == null) {
1716 atype = atype.BaseType;
1720 foreach (Constructor c in tc.InstanceConstructors) {
1721 if ((c.ModFlags & Modifiers.PUBLIC) == 0)
1723 if ((c.Parameters.FixedParameters != null) &&
1724 (c.Parameters.FixedParameters.Length != 0))
1726 if (c.Parameters.HasArglist || c.Parameters.HasParams)
1733 TypeParameter tparam = TypeManager.LookupTypeParameter (atype);
1734 if (tparam != null) {
1735 if (tparam.GenericConstraints == null)
1738 return tparam.GenericConstraints.HasConstructorConstraint;
1741 MemberList list = TypeManager.FindMembers (
1742 atype, MemberTypes.Constructor,
1743 BindingFlags.Public | BindingFlags.Instance |
1744 BindingFlags.DeclaredOnly, null, null);
1746 if (atype.IsAbstract || (list == null))
1749 foreach (MethodBase mb in list) {
1750 ParameterData pd = TypeManager.GetParameterData (mb);
1751 if ((pd.Count == 0) && mb.IsPublic && !mb.IsStatic)
1758 protected abstract string GetSignatureForError ();
1759 protected abstract void Report_SymbolRelatedToPreviousError ();
1761 void Error_TypeMustBeConvertible (Type atype, Type gc, Type ptype)
1763 Report_SymbolRelatedToPreviousError ();
1764 Report.SymbolRelatedToPreviousError (atype);
1765 Report.Error (309, loc,
1766 "The type `{0}' must be convertible to `{1}' in order to " +
1767 "use it as parameter `{2}' in the generic type or method `{3}'",
1768 TypeManager.CSharpName (atype), TypeManager.CSharpName (gc),
1769 TypeManager.CSharpName (ptype), GetSignatureForError ());
1772 public static bool CheckConstraints (EmitContext ec, MethodBase definition,
1773 MethodBase instantiated, Location loc)
1775 MethodConstraintChecker checker = new MethodConstraintChecker (
1776 definition, definition.GetGenericArguments (),
1777 instantiated.GetGenericArguments (), loc);
1779 return checker.CheckConstraints (ec);
1782 public static bool CheckConstraints (IResolveContext ec, Type gt, Type[] gen_params,
1783 Type[] atypes, Location loc)
1785 TypeConstraintChecker checker = new TypeConstraintChecker (
1786 gt, gen_params, atypes, loc);
1788 return checker.CheckConstraints (ec);
1791 protected class MethodConstraintChecker : ConstraintChecker
1793 MethodBase definition;
1795 public MethodConstraintChecker (MethodBase definition, Type[] gen_params,
1796 Type[] atypes, Location loc)
1797 : base (gen_params, atypes, loc)
1799 this.definition = definition;
1802 protected override string GetSignatureForError ()
1804 return TypeManager.CSharpSignature (definition);
1807 protected override void Report_SymbolRelatedToPreviousError ()
1809 Report.SymbolRelatedToPreviousError (definition);
1813 protected class TypeConstraintChecker : ConstraintChecker
1817 public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
1819 : base (gen_params, atypes, loc)
1824 protected override string GetSignatureForError ()
1826 return TypeManager.CSharpName (gt);
1829 protected override void Report_SymbolRelatedToPreviousError ()
1831 Report.SymbolRelatedToPreviousError (gt);
1837 /// A generic method definition.
1839 public class GenericMethod : DeclSpace
1841 Expression return_type;
1842 Parameters parameters;
1844 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
1845 Expression return_type, Parameters parameters)
1846 : base (ns, parent, name, null)
1848 this.return_type = return_type;
1849 this.parameters = parameters;
1852 public override TypeBuilder DefineType ()
1854 throw new Exception ();
1857 public override bool Define ()
1859 for (int i = 0; i < TypeParameters.Length; i++)
1860 if (!TypeParameters [i].Resolve (this))
1867 /// Define and resolve the type parameters.
1868 /// We're called from Method.Define().
1870 public bool Define (MethodBuilder mb, ToplevelBlock block)
1872 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1873 string[] snames = new string [names.Length];
1874 for (int i = 0; i < names.Length; i++) {
1875 string type_argument_name = names[i].Name;
1876 Parameter p = parameters.GetParameterByName (type_argument_name);
1878 Error_ParameterNameCollision (p.Location, type_argument_name, "method parameter");
1882 // FIXME: This is wrong, since it only looks at the outermost set of variables
1883 if (block != null) {
1884 LocalInfo li = (LocalInfo)block.Variables [type_argument_name];
1886 Error_ParameterNameCollision (li.Location, type_argument_name, "local variable");
1890 snames[i] = type_argument_name;
1893 GenericTypeParameterBuilder[] gen_params = mb.DefineGenericParameters (snames);
1894 for (int i = 0; i < TypeParameters.Length; i++)
1895 TypeParameters [i].Define (gen_params [i]);
1900 for (int i = 0; i < TypeParameters.Length; i++) {
1901 if (!TypeParameters [i].ResolveType (this))
1908 static void Error_ParameterNameCollision (Location loc, string name, string collisionWith)
1910 Report.Error (412, loc, "The type parameter name `{0}' is the same as `{1}'",
1911 name, collisionWith);
1915 /// We're called from MethodData.Define() after creating the MethodBuilder.
1917 public bool DefineType (EmitContext ec, MethodBuilder mb,
1918 MethodInfo implementing, bool is_override)
1920 for (int i = 0; i < TypeParameters.Length; i++)
1921 if (!TypeParameters [i].DefineType (
1922 ec, mb, implementing, is_override))
1926 foreach (Parameter p in parameters.FixedParameters){
1927 if (!p.Resolve (ec))
1930 if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec, false) == null))
1936 public void EmitAttributes ()
1938 for (int i = 0; i < TypeParameters.Length; i++)
1939 TypeParameters [i].EmitAttributes ();
1941 if (OptAttributes != null)
1942 OptAttributes.Emit ();
1945 public override bool DefineMembers ()
1950 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1951 MemberFilter filter, object criteria)
1953 throw new Exception ();
1956 public override MemberCache MemberCache {
1962 public override AttributeTargets AttributeTargets {
1964 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1968 public override string DocCommentHeader {
1969 get { return "M:"; }
1972 public new void VerifyClsCompliance ()
1974 foreach (TypeParameter tp in TypeParameters) {
1975 if (tp.Constraints == null)
1978 tp.Constraints.VerifyClsCompliance ();
1983 public class DefaultValueExpression : Expression
1987 public DefaultValueExpression (Expression expr, Location loc)
1993 public override Expression DoResolve (EmitContext ec)
1995 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
2001 if (type == TypeManager.void_type) {
2002 Error_VoidInvalidInTheContext (loc);
2006 if (type.IsGenericParameter)
2008 GenericConstraints constraints = TypeManager.GetTypeParameterConstraints(type);
2009 if (constraints != null && constraints.IsReferenceType)
2010 return new NullDefault (new NullLiteral (Location), type);
2014 Constant c = New.Constantify(type);
2016 return new NullDefault (c, type);
2018 if (!TypeManager.IsValueType (type))
2019 return new NullDefault (new NullLiteral (Location), type);
2021 eclass = ExprClass.Variable;
2025 public override void Emit (EmitContext ec)
2027 LocalTemporary temp_storage = new LocalTemporary(type);
2029 temp_storage.AddressOf(ec, AddressOp.LoadStore);
2030 ec.ig.Emit(OpCodes.Initobj, type);
2031 temp_storage.Emit(ec);
2035 public class NullableType : TypeExpr
2037 Expression underlying;
2039 public NullableType (Expression underlying, Location l)
2041 this.underlying = underlying;
2044 eclass = ExprClass.Type;
2047 public NullableType (Type type, Location loc)
2048 : this (new TypeExpression (type, loc), loc)
2051 public override string Name {
2052 get { return underlying.ToString () + "?"; }
2055 public override string FullName {
2056 get { return underlying.ToString () + "?"; }
2059 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
2061 TypeArguments args = new TypeArguments (loc);
2062 args.Add (underlying);
2064 ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
2065 return ctype.ResolveAsTypeTerminal (ec, false);
2069 public partial class TypeManager
2072 // A list of core types that the compiler requires or uses
2074 static public Type activator_type;
2075 static public Type generic_ilist_type;
2076 static public Type generic_icollection_type;
2077 static public Type generic_ienumerator_type;
2078 static public Type generic_ienumerable_type;
2079 static public Type generic_nullable_type;
2082 // These methods are called by code generated by the compiler
2084 static public MethodInfo activator_create_instance;
2086 static void InitGenericCoreTypes ()
2088 activator_type = CoreLookupType ("System", "Activator");
2090 generic_ilist_type = CoreLookupType (
2091 "System.Collections.Generic", "IList", 1);
2092 generic_icollection_type = CoreLookupType (
2093 "System.Collections.Generic", "ICollection", 1);
2094 generic_ienumerator_type = CoreLookupType (
2095 "System.Collections.Generic", "IEnumerator", 1);
2096 generic_ienumerable_type = CoreLookupType (
2097 "System.Collections.Generic", "IEnumerable", 1);
2098 generic_nullable_type = CoreLookupType (
2099 "System", "Nullable", 1);
2102 static void InitGenericCodeHelpers ()
2105 activator_create_instance = GetMethod (
2106 activator_type, "CreateInstance", Type.EmptyTypes);
2109 static Type CoreLookupType (string ns, string name, int arity)
2111 return CoreLookupType (ns, MemberName.MakeName (name, arity));
2114 public static TypeContainer LookupGenericTypeContainer (Type t)
2116 t = DropGenericTypeArguments (t);
2117 return LookupTypeContainer (t);
2120 public static GenericConstraints GetTypeParameterConstraints (Type t)
2122 if (!t.IsGenericParameter)
2123 throw new InvalidOperationException ();
2125 TypeParameter tparam = LookupTypeParameter (t);
2127 return tparam.GenericConstraints;
2129 return ReflectionConstraints.GetConstraints (t);
2133 /// Check whether `a' and `b' may become equal generic types.
2134 /// The algorithm to do that is a little bit complicated.
2136 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_inferred,
2137 Type[] method_inferred)
2139 if (a.IsGenericParameter) {
2141 // If a is an array of a's type, they may never
2145 b = b.GetElementType ();
2151 // If b is a generic parameter or an actual type,
2152 // they may become equal:
2154 // class X<T,U> : I<T>, I<U>
2155 // class X<T> : I<T>, I<float>
2157 if (b.IsGenericParameter || !b.IsGenericType) {
2158 int pos = a.GenericParameterPosition;
2159 Type[] args = a.DeclaringMethod != null ? method_inferred : class_inferred;
2160 if (args [pos] == null) {
2165 return args [pos] == a;
2169 // We're now comparing a type parameter with a
2170 // generic instance. They may become equal unless
2171 // the type parameter appears anywhere in the
2172 // generic instance:
2174 // class X<T,U> : I<T>, I<X<U>>
2175 // -> error because you could instanciate it as
2178 // class X<T> : I<T>, I<X<T>> -> ok
2181 Type[] bargs = GetTypeArguments (b);
2182 for (int i = 0; i < bargs.Length; i++) {
2183 if (a.Equals (bargs [i]))
2190 if (b.IsGenericParameter)
2191 return MayBecomeEqualGenericTypes (b, a, class_inferred, method_inferred);
2194 // At this point, neither a nor b are a type parameter.
2196 // If one of them is a generic instance, let
2197 // MayBecomeEqualGenericInstances() compare them (if the
2198 // other one is not a generic instance, they can never
2202 if (a.IsGenericType || b.IsGenericType)
2203 return MayBecomeEqualGenericInstances (a, b, class_inferred, method_inferred);
2206 // If both of them are arrays.
2209 if (a.IsArray && b.IsArray) {
2210 if (a.GetArrayRank () != b.GetArrayRank ())
2213 a = a.GetElementType ();
2214 b = b.GetElementType ();
2216 return MayBecomeEqualGenericTypes (a, b, class_inferred, method_inferred);
2220 // Ok, two ordinary types.
2223 return a.Equals (b);
2227 // Checks whether two generic instances may become equal for some
2228 // particular instantiation (26.3.1).
2230 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
2231 Type[] class_inferred,
2232 Type[] method_inferred)
2234 if (!a.IsGenericType || !b.IsGenericType)
2236 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2239 return MayBecomeEqualGenericInstances (
2240 GetTypeArguments (a), GetTypeArguments (b), class_inferred, method_inferred);
2243 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
2244 Type[] class_inferred,
2245 Type[] method_inferred)
2247 if (aargs.Length != bargs.Length)
2250 for (int i = 0; i < aargs.Length; i++) {
2251 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_inferred, method_inferred))
2258 static bool UnifyType (Type pt, Type at, Type[] inferred)
2260 if (pt.IsGenericParameter) {
2261 if (pt.DeclaringMethod == null)
2264 int pos = pt.GenericParameterPosition;
2266 if (inferred [pos] == null)
2267 inferred [pos] = at;
2269 return inferred [pos] == at;
2272 if (!pt.ContainsGenericParameters) {
2273 if (at.ContainsGenericParameters)
2274 return UnifyType (at, pt, inferred);
2281 if (at.GetArrayRank () != pt.GetArrayRank ())
2284 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2287 if (!pt.IsGenericType)
2290 Type gt = pt.GetGenericTypeDefinition ();
2291 if ((gt != generic_ilist_type) && (gt != generic_icollection_type) &&
2292 (gt != generic_ienumerable_type))
2295 Type[] args = GetTypeArguments (pt);
2296 return UnifyType (args [0], at.GetElementType (), inferred);
2301 (pt.GetArrayRank () != at.GetArrayRank ()))
2304 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2307 if (pt.IsByRef && at.IsByRef)
2308 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2309 ArrayList list = new ArrayList ();
2310 if (at.IsGenericType)
2312 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
2315 list.AddRange (TypeManager.GetInterfaces (at));
2317 foreach (Type type in list) {
2318 if (!type.IsGenericType)
2321 if (DropGenericTypeArguments (pt) != DropGenericTypeArguments (type))
2324 if (!UnifyTypes (pt.GetGenericArguments (), type.GetGenericArguments (), inferred))
2331 static bool UnifyTypes (Type[] pts, Type [] ats, Type [] inferred)
2333 for (int i = 0; i < ats.Length; i++) {
2334 if (!UnifyType (pts [i], ats [i], inferred))
2341 /// Type inference. Try to infer the type arguments from the params method
2342 /// `method', which is invoked with the arguments `arguments'. This is used
2343 /// when resolving an Invocation or a DelegateInvocation and the user
2344 /// did not explicitly specify type arguments.
2346 public static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
2347 ref MethodBase method)
2349 if (!TypeManager.IsGenericMethod (method))
2352 // if there are no arguments, there's no way to infer the type-arguments
2353 if (arguments == null || arguments.Count == 0)
2356 ParameterData pd = TypeManager.GetParameterData (method);
2357 int pd_count = pd.Count;
2358 int arg_count = arguments.Count;
2363 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2366 if (pd_count - 1 > arg_count)
2369 Type[] method_args = method.GetGenericArguments ();
2370 Type[] inferred_types = new Type [method_args.Length];
2373 // If we have come this far, the case which
2374 // remains is when the number of parameters is
2375 // less than or equal to the argument count.
2377 for (int i = 0; i < pd_count - 1; ++i) {
2378 Argument a = (Argument) arguments [i];
2380 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2383 Type pt = pd.ParameterType (i);
2386 if (!UnifyType (pt, at, inferred_types))
2390 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
2392 for (int i = pd_count - 1; i < arg_count; i++) {
2393 Argument a = (Argument) arguments [i];
2395 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2398 if (!UnifyType (element_type, a.Type, inferred_types))
2402 for (int i = 0; i < inferred_types.Length; i++)
2403 if (inferred_types [i] == null)
2406 method = ((MethodInfo)method).MakeGenericMethod (inferred_types);
2410 static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
2411 Type[] inferred_types)
2413 for (int i = 0; i < arg_types.Length; i++) {
2414 if (arg_types [i] == null)
2417 if (!UnifyType (param_types [i], arg_types [i], inferred_types))
2421 for (int i = 0; i < inferred_types.Length; ++i)
2422 if (inferred_types [i] == null)
2429 // Infers the type of a single LambdaExpression in the invocation call and
2430 // stores the infered type in the inferred_types array.
2432 // The index of the arguments that contain lambdas is passed in
2434 // @lambdas. Merely to avoid rescanning the list.
2436 // The method being called:
2437 // @method_generic_args: The generic type arguments for the method being called
2438 // @method_pd: The ParameterData for the method being called.
2441 // @arguments: Arraylist of Argument()s. The arguments being passed.
2444 // @inferred_types: the array that is populated with our results.
2446 // true if the code was able to do one inference.
2448 static bool LambdaInfer (EmitContext ec,
2449 Type [] method_generic_args,
2450 ParameterData method_pd,
2451 ArrayList arguments,
2452 Type[] inferred_types,
2455 int last_count = lambdas.Count;
2457 for (int i = 0; i < last_count; i++){
2458 int argn = (int) lambdas [i];
2460 Argument a = (Argument) arguments [argn];
2462 LambdaExpression le = a.Expr as LambdaExpression;
2465 throw new Exception (
2466 String.Format ("Internal Compiler error: argument {0} should be a Lambda Expression",
2470 // "The corresponding parameter’s type, in the
2471 // following called P, is a delegate type with a
2472 // return type that involves one or more method type
2476 if (!TypeManager.IsDelegateType (method_pd.ParameterType (argn)))
2477 goto useless_lambda;
2479 Type p_type = method_pd.ParameterType (argn);
2480 MethodGroupExpr method_group = Expression.MemberLookup (
2481 ec.ContainerType, p_type, "Invoke", MemberTypes.Method,
2482 Expression.AllBindingFlags, Location.Null) as MethodGroupExpr;
2484 if (method_group == null){
2485 // This we report elsewhere as -200, but here we can ignore
2486 goto useless_lambda;
2488 MethodInfo p_delegate_method = method_group.Methods [0] as MethodInfo;
2489 if (p_delegate_method == null){
2490 // This should not happen.
2491 goto useless_lambda;
2494 Type p_return_type = p_delegate_method.ReturnType;
2495 if (!p_return_type.IsGenericParameter)
2496 goto useless_lambda;
2499 // P and L have the same number of parameters, and
2500 // each parameter in P has the same modifiers as the
2501 // corresponding parameter in L, or no modifiers if
2502 // L has an implicitly typed parameter list.
2504 ParameterData p_delegate_parameters = TypeManager.GetParameterData (p_delegate_method);
2505 int p_delegate_parameter_count = p_delegate_parameters.Count;
2506 if (p_delegate_parameter_count != le.Parameters.Count)
2507 goto useless_lambda;
2509 if (le.HasExplicitParameters){
2510 for (int j = 0; j < p_delegate_parameter_count; j++){
2511 if (p_delegate_parameters.ParameterModifier (j) !=
2512 le.Parameters.ParameterModifier (j))
2513 goto useless_lambda;
2516 for (int j = 0; j < p_delegate_parameter_count; j++)
2517 if (le.Parameters.ParameterModifier (j) != Parameter.Modifier.NONE)
2518 goto useless_lambda;
2522 // TODO: P’s parameter types involve no method type
2523 // parameters or involve only method type parameters
2524 // for which a consistent set of inferences have
2525 // already been made.
2527 //Console.WriteLine ("Method: {0}", p_delegate_method);
2528 //for (int j = 0; j < p_delegate_parameter_count; j++){
2529 //Console.WriteLine ("PType [{2}, {0}] = {1}", j, p_delegate_parameters.ParameterType (j), argn);
2533 // At this point we know that P has method type parameters
2534 // that involve only type parameters that have a consistent
2535 // set of inferences made.
2537 if (le.HasExplicitParameters){
2539 // TODO: If L has an explicitly typed parameter
2540 // list, when inferred types are substituted for
2541 // method type parameters in P, each parameter in P
2542 // has the same type as the corresponding parameter
2547 // TODO: If L has an implicitly typed parameter
2548 // list, when inferred types are substituted for
2549 // method type parameters in P and the resulting
2550 // parameter types are given to the parameters of L,
2551 // the body of L is a valid expression or statement
2554 Type [] types = new Type [p_delegate_parameter_count];
2556 //bool failure = false;
2557 for (int j = 0; j < p_delegate_parameter_count; j++){
2558 Type p_pt = p_delegate_parameters.ParameterType (j);
2560 if (!p_pt.IsGenericParameter){
2565 //bool found = false;
2566 for (int k = 0; k < method_generic_args.Length; k++){
2567 if (method_generic_args [k] == p_pt){
2568 types [j] = inferred_types [k];
2573 // If we could not infer just yet, continue
2575 if (types [j] == null)
2580 // If it results in a valid expression or statement block
2582 Type lambda_inferred_type = le.TryBuild (ec, types);
2584 if (lambda_inferred_type != null){
2586 // Success, set the proper inferred_type value to the new type.
2589 for (int k = 0; k < method_generic_args.Length; k++){
2590 if (method_generic_args [k] == p_return_type){
2591 inferred_types [k] = lambda_inferred_type;
2593 lambdas.RemoveAt (i);
2601 lambdas.RemoveAt (i);
2608 Console.WriteLine ("Inferred types");
2609 foreach (Type it in inferred_types){
2610 Console.WriteLine (" IT: {0}", it);
2616 // No inference was made in any of the elements.
2621 /// Type inference. Try to infer the type arguments from `method',
2622 /// which is invoked with the arguments `arguments'. This is used
2623 /// when resolving an Invocation or a DelegateInvocation and the user
2624 /// did not explicitly specify type arguments.
2626 public static bool InferTypeArguments (EmitContext ec,
2627 ArrayList arguments,
2628 ref MethodBase method)
2630 if (!TypeManager.IsGenericMethod (method))
2634 if (arguments != null)
2635 arg_count = arguments.Count;
2639 ParameterData pd = TypeManager.GetParameterData (method);
2640 if (arg_count != pd.Count)
2643 Type[] method_generic_args = method.GetGenericArguments ();
2645 bool is_open = false;
2647 for (int i = 0; i < method_generic_args.Length; i++) {
2648 if (method_generic_args [i].IsGenericParameter) {
2654 // If none of the method parameters mention a generic parameter, we can't infer the generic parameters
2656 return !TypeManager.IsGenericMethodDefinition (method);
2658 Type[] inferred_types = new Type [method_generic_args.Length];
2660 Type[] param_types = new Type [pd.Count];
2661 Type[] arg_types = new Type [pd.Count];
2662 ArrayList lambdas = null;
2664 for (int i = 0; i < arg_count; i++) {
2665 param_types [i] = pd.ParameterType (i);
2667 Argument a = (Argument) arguments [i];
2668 if (a.Expr is NullLiteral || a.Expr is MethodGroupExpr)
2671 if (a.Expr is LambdaExpression){
2672 if (lambdas == null)
2673 lambdas = new ArrayList ();
2676 else if (a.Expr is AnonymousMethodExpression) {
2677 if (RootContext.Version != LanguageVersion.LINQ)
2680 Type dtype = param_types[i];
2681 if (!TypeManager.IsDelegateType (dtype))
2684 AnonymousMethodExpression am = (AnonymousMethodExpression)a.Expr;
2685 Expression e = am.InferTypeArguments (ec, dtype);
2689 arg_types[i] = e.Type;
2693 arg_types [i] = a.Type;
2696 if (!InferTypeArguments (param_types, arg_types, inferred_types)){
2697 //Console.WriteLine ("InferTypeArgument found {0} lambdas ", lambdas);
2698 if (lambdas == null)
2702 // While the lambda expressions lead to a valid inference
2706 lambda_count = lambdas.Count;
2707 if (!LambdaInfer (ec, method_generic_args, pd, arguments, inferred_types, lambdas))
2709 } while (lambdas.Count != 0 && lambdas.Count != lambda_count);
2712 method = ((MethodInfo)method).MakeGenericMethod (inferred_types);
2715 // MS implementation throws NotSupportedException for GetParameters
2716 // on unbaked generic method
2717 ParameterData p = TypeManager.GetParameterData (method);
2718 p.InflateTypes (param_types, inferred_types);
2727 public static bool InferTypeArguments (ParameterData apd,
2728 ref MethodBase method)
2730 if (!TypeManager.IsGenericMethod (method))
2733 ParameterData pd = TypeManager.GetParameterData (method);
2734 if (apd.Count != pd.Count)
2737 Type[] method_args = method.GetGenericArguments ();
2738 Type[] inferred_types = new Type [method_args.Length];
2740 Type[] param_types = new Type [pd.Count];
2741 Type[] arg_types = new Type [pd.Count];
2743 for (int i = 0; i < apd.Count; i++) {
2744 param_types [i] = pd.ParameterType (i);
2745 arg_types [i] = apd.ParameterType (i);
2748 if (!InferTypeArguments (param_types, arg_types, inferred_types))
2751 method = ((MethodInfo)method).MakeGenericMethod (inferred_types);
2756 public abstract class Nullable
2758 public sealed class NullableInfo
2760 public readonly Type Type;
2761 public readonly Type UnderlyingType;
2762 public readonly MethodInfo HasValue;
2763 public readonly MethodInfo Value;
2764 public readonly ConstructorInfo Constructor;
2766 public NullableInfo (Type type)
2769 UnderlyingType = TypeManager.GetTypeArguments (type) [0];
2771 PropertyInfo has_value_pi = TypeManager.GetProperty (type, "HasValue");
2772 PropertyInfo value_pi = TypeManager.GetProperty (type, "Value");
2774 HasValue = has_value_pi.GetGetMethod (false);
2775 Value = value_pi.GetGetMethod (false);
2776 Constructor = type.GetConstructor (new Type[] { UnderlyingType });
2780 public class Unwrap : Expression, IMemoryLocation, IAssignMethod
2785 LocalTemporary temp;
2788 protected Unwrap (Expression expr)
2791 this.loc = expr.Location;
2794 public static Unwrap Create (Expression expr, EmitContext ec)
2796 return new Unwrap (expr).Resolve (ec) as Unwrap;
2799 public override Expression DoResolve (EmitContext ec)
2801 expr = expr.Resolve (ec);
2805 temp = new LocalTemporary (expr.Type);
2807 info = new NullableInfo (expr.Type);
2808 type = info.UnderlyingType;
2809 eclass = expr.eclass;
2813 public override void Emit (EmitContext ec)
2815 AddressOf (ec, AddressOp.LoadStore);
2816 ec.ig.EmitCall (OpCodes.Call, info.Value, null);
2819 public void EmitCheck (EmitContext ec)
2821 AddressOf (ec, AddressOp.LoadStore);
2822 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
2825 public void Store (EmitContext ec)
2830 void create_temp (EmitContext ec)
2832 if ((temp != null) && !has_temp) {
2839 public void AddressOf (EmitContext ec, AddressOp mode)
2843 temp.AddressOf (ec, AddressOp.LoadStore);
2845 ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
2848 public void Emit (EmitContext ec, bool leave_copy)
2861 public void EmitAssign (EmitContext ec, Expression source,
2862 bool leave_copy, bool prepare_for_load)
2864 InternalWrap wrap = new InternalWrap (source, info, loc);
2865 ((IAssignMethod) expr).EmitAssign (ec, wrap, leave_copy, false);
2868 protected class InternalWrap : Expression
2870 public Expression expr;
2871 public NullableInfo info;
2873 public InternalWrap (Expression expr, NullableInfo info, Location loc)
2880 eclass = ExprClass.Value;
2883 public override Expression DoResolve (EmitContext ec)
2888 public override void Emit (EmitContext ec)
2891 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2896 public class Wrap : Expression
2901 protected Wrap (Expression expr)
2904 this.loc = expr.Location;
2907 public static Wrap Create (Expression expr, EmitContext ec)
2909 return new Wrap (expr).Resolve (ec) as Wrap;
2912 public override Expression DoResolve (EmitContext ec)
2914 expr = expr.Resolve (ec);
2918 TypeExpr target_type = new NullableType (expr.Type, loc);
2919 target_type = target_type.ResolveAsTypeTerminal (ec, false);
2920 if (target_type == null)
2923 type = target_type.Type;
2924 info = new NullableInfo (type);
2925 eclass = ExprClass.Value;
2929 public override void Emit (EmitContext ec)
2932 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2936 public class NullableLiteral : NullLiteral, IMemoryLocation {
2937 public NullableLiteral (Type target_type, Location loc)
2940 this.type = target_type;
2942 eclass = ExprClass.Value;
2945 public override Expression DoResolve (EmitContext ec)
2950 public override void Emit (EmitContext ec)
2952 LocalTemporary value_target = new LocalTemporary (type);
2954 value_target.AddressOf (ec, AddressOp.Store);
2955 ec.ig.Emit (OpCodes.Initobj, type);
2956 value_target.Emit (ec);
2959 public void AddressOf (EmitContext ec, AddressOp Mode)
2961 LocalTemporary value_target = new LocalTemporary (type);
2963 value_target.AddressOf (ec, AddressOp.Store);
2964 ec.ig.Emit (OpCodes.Initobj, type);
2965 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
2969 public abstract class Lifted : Expression, IMemoryLocation
2971 Expression expr, underlying, wrap, null_value;
2974 protected Lifted (Expression expr, Location loc)
2980 public override Expression DoResolve (EmitContext ec)
2982 expr = expr.Resolve (ec);
2986 unwrap = Unwrap.Create (expr, ec);
2990 underlying = ResolveUnderlying (unwrap, ec);
2991 if (underlying == null)
2994 wrap = Wrap.Create (underlying, ec);
2998 null_value = new NullableLiteral (wrap.Type, loc).Resolve (ec);
2999 if (null_value == null)
3003 eclass = ExprClass.Value;
3007 protected abstract Expression ResolveUnderlying (Expression unwrap, EmitContext ec);
3009 public override void Emit (EmitContext ec)
3011 ILGenerator ig = ec.ig;
3012 Label is_null_label = ig.DefineLabel ();
3013 Label end_label = ig.DefineLabel ();
3015 unwrap.EmitCheck (ec);
3016 ig.Emit (OpCodes.Brfalse, is_null_label);
3019 ig.Emit (OpCodes.Br, end_label);
3021 ig.MarkLabel (is_null_label);
3022 null_value.Emit (ec);
3024 ig.MarkLabel (end_label);
3027 public void AddressOf (EmitContext ec, AddressOp mode)
3029 unwrap.AddressOf (ec, mode);
3033 public class LiftedConversion : Lifted
3035 public readonly bool IsUser;
3036 public readonly bool IsExplicit;
3037 public readonly Type TargetType;
3039 public LiftedConversion (Expression expr, Type target_type, bool is_user,
3040 bool is_explicit, Location loc)
3043 this.IsUser = is_user;
3044 this.IsExplicit = is_explicit;
3045 this.TargetType = target_type;
3048 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
3050 Type type = TypeManager.GetTypeArguments (TargetType) [0];
3053 return Convert.UserDefinedConversion (ec, unwrap, type, loc, IsExplicit);
3056 return Convert.ExplicitConversion (ec, unwrap, type, loc);
3058 return Convert.ImplicitConversion (ec, unwrap, type, loc);
3063 public class LiftedUnaryOperator : Lifted
3065 public readonly Unary.Operator Oper;
3067 public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
3073 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
3075 return new Unary (Oper, unwrap, loc);
3079 public class LiftedConditional : Lifted
3081 Expression true_expr, false_expr;
3083 public LiftedConditional (Expression expr, Expression true_expr, Expression false_expr,
3087 this.true_expr = true_expr;
3088 this.false_expr = false_expr;
3091 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
3093 return new Conditional (unwrap, true_expr, false_expr);
3097 public class LiftedBinaryOperator : Expression
3099 public readonly Binary.Operator Oper;
3101 Expression left, right, original_left, original_right;
3102 Expression underlying, null_value, bool_wrap;
3103 Unwrap left_unwrap, right_unwrap;
3104 bool is_equality, is_comparision, is_boolean;
3106 public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
3110 this.left = original_left = left;
3111 this.right = original_right = right;
3115 public override Expression DoResolve (EmitContext ec)
3117 if (TypeManager.IsNullableType (left.Type)) {
3118 left = left_unwrap = Unwrap.Create (left, ec);
3123 if (TypeManager.IsNullableType (right.Type)) {
3124 right = right_unwrap = Unwrap.Create (right, ec);
3129 if ((Oper == Binary.Operator.LogicalAnd) ||
3130 (Oper == Binary.Operator.LogicalOr)) {
3131 Binary.Error_OperatorCannotBeApplied (
3132 loc, Binary.OperName (Oper),
3133 original_left.GetSignatureForError (),
3134 original_right.GetSignatureForError ());
3138 if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr)) &&
3139 ((left.Type == TypeManager.bool_type) && (right.Type == TypeManager.bool_type))) {
3140 Expression empty = new EmptyExpression (TypeManager.bool_type);
3141 bool_wrap = Wrap.Create (empty, ec);
3142 null_value = new NullableLiteral (bool_wrap.Type, loc).Resolve (ec);
3144 type = bool_wrap.Type;
3146 } else if ((Oper == Binary.Operator.Equality) || (Oper == Binary.Operator.Inequality)) {
3147 if (!(left is NullLiteral) && !(right is NullLiteral)) {
3148 underlying = new Binary (Oper, left, right).Resolve (ec);
3149 if (underlying == null)
3153 type = TypeManager.bool_type;
3155 } else if ((Oper == Binary.Operator.LessThan) ||
3156 (Oper == Binary.Operator.GreaterThan) ||
3157 (Oper == Binary.Operator.LessThanOrEqual) ||
3158 (Oper == Binary.Operator.GreaterThanOrEqual)) {
3159 underlying = new Binary (Oper, left, right).Resolve (ec);
3160 if (underlying == null)
3163 type = TypeManager.bool_type;
3164 is_comparision = true;
3166 underlying = new Binary (Oper, left, right).Resolve (ec);
3167 if (underlying == null)
3170 underlying = Wrap.Create (underlying, ec);
3171 if (underlying == null)
3174 type = underlying.Type;
3175 null_value = new NullableLiteral (type, loc).Resolve (ec);
3178 eclass = ExprClass.Value;
3182 void EmitBoolean (EmitContext ec)
3184 ILGenerator ig = ec.ig;
3186 Label left_is_null_label = ig.DefineLabel ();
3187 Label right_is_null_label = ig.DefineLabel ();
3188 Label is_null_label = ig.DefineLabel ();
3189 Label wrap_label = ig.DefineLabel ();
3190 Label end_label = ig.DefineLabel ();
3192 if (left_unwrap != null) {
3193 left_unwrap.EmitCheck (ec);
3194 ig.Emit (OpCodes.Brfalse, left_is_null_label);
3198 ig.Emit (OpCodes.Dup);
3199 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3200 ig.Emit (OpCodes.Brtrue, wrap_label);
3202 ig.Emit (OpCodes.Brfalse, wrap_label);
3204 if (right_unwrap != null) {
3205 right_unwrap.EmitCheck (ec);
3206 ig.Emit (OpCodes.Brfalse, right_is_null_label);
3209 if ((Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr))
3210 ig.Emit (OpCodes.Pop);
3213 if (Oper == Binary.Operator.BitwiseOr)
3214 ig.Emit (OpCodes.Or);
3215 else if (Oper == Binary.Operator.BitwiseAnd)
3216 ig.Emit (OpCodes.And);
3217 ig.Emit (OpCodes.Br, wrap_label);
3219 ig.MarkLabel (left_is_null_label);
3220 if (right_unwrap != null) {
3221 right_unwrap.EmitCheck (ec);
3222 ig.Emit (OpCodes.Brfalse, is_null_label);
3226 ig.Emit (OpCodes.Dup);
3227 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3228 ig.Emit (OpCodes.Brtrue, wrap_label);
3230 ig.Emit (OpCodes.Brfalse, wrap_label);
3232 ig.MarkLabel (right_is_null_label);
3233 ig.Emit (OpCodes.Pop);
3234 ig.MarkLabel (is_null_label);
3235 null_value.Emit (ec);
3236 ig.Emit (OpCodes.Br, end_label);
3238 ig.MarkLabel (wrap_label);
3239 ig.Emit (OpCodes.Nop);
3240 bool_wrap.Emit (ec);
3241 ig.Emit (OpCodes.Nop);
3243 ig.MarkLabel (end_label);
3246 void EmitEquality (EmitContext ec)
3248 ILGenerator ig = ec.ig;
3250 // Given 'X? x;' for any value type X: 'x != null' is the same as 'x.HasValue'
3251 if (left is NullLiteral) {
3252 if (right_unwrap == null)
3253 throw new InternalErrorException ();
3254 right_unwrap.EmitCheck (ec);
3255 if (Oper == Binary.Operator.Equality) {
3256 ig.Emit (OpCodes.Ldc_I4_0);
3257 ig.Emit (OpCodes.Ceq);
3262 if (right is NullLiteral) {
3263 if (left_unwrap == null)
3264 throw new InternalErrorException ();
3265 left_unwrap.EmitCheck (ec);
3266 if (Oper == Binary.Operator.Equality) {
3267 ig.Emit (OpCodes.Ldc_I4_0);
3268 ig.Emit (OpCodes.Ceq);
3273 Label both_have_value_label = ig.DefineLabel ();
3274 Label end_label = ig.DefineLabel ();
3276 if (left_unwrap != null && right_unwrap != null) {
3277 Label dissimilar_label = ig.DefineLabel ();
3279 left_unwrap.EmitCheck (ec);
3280 ig.Emit (OpCodes.Dup);
3281 right_unwrap.EmitCheck (ec);
3282 ig.Emit (OpCodes.Bne_Un, dissimilar_label);
3284 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3287 if (Oper == Binary.Operator.Equality)
3288 ig.Emit (OpCodes.Ldc_I4_1);
3290 ig.Emit (OpCodes.Ldc_I4_0);
3291 ig.Emit (OpCodes.Br, end_label);
3293 ig.MarkLabel (dissimilar_label);
3294 ig.Emit (OpCodes.Pop);
3295 } else if (left_unwrap != null) {
3296 left_unwrap.EmitCheck (ec);
3297 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3298 } else if (right_unwrap != null) {
3299 right_unwrap.EmitCheck (ec);
3300 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3302 throw new InternalErrorException ("shouldn't get here");
3305 // one is null while the other isn't
3306 if (Oper == Binary.Operator.Equality)
3307 ig.Emit (OpCodes.Ldc_I4_0);
3309 ig.Emit (OpCodes.Ldc_I4_1);
3310 ig.Emit (OpCodes.Br, end_label);
3312 ig.MarkLabel (both_have_value_label);
3313 underlying.Emit (ec);
3315 ig.MarkLabel (end_label);
3318 void EmitComparision (EmitContext ec)
3320 ILGenerator ig = ec.ig;
3322 Label is_null_label = ig.DefineLabel ();
3323 Label end_label = ig.DefineLabel ();
3325 if (left_unwrap != null) {
3326 left_unwrap.EmitCheck (ec);
3327 ig.Emit (OpCodes.Brfalse, is_null_label);
3330 if (right_unwrap != null) {
3331 right_unwrap.EmitCheck (ec);
3332 ig.Emit (OpCodes.Brfalse, is_null_label);
3335 underlying.Emit (ec);
3336 ig.Emit (OpCodes.Br, end_label);
3338 ig.MarkLabel (is_null_label);
3339 ig.Emit (OpCodes.Ldc_I4_0);
3341 ig.MarkLabel (end_label);
3344 public override void Emit (EmitContext ec)
3346 if (left_unwrap != null)
3347 left_unwrap.Store (ec);
3348 if (right_unwrap != null)
3349 right_unwrap.Store (ec);
3354 } else if (is_equality) {
3357 } else if (is_comparision) {
3358 EmitComparision (ec);
3362 ILGenerator ig = ec.ig;
3364 Label is_null_label = ig.DefineLabel ();
3365 Label end_label = ig.DefineLabel ();
3367 if (left_unwrap != null) {
3368 left_unwrap.EmitCheck (ec);
3369 ig.Emit (OpCodes.Brfalse, is_null_label);
3372 if (right_unwrap != null) {
3373 right_unwrap.EmitCheck (ec);
3374 ig.Emit (OpCodes.Brfalse, is_null_label);
3377 underlying.Emit (ec);
3378 ig.Emit (OpCodes.Br, end_label);
3380 ig.MarkLabel (is_null_label);
3381 null_value.Emit (ec);
3383 ig.MarkLabel (end_label);
3387 public class OperatorTrueOrFalse : Expression
3389 public readonly bool IsTrue;
3394 public OperatorTrueOrFalse (Expression expr, bool is_true, Location loc)
3396 this.IsTrue = is_true;
3401 public override Expression DoResolve (EmitContext ec)
3403 unwrap = Unwrap.Create (expr, ec);
3407 if (unwrap.Type != TypeManager.bool_type)
3410 type = TypeManager.bool_type;
3411 eclass = ExprClass.Value;
3415 public override void Emit (EmitContext ec)
3417 ILGenerator ig = ec.ig;
3419 Label is_null_label = ig.DefineLabel ();
3420 Label end_label = ig.DefineLabel ();
3422 unwrap.EmitCheck (ec);
3423 ig.Emit (OpCodes.Brfalse, is_null_label);
3427 ig.Emit (OpCodes.Ldc_I4_0);
3428 ig.Emit (OpCodes.Ceq);
3430 ig.Emit (OpCodes.Br, end_label);
3432 ig.MarkLabel (is_null_label);
3433 ig.Emit (OpCodes.Ldc_I4_0);
3435 ig.MarkLabel (end_label);
3439 public class NullCoalescingOperator : Expression
3441 Expression left, right;
3445 public NullCoalescingOperator (Expression left, Expression right, Location loc)
3451 eclass = ExprClass.Value;
3454 public override Expression DoResolve (EmitContext ec)
3459 left = left.Resolve (ec);
3463 right = right.Resolve (ec);
3467 Type ltype = left.Type, rtype = right.Type;
3469 if (!TypeManager.IsNullableType (ltype) && ltype.IsValueType) {
3470 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3474 if (TypeManager.IsNullableType (ltype)) {
3475 NullableInfo info = new NullableInfo (ltype);
3477 unwrap = Unwrap.Create (left, ec);
3481 expr = Convert.ImplicitConversion (ec, right, info.UnderlyingType, loc);
3489 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
3495 Expression left_null = unwrap != null ? unwrap : left;
3496 expr = Convert.ImplicitConversion (ec, left_null, rtype, loc);
3504 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3508 public override void Emit (EmitContext ec)
3510 ILGenerator ig = ec.ig;
3512 Label is_null_label = ig.DefineLabel ();
3513 Label end_label = ig.DefineLabel ();
3515 if (unwrap != null) {
3516 unwrap.EmitCheck (ec);
3517 ig.Emit (OpCodes.Brfalse, is_null_label);
3520 ig.Emit (OpCodes.Br, end_label);
3522 ig.MarkLabel (is_null_label);
3525 ig.MarkLabel (end_label);
3528 ig.Emit (OpCodes.Dup);
3529 ig.Emit (OpCodes.Brtrue, end_label);
3531 ig.MarkLabel (is_null_label);
3533 ig.Emit (OpCodes.Pop);
3536 ig.MarkLabel (end_label);
3541 public class LiftedUnaryMutator : ExpressionStatement
3543 public readonly UnaryMutator.Mode Mode;
3544 Expression expr, null_value;
3545 UnaryMutator underlying;
3548 public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
3554 eclass = ExprClass.Value;
3557 public override Expression DoResolve (EmitContext ec)
3559 expr = expr.Resolve (ec);
3563 unwrap = Unwrap.Create (expr, ec);
3567 underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
3568 if (underlying == null)
3571 null_value = new NullableLiteral (expr.Type, loc).Resolve (ec);
3572 if (null_value == null)
3579 void DoEmit (EmitContext ec, bool is_expr)
3581 ILGenerator ig = ec.ig;
3582 Label is_null_label = ig.DefineLabel ();
3583 Label end_label = ig.DefineLabel ();
3585 unwrap.EmitCheck (ec);
3586 ig.Emit (OpCodes.Brfalse, is_null_label);
3589 underlying.Emit (ec);
3591 underlying.EmitStatement (ec);
3592 ig.Emit (OpCodes.Br, end_label);
3594 ig.MarkLabel (is_null_label);
3596 null_value.Emit (ec);
3598 ig.MarkLabel (end_label);
3601 public override void Emit (EmitContext ec)
3606 public override void EmitStatement (EmitContext ec)