2 // generic.cs: Generics support
4 // Authors: Martin Baulig (martin@ximian.com)
5 // Miguel de Icaza (miguel@ximian.com)
6 // Marek Safar (marek.safar@gmail.com)
8 // Licensed under the terms of the GNU GPL
10 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // (C) 2004 Novell, Inc
14 using System.Reflection;
15 using System.Reflection.Emit;
16 using System.Globalization;
17 using System.Collections;
19 using System.Text.RegularExpressions;
21 namespace Mono.CSharp {
24 /// Abstract base class for type parameter constraints.
25 /// The type parameter can come from a generic type definition or from reflection.
27 public abstract class GenericConstraints {
28 public abstract string TypeParameter {
32 public abstract GenericParameterAttributes Attributes {
36 public bool HasConstructorConstraint {
37 get { return (Attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0; }
40 public bool HasReferenceTypeConstraint {
41 get { return (Attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0; }
44 public bool HasValueTypeConstraint {
45 get { return (Attributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0; }
48 public virtual bool HasClassConstraint {
49 get { return ClassConstraint != null; }
52 public abstract Type ClassConstraint {
56 public abstract Type[] InterfaceConstraints {
60 public abstract Type EffectiveBaseClass {
65 // Returns whether the type parameter is "known to be a reference type".
67 public virtual bool IsReferenceType {
69 if (HasReferenceTypeConstraint)
71 if (HasValueTypeConstraint)
74 if (ClassConstraint != null) {
75 if (ClassConstraint.IsValueType)
78 if (ClassConstraint != TypeManager.object_type)
82 foreach (Type t in InterfaceConstraints) {
83 if (!t.IsGenericParameter)
86 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
87 if ((gc != null) && gc.IsReferenceType)
96 // Returns whether the type parameter is "known to be a value type".
98 public virtual bool IsValueType {
100 if (HasValueTypeConstraint)
102 if (HasReferenceTypeConstraint)
105 if (ClassConstraint != null) {
106 if (!ClassConstraint.IsValueType)
109 if (ClassConstraint != TypeManager.value_type)
113 foreach (Type t in InterfaceConstraints) {
114 if (!t.IsGenericParameter)
117 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
118 if ((gc != null) && gc.IsValueType)
127 public enum SpecialConstraint
135 /// Tracks the constraints for a type parameter from a generic type definition.
137 public class Constraints : GenericConstraints {
139 ArrayList constraints;
143 // name is the identifier, constraints is an arraylist of
144 // Expressions (with types) or `true' for the constructor constraint.
146 public Constraints (string name, ArrayList constraints,
150 this.constraints = constraints;
154 public override string TypeParameter {
160 public Constraints Clone ()
162 return new Constraints (name, constraints, loc);
165 GenericParameterAttributes attrs;
166 TypeExpr class_constraint;
167 ArrayList iface_constraints;
168 ArrayList type_param_constraints;
170 Type class_constraint_type;
171 Type[] iface_constraint_types;
172 Type effective_base_type;
177 /// Resolve the constraints - but only resolve things into Expression's, not
178 /// into actual types.
180 public bool Resolve (IResolveContext ec)
185 iface_constraints = new ArrayList ();
186 type_param_constraints = new ArrayList ();
188 foreach (object obj in constraints) {
189 if (HasConstructorConstraint) {
190 Report.Error (401, loc,
191 "The new() constraint must be the last constraint specified");
195 if (obj is SpecialConstraint) {
196 SpecialConstraint sc = (SpecialConstraint) obj;
198 if (sc == SpecialConstraint.Constructor) {
199 if (!HasValueTypeConstraint) {
200 attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
204 Report.Error (451, loc, "The `new()' constraint " +
205 "cannot be used with the `struct' constraint");
209 if ((num_constraints > 0) || HasReferenceTypeConstraint || HasValueTypeConstraint) {
210 Report.Error (449, loc, "The `class' or `struct' " +
211 "constraint must be the first constraint specified");
215 if (sc == SpecialConstraint.ReferenceType)
216 attrs |= GenericParameterAttributes.ReferenceTypeConstraint;
218 attrs |= GenericParameterAttributes.NotNullableValueTypeConstraint;
222 int errors = Report.Errors;
223 FullNamedExpression fn = ((Expression) obj).ResolveAsTypeStep (ec, false);
226 if (errors != Report.Errors)
229 NamespaceEntry.Error_NamespaceNotFound (loc, ((Expression)obj).GetSignatureForError ());
234 ConstructedType cexpr = fn as ConstructedType;
236 if (!cexpr.ResolveConstructedType (ec))
241 expr = ((Expression) obj).ResolveAsTypeTerminal (ec, false);
243 if ((expr == null) || (expr.Type == null))
246 if (!ec.GenericDeclContainer.IsAccessibleAs (fn.Type)) {
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 class_constraint_type == TypeManager.multicast_delegate_type) {
334 Report.Error (702, loc,
335 "A constraint cannot be special class `{0}'",
336 TypeManager.CSharpName (class_constraint_type));
341 if (class_constraint_type != null)
342 effective_base_type = class_constraint_type;
343 else if (HasValueTypeConstraint)
344 effective_base_type = TypeManager.value_type;
346 effective_base_type = TypeManager.object_type;
352 bool CheckTypeParameterConstraints (TypeParameter tparam, Hashtable seen)
354 seen.Add (tparam, true);
356 Constraints constraints = tparam.Constraints;
357 if (constraints == null)
360 if (constraints.HasValueTypeConstraint) {
361 Report.Error (456, loc, "Type parameter `{0}' has " +
362 "the `struct' constraint, so it cannot " +
363 "be used as a constraint for `{1}'",
368 if (constraints.type_param_constraints == null)
371 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
372 if (seen.Contains (expr.TypeParameter)) {
373 Report.Error (454, loc, "Circular constraint " +
374 "dependency involving `{0}' and `{1}'",
375 tparam.Name, expr.Name);
379 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
387 /// Resolve the constraints into actual types.
389 public bool ResolveTypes (IResolveContext ec)
394 resolved_types = true;
396 foreach (object obj in constraints) {
397 ConstructedType cexpr = obj as ConstructedType;
401 if (!cexpr.CheckConstraints (ec))
405 foreach (TypeParameterExpr expr in type_param_constraints) {
406 Hashtable seen = new Hashtable ();
407 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
411 for (int i = 0; i < iface_constraints.Count; ++i) {
412 TypeExpr iface_constraint = (TypeExpr) iface_constraints [i];
413 iface_constraint = iface_constraint.ResolveAsTypeTerminal (ec, false);
414 if (iface_constraint == null)
416 iface_constraints [i] = iface_constraint;
419 if (class_constraint != null) {
420 class_constraint = class_constraint.ResolveAsTypeTerminal (ec, false);
421 if (class_constraint == null)
429 /// Check whether there are no conflicts in our type parameter constraints.
431 /// This is an example:
435 /// where U : T, struct
437 public bool CheckDependencies ()
439 foreach (TypeParameterExpr expr in type_param_constraints) {
440 if (!CheckDependencies (expr.TypeParameter))
447 bool CheckDependencies (TypeParameter tparam)
449 Constraints constraints = tparam.Constraints;
450 if (constraints == null)
453 if (HasValueTypeConstraint && constraints.HasClassConstraint) {
454 Report.Error (455, loc, "Type parameter `{0}' inherits " +
455 "conflicting constraints `{1}' and `{2}'",
456 name, TypeManager.CSharpName (constraints.ClassConstraint),
461 if (HasClassConstraint && constraints.HasClassConstraint) {
462 Type t1 = ClassConstraint;
463 TypeExpr e1 = class_constraint;
464 Type t2 = constraints.ClassConstraint;
465 TypeExpr e2 = constraints.class_constraint;
467 if (!Convert.ImplicitReferenceConversionExists (e1, t2) &&
468 !Convert.ImplicitReferenceConversionExists (e2, t1)) {
469 Report.Error (455, loc,
470 "Type parameter `{0}' inherits " +
471 "conflicting constraints `{1}' and `{2}'",
472 name, TypeManager.CSharpName (t1), TypeManager.CSharpName (t2));
477 if (constraints.type_param_constraints == null)
480 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
481 if (!CheckDependencies (expr.TypeParameter))
488 public override GenericParameterAttributes Attributes {
489 get { return attrs; }
492 public override bool HasClassConstraint {
493 get { return class_constraint != null; }
496 public override Type ClassConstraint {
497 get { return class_constraint_type; }
500 public override Type[] InterfaceConstraints {
501 get { return iface_constraint_types; }
504 public override Type EffectiveBaseClass {
505 get { return effective_base_type; }
508 public bool IsSubclassOf (Type t)
510 if ((class_constraint_type != null) &&
511 class_constraint_type.IsSubclassOf (t))
514 if (iface_constraint_types == null)
517 foreach (Type iface in iface_constraint_types) {
518 if (TypeManager.IsSubclassOf (iface, t))
525 public Location Location {
532 /// This is used when we're implementing a generic interface method.
533 /// Each method type parameter in implementing method must have the same
534 /// constraints than the corresponding type parameter in the interface
535 /// method. To do that, we're called on each of the implementing method's
538 public bool CheckInterfaceMethod (GenericConstraints gc)
540 if (gc.Attributes != attrs)
543 if (HasClassConstraint != gc.HasClassConstraint)
545 if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
548 int gc_icount = gc.InterfaceConstraints != null ?
549 gc.InterfaceConstraints.Length : 0;
550 int icount = InterfaceConstraints != null ?
551 InterfaceConstraints.Length : 0;
553 if (gc_icount != icount)
556 for (int i = 0; i < gc.InterfaceConstraints.Length; ++i) {
557 Type iface = gc.InterfaceConstraints [i];
558 if (iface.IsGenericType)
559 iface = iface.GetGenericTypeDefinition ();
562 for (int ii = 0; i < InterfaceConstraints.Length; ++ii) {
563 Type check = InterfaceConstraints [ii];
564 if (check.IsGenericType)
565 check = check.GetGenericTypeDefinition ();
567 if (TypeManager.IsEqual (iface, check)) {
580 public void VerifyClsCompliance ()
582 if (class_constraint_type != null && !AttributeTester.IsClsCompliant (class_constraint_type))
583 Warning_ConstrainIsNotClsCompliant (class_constraint_type, class_constraint.Location);
585 if (iface_constraint_types != null) {
586 for (int i = 0; i < iface_constraint_types.Length; ++i) {
587 if (!AttributeTester.IsClsCompliant (iface_constraint_types [i]))
588 Warning_ConstrainIsNotClsCompliant (iface_constraint_types [i],
589 ((TypeExpr)iface_constraints [i]).Location);
594 void Warning_ConstrainIsNotClsCompliant (Type t, Location loc)
596 Report.SymbolRelatedToPreviousError (t);
597 Report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
598 TypeManager.CSharpName (t));
603 /// A type parameter from a generic type definition.
605 public class TypeParameter : MemberCore, IMemberContainer
607 static readonly string[] attribute_target = new string [] { "type parameter" };
611 GenericConstraints gc;
612 Constraints constraints;
614 GenericTypeParameterBuilder type;
615 MemberCache member_cache;
617 public TypeParameter (DeclSpace parent, DeclSpace decl, string name,
618 Constraints constraints, Attributes attrs, Location loc)
619 : base (parent, new MemberName (name, loc), attrs)
623 this.constraints = constraints;
627 public GenericConstraints GenericConstraints {
628 get { return gc != null ? gc : constraints; }
631 public Constraints Constraints {
632 get { return constraints; }
635 public DeclSpace DeclSpace {
644 /// This is the first method which is called during the resolving
645 /// process; we're called immediately after creating the type parameters
646 /// with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
649 /// We're either called from TypeContainer.DefineType() or from
650 /// GenericMethod.Define() (called from Method.Define()).
652 public void Define (GenericTypeParameterBuilder type)
654 if (this.type != null)
655 throw new InvalidOperationException ();
658 TypeManager.AddTypeParameter (type, this);
662 /// This is the second method which is called during the resolving
663 /// process - in case of class type parameters, we're called from
664 /// TypeContainer.ResolveType() - after it resolved the class'es
665 /// base class and interfaces. For method type parameters, we're
666 /// called immediately after Define().
668 /// We're just resolving the constraints into expressions here, we
669 /// don't resolve them into actual types.
671 /// Note that in the special case of partial generic classes, we may be
672 /// called _before_ Define() and we may also be called multiple types.
674 public bool Resolve (DeclSpace ds)
676 if (constraints != null) {
677 if (!constraints.Resolve (ds)) {
687 /// This is the third method which is called during the resolving
688 /// process. We're called immediately after calling DefineConstraints()
689 /// on all of the current class'es type parameters.
691 /// Our job is to resolve the constraints to actual types.
693 /// Note that we may have circular dependencies on type parameters - this
694 /// is why Resolve() and ResolveType() are separate.
696 public bool ResolveType (IResolveContext ec)
698 if (constraints != null) {
699 if (!constraints.ResolveTypes (ec)) {
709 /// This is the fourth and last method which is called during the resolving
710 /// process. We're called after everything is fully resolved and actually
711 /// register the constraints with SRE and the TypeManager.
713 public bool DefineType (IResolveContext ec)
715 return DefineType (ec, null, null, false);
719 /// This is the fith and last method which is called during the resolving
720 /// process. We're called after everything is fully resolved and actually
721 /// register the constraints with SRE and the TypeManager.
723 /// The `builder', `implementing' and `is_override' arguments are only
724 /// applicable to method type parameters.
726 public bool DefineType (IResolveContext ec, MethodBuilder builder,
727 MethodInfo implementing, bool is_override)
729 if (!ResolveType (ec))
732 if (implementing != null) {
733 if (is_override && (constraints != null)) {
734 Report.Error (460, loc,
735 "`{0}': Cannot specify constraints for overrides or explicit interface implementation methods",
736 TypeManager.CSharpSignature (builder));
740 MethodBase mb = TypeManager.DropGenericMethodArguments (implementing);
742 int pos = type.GenericParameterPosition;
743 Type mparam = mb.GetGenericArguments () [pos];
744 GenericConstraints temp_gc = ReflectionConstraints.GetConstraints (mparam);
747 gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
748 else if (constraints != null)
749 gc = new InflatedConstraints (constraints, implementing.DeclaringType);
752 if (constraints != null) {
755 else if (!constraints.CheckInterfaceMethod (gc))
758 if (!is_override && (temp_gc != null))
763 Report.SymbolRelatedToPreviousError (implementing);
766 425, loc, "The constraints for type " +
767 "parameter `{0}' of method `{1}' must match " +
768 "the constraints for type parameter `{2}' " +
769 "of interface method `{3}'. Consider using " +
770 "an explicit interface implementation instead",
771 Name, TypeManager.CSharpSignature (builder),
772 TypeManager.CSharpName (mparam), TypeManager.CSharpSignature (mb));
775 } else if (DeclSpace is CompilerGeneratedClass) {
776 TypeParameter[] tparams = DeclSpace.TypeParameters;
777 Type[] types = new Type [tparams.Length];
778 for (int i = 0; i < tparams.Length; i++)
779 types [i] = tparams [i].Type;
781 if (constraints != null)
782 gc = new InflatedConstraints (constraints, types);
784 gc = (GenericConstraints) constraints;
790 if (gc.HasClassConstraint)
791 type.SetBaseTypeConstraint (gc.ClassConstraint);
793 type.SetInterfaceConstraints (gc.InterfaceConstraints);
794 type.SetGenericParameterAttributes (gc.Attributes);
795 TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
801 /// Check whether there are no conflicts in our type parameter constraints.
803 /// This is an example:
807 /// where U : T, struct
809 public bool CheckDependencies ()
811 if (constraints != null)
812 return constraints.CheckDependencies ();
818 /// This is called for each part of a partial generic type definition.
820 /// If `new_constraints' is not null and we don't already have constraints,
821 /// they become our constraints. If we already have constraints, we must
822 /// check that they're the same.
825 public bool UpdateConstraints (IResolveContext ec, Constraints new_constraints)
828 throw new InvalidOperationException ();
830 if (new_constraints == null)
833 if (!new_constraints.Resolve (ec))
835 if (!new_constraints.ResolveTypes (ec))
838 if (constraints != null)
839 return constraints.CheckInterfaceMethod (new_constraints);
841 constraints = new_constraints;
845 public override void Emit ()
847 if (OptAttributes != null)
848 OptAttributes.Emit ();
853 public override string DocCommentHeader {
855 throw new InvalidOperationException (
856 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
864 public override bool Define ()
869 public override void ApplyAttributeBuilder (Attribute a,
870 CustomAttributeBuilder cb)
872 type.SetCustomAttribute (cb);
875 public override AttributeTargets AttributeTargets {
877 return AttributeTargets.GenericParameter;
881 public override string[] ValidAttributeTargets {
883 return attribute_target;
891 string IMemberContainer.Name {
895 MemberCache IMemberContainer.BaseCache {
900 if (gc.EffectiveBaseClass.BaseType == null)
903 return TypeManager.LookupMemberCache (gc.EffectiveBaseClass.BaseType);
907 bool IMemberContainer.IsInterface {
908 get { return false; }
911 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
913 throw new NotSupportedException ();
916 public MemberCache MemberCache {
918 if (member_cache != null)
924 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
925 member_cache = new MemberCache (this, gc.EffectiveBaseClass, ifaces);
931 public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
932 MemberFilter filter, object criteria)
935 return MemberList.Empty;
937 ArrayList members = new ArrayList ();
939 if (gc.HasClassConstraint) {
940 MemberList list = TypeManager.FindMembers (
941 gc.ClassConstraint, mt, bf, filter, criteria);
943 members.AddRange (list);
946 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
947 foreach (Type t in ifaces) {
948 MemberList list = TypeManager.FindMembers (
949 t, mt, bf, filter, criteria);
951 members.AddRange (list);
954 return new MemberList (members);
957 public bool IsSubclassOf (Type t)
962 if (constraints != null)
963 return constraints.IsSubclassOf (t);
968 public override string ToString ()
970 return "TypeParameter[" + name + "]";
973 public static string GetSignatureForError (TypeParameter[] tp)
975 if (tp == null || tp.Length == 0)
978 StringBuilder sb = new StringBuilder ("<");
979 for (int i = 0; i < tp.Length; ++i) {
982 sb.Append (tp[i].GetSignatureForError ());
985 return sb.ToString ();
988 public void InflateConstraints (Type declaring)
990 if (constraints != null)
991 gc = new InflatedConstraints (constraints, declaring);
994 public override bool IsClsComplianceRequired ()
999 protected class InflatedConstraints : GenericConstraints
1001 GenericConstraints gc;
1003 Type class_constraint;
1004 Type[] iface_constraints;
1007 public InflatedConstraints (GenericConstraints gc, Type declaring)
1008 : this (gc, TypeManager.GetTypeArguments (declaring))
1011 public InflatedConstraints (GenericConstraints gc, Type[] dargs)
1016 ArrayList list = new ArrayList ();
1017 if (gc.HasClassConstraint)
1018 list.Add (inflate (gc.ClassConstraint));
1019 foreach (Type iface in gc.InterfaceConstraints)
1020 list.Add (inflate (iface));
1022 bool has_class_constr = false;
1023 if (list.Count > 0) {
1024 Type first = (Type) list [0];
1025 has_class_constr = !first.IsGenericParameter && !first.IsInterface;
1028 if ((list.Count > 0) && has_class_constr) {
1029 class_constraint = (Type) list [0];
1030 iface_constraints = new Type [list.Count - 1];
1031 list.CopyTo (1, iface_constraints, 0, list.Count - 1);
1033 iface_constraints = new Type [list.Count];
1034 list.CopyTo (iface_constraints, 0);
1037 if (HasValueTypeConstraint)
1038 base_type = TypeManager.value_type;
1039 else if (class_constraint != null)
1040 base_type = class_constraint;
1042 base_type = TypeManager.object_type;
1045 Type inflate (Type t)
1049 if (t.IsGenericParameter)
1050 return dargs [t.GenericParameterPosition];
1051 if (t.IsGenericType) {
1052 Type[] args = t.GetGenericArguments ();
1053 Type[] inflated = new Type [args.Length];
1055 for (int i = 0; i < args.Length; i++)
1056 inflated [i] = inflate (args [i]);
1058 t = t.GetGenericTypeDefinition ();
1059 t = t.MakeGenericType (inflated);
1065 public override string TypeParameter {
1066 get { return gc.TypeParameter; }
1069 public override GenericParameterAttributes Attributes {
1070 get { return gc.Attributes; }
1073 public override Type ClassConstraint {
1074 get { return class_constraint; }
1077 public override Type EffectiveBaseClass {
1078 get { return base_type; }
1081 public override Type[] InterfaceConstraints {
1082 get { return iface_constraints; }
1088 /// A TypeExpr which already resolved to a type parameter.
1090 public class TypeParameterExpr : TypeExpr {
1091 TypeParameter type_parameter;
1093 public override string Name {
1095 return type_parameter.Name;
1099 public override string FullName {
1101 return type_parameter.Name;
1105 public TypeParameter TypeParameter {
1107 return type_parameter;
1111 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1113 this.type_parameter = type_parameter;
1117 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1119 type = type_parameter.Type;
1124 public override bool IsInterface {
1125 get { return false; }
1128 public override bool CheckAccessLevel (DeclSpace ds)
1133 public void Error_CannotUseAsUnmanagedType (Location loc)
1135 Report.Error (-203, loc, "Can not use type parameter as unmanaged type");
1140 /// Tracks the type arguments when instantiating a generic type. We're used in
1141 /// ConstructedType.
1143 public class TypeArguments {
1144 public readonly Location Location;
1151 public TypeArguments (Location loc)
1153 args = new ArrayList ();
1154 this.Location = loc;
1157 public TypeArguments (Location loc, params Expression[] types)
1159 this.Location = loc;
1160 this.args = new ArrayList (types);
1163 public TypeArguments (int dimension, Location loc)
1165 this.dimension = dimension;
1166 this.Location = loc;
1169 public void Add (Expression type)
1172 throw new InvalidOperationException ();
1177 public void Add (TypeArguments new_args)
1180 throw new InvalidOperationException ();
1182 args.AddRange (new_args.args);
1186 /// We're used during the parsing process: the parser can't distinguish
1187 /// between type parameters and type arguments. Because of that, the
1188 /// parser creates a `MemberName' with `TypeArguments' for both cases and
1189 /// in case of a generic type definition, we call GetDeclarations().
1191 public TypeParameterName[] GetDeclarations ()
1193 TypeParameterName[] ret = new TypeParameterName [args.Count];
1194 for (int i = 0; i < args.Count; i++) {
1195 TypeParameterName name = args [i] as TypeParameterName;
1200 SimpleName sn = args [i] as SimpleName;
1202 ret [i] = new TypeParameterName (sn.Name, null, sn.Location);
1206 Report.Error (81, Location, "Type parameter declaration " +
1207 "must be an identifier not a type");
1214 /// We may only be used after Resolve() is called and return the fully
1217 public Type[] Arguments {
1223 public bool HasTypeArguments {
1225 return has_type_args;
1238 public bool IsUnbound {
1240 return dimension > 0;
1244 public override string ToString ()
1246 StringBuilder s = new StringBuilder ();
1249 for (int i = 0; i < count; i++){
1251 // FIXME: Use TypeManager.CSharpname once we have the type
1254 s.Append (args [i].ToString ());
1258 return s.ToString ();
1261 public string GetSignatureForError()
1263 StringBuilder sb = new StringBuilder();
1264 for (int i = 0; i < Count; ++i)
1266 Expression expr = (Expression)args [i];
1267 sb.Append(expr.GetSignatureForError());
1271 return sb.ToString();
1275 /// Resolve the type arguments.
1277 public bool Resolve (IResolveContext ec)
1279 int count = args.Count;
1282 atypes = new Type [count];
1284 for (int i = 0; i < count; i++){
1285 TypeExpr te = ((Expression) args [i]).ResolveAsTypeTerminal (ec, false);
1291 atypes[i] = te.Type;
1292 if (te.Type.IsGenericParameter) {
1293 if (te is TypeParameterExpr)
1294 has_type_args = true;
1298 if (te.Type.IsSealed && te.Type.IsAbstract) {
1299 Report.Error (718, Location, "`{0}': static classes cannot be used as generic arguments",
1300 te.GetSignatureForError ());
1304 if (te.Type.IsPointer) {
1305 Report.Error (306, Location, "The type `{0}' may not be used " +
1306 "as a type argument", TypeManager.CSharpName (te.Type));
1310 if (te.Type == TypeManager.void_type) {
1311 Expression.Error_VoidInvalidInTheContext (Location);
1318 public TypeArguments Clone ()
1320 TypeArguments copy = new TypeArguments (Location);
1321 foreach (Expression ta in args)
1328 public class TypeParameterName : SimpleName
1330 Attributes attributes;
1332 public TypeParameterName (string name, Attributes attrs, Location loc)
1338 public Attributes OptAttributes {
1346 /// An instantiation of a generic type.
1348 public class ConstructedType : TypeExpr {
1350 FullNamedExpression name;
1352 Type[] gen_params, atypes;
1356 /// Instantiate the generic type `fname' with the type arguments `args'.
1358 public ConstructedType (FullNamedExpression fname, TypeArguments args, Location l)
1364 eclass = ExprClass.Type;
1365 full_name = name + "<" + args.ToString () + ">";
1368 protected ConstructedType (TypeArguments args, Location l)
1373 eclass = ExprClass.Type;
1376 protected ConstructedType (TypeParameter[] type_params, Location l)
1380 args = new TypeArguments (l);
1381 foreach (TypeParameter type_param in type_params)
1382 args.Add (new TypeParameterExpr (type_param, l));
1384 eclass = ExprClass.Type;
1388 /// This is used to construct the `this' type inside a generic type definition.
1390 public ConstructedType (Type t, TypeParameter[] type_params, Location l)
1391 : this (type_params, l)
1393 gt = t.GetGenericTypeDefinition ();
1395 this.name = new TypeExpression (gt, l);
1396 full_name = gt.FullName + "<" + args.ToString () + ">";
1400 /// Instantiate the generic type `t' with the type arguments `args'.
1401 /// Use this constructor if you already know the fully resolved
1404 public ConstructedType (Type t, TypeArguments args, Location l)
1407 gt = t.GetGenericTypeDefinition ();
1409 this.name = new TypeExpression (gt, l);
1410 full_name = gt.FullName + "<" + args.ToString () + ">";
1413 public TypeArguments TypeArguments {
1414 get { return args; }
1417 public override string GetSignatureForError ()
1419 return TypeManager.RemoveGenericArity (gt.FullName) + "<" + args.GetSignatureForError () + ">";
1422 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1424 if (!ResolveConstructedType (ec))
1431 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1432 /// after fully resolving the constructed type.
1434 public bool CheckConstraints (IResolveContext ec)
1436 return ConstraintChecker.CheckConstraints (ec, gt, gen_params, atypes, loc);
1440 /// Resolve the constructed type, but don't check the constraints.
1442 public bool ResolveConstructedType (IResolveContext ec)
1446 // If we already know the fully resolved generic type.
1448 return DoResolveType (ec);
1454 Report.Error (246, loc, "Cannot find type `{0}'<...>", Name);
1458 num_args = TypeManager.GetNumberOfTypeArguments (t);
1459 if (num_args == 0) {
1460 Report.Error (308, loc,
1461 "The non-generic type `{0}' cannot " +
1462 "be used with type arguments.",
1463 TypeManager.CSharpName (t));
1467 gt = t.GetGenericTypeDefinition ();
1468 return DoResolveType (ec);
1471 bool DoResolveType (IResolveContext ec)
1474 // Resolve the arguments.
1476 if (args.Resolve (ec) == false)
1479 gen_params = gt.GetGenericArguments ();
1480 atypes = args.Arguments;
1482 if (atypes.Length != gen_params.Length) {
1483 Report.Error (305, loc,
1484 "Using the generic type `{0}' " +
1485 "requires {1} type arguments",
1486 TypeManager.CSharpName (gt),
1487 gen_params.Length.ToString ());
1492 // Now bind the parameters.
1494 type = gt.MakeGenericType (atypes);
1498 public Expression GetSimpleName (EmitContext ec)
1503 public override bool CheckAccessLevel (DeclSpace ds)
1505 return ds.CheckAccessLevel (gt);
1508 public override bool AsAccessible (DeclSpace ds)
1510 foreach (Type t in atypes) {
1511 if (!ds.IsAccessibleAs (t))
1515 return ds.IsAccessibleAs (gt);
1518 public override bool IsClass {
1519 get { return gt.IsClass; }
1522 public override bool IsValueType {
1523 get { return gt.IsValueType; }
1526 public override bool IsInterface {
1527 get { return gt.IsInterface; }
1530 public override bool IsSealed {
1531 get { return gt.IsSealed; }
1534 public override bool Equals (object obj)
1536 ConstructedType cobj = obj as ConstructedType;
1540 if ((type == null) || (cobj.type == null))
1543 return type == cobj.type;
1546 public override int GetHashCode ()
1548 return base.GetHashCode ();
1551 public override string Name {
1557 public override string FullName {
1564 public abstract class ConstraintChecker
1566 protected readonly Type[] gen_params;
1567 protected readonly Type[] atypes;
1568 protected readonly Location loc;
1570 protected ConstraintChecker (Type[] gen_params, Type[] atypes, Location loc)
1572 this.gen_params = gen_params;
1573 this.atypes = atypes;
1578 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1579 /// after fully resolving the constructed type.
1581 public bool CheckConstraints (IResolveContext ec)
1583 for (int i = 0; i < gen_params.Length; i++) {
1584 if (!CheckConstraints (ec, i))
1591 protected bool CheckConstraints (IResolveContext ec, int index)
1593 Type atype = atypes [index];
1594 Type ptype = gen_params [index];
1599 Expression aexpr = new EmptyExpression (atype);
1601 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1605 bool is_class, is_struct;
1606 if (atype.IsGenericParameter) {
1607 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1609 if (agc is Constraints)
1610 ((Constraints) agc).Resolve (ec);
1611 is_class = agc.IsReferenceType;
1612 is_struct = agc.IsValueType;
1614 is_class = is_struct = false;
1619 if (!atype.IsGenericType)
1621 is_class = atype.IsClass || atype.IsInterface;
1622 is_struct = atype.IsValueType && !TypeManager.IsNullableType (atype);
1626 // First, check the `class' and `struct' constraints.
1628 if (gc.HasReferenceTypeConstraint && !is_class) {
1629 Report.Error (452, loc, "The type `{0}' must be " +
1630 "a reference type in order to use it " +
1631 "as type parameter `{1}' in the " +
1632 "generic type or method `{2}'.",
1633 TypeManager.CSharpName (atype),
1634 TypeManager.CSharpName (ptype),
1635 GetSignatureForError ());
1637 } else if (gc.HasValueTypeConstraint && !is_struct) {
1638 Report.Error (453, loc, "The type `{0}' must be a " +
1639 "non-nullable value type in order to use it " +
1640 "as type parameter `{1}' in the " +
1641 "generic type or method `{2}'.",
1642 TypeManager.CSharpName (atype),
1643 TypeManager.CSharpName (ptype),
1644 GetSignatureForError ());
1649 // The class constraint comes next.
1651 if (gc.HasClassConstraint) {
1652 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint))
1657 // Now, check the interface constraints.
1659 if (gc.InterfaceConstraints != null) {
1660 foreach (Type it in gc.InterfaceConstraints) {
1661 if (!CheckConstraint (ec, ptype, aexpr, it))
1667 // Finally, check the constructor constraint.
1670 if (!gc.HasConstructorConstraint)
1673 if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
1676 if (HasDefaultConstructor (atype))
1679 Report_SymbolRelatedToPreviousError ();
1680 Report.SymbolRelatedToPreviousError (atype);
1681 Report.Error (310, loc, "The type `{0}' must have a public " +
1682 "parameterless constructor in order to use it " +
1683 "as parameter `{1}' in the generic type or " +
1685 TypeManager.CSharpName (atype),
1686 TypeManager.CSharpName (ptype),
1687 GetSignatureForError ());
1691 protected bool CheckConstraint (IResolveContext ec, Type ptype, Expression expr,
1694 if (TypeManager.HasGenericArguments (ctype)) {
1695 Type[] types = TypeManager.GetTypeArguments (ctype);
1697 TypeArguments new_args = new TypeArguments (loc);
1699 for (int i = 0; i < types.Length; i++) {
1702 if (t.IsGenericParameter) {
1703 int pos = t.GenericParameterPosition;
1706 new_args.Add (new TypeExpression (t, loc));
1709 TypeExpr ct = new ConstructedType (ctype, new_args, loc);
1710 if (ct.ResolveAsTypeStep (ec, false) == null)
1713 } else if (ctype.IsGenericParameter) {
1714 int pos = ctype.GenericParameterPosition;
1715 ctype = atypes [pos];
1718 if (Convert.ImplicitStandardConversionExists (expr, ctype))
1721 Error_TypeMustBeConvertible (expr.Type, ctype, ptype);
1725 bool HasDefaultConstructor (Type atype)
1727 if (atype.IsAbstract)
1731 atype = TypeManager.DropGenericTypeArguments (atype);
1732 if (atype is TypeBuilder) {
1733 TypeContainer tc = TypeManager.LookupTypeContainer (atype);
1734 if (tc.InstanceConstructors == null) {
1735 atype = atype.BaseType;
1739 foreach (Constructor c in tc.InstanceConstructors) {
1740 if ((c.ModFlags & Modifiers.PUBLIC) == 0)
1742 if ((c.Parameters.FixedParameters != null) &&
1743 (c.Parameters.FixedParameters.Length != 0))
1745 if (c.Parameters.HasArglist || c.Parameters.HasParams)
1752 TypeParameter tparam = TypeManager.LookupTypeParameter (atype);
1753 if (tparam != null) {
1754 if (tparam.GenericConstraints == null)
1757 return tparam.GenericConstraints.HasConstructorConstraint ||
1758 tparam.GenericConstraints.HasValueTypeConstraint;
1761 MemberInfo [] list = TypeManager.MemberLookup (null, null, atype, MemberTypes.Constructor,
1762 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
1763 ConstructorInfo.ConstructorName, null);
1768 foreach (MethodBase mb in list) {
1769 ParameterData pd = TypeManager.GetParameterData (mb);
1777 protected abstract string GetSignatureForError ();
1778 protected abstract void Report_SymbolRelatedToPreviousError ();
1780 void Error_TypeMustBeConvertible (Type atype, Type gc, Type ptype)
1782 Report_SymbolRelatedToPreviousError ();
1783 Report.SymbolRelatedToPreviousError (atype);
1784 Report.Error (309, loc,
1785 "The type `{0}' must be convertible to `{1}' in order to " +
1786 "use it as parameter `{2}' in the generic type or method `{3}'",
1787 TypeManager.CSharpName (atype), TypeManager.CSharpName (gc),
1788 TypeManager.CSharpName (ptype), GetSignatureForError ());
1791 public static bool CheckConstraints (EmitContext ec, MethodBase definition,
1792 MethodBase instantiated, Location loc)
1794 MethodConstraintChecker checker = new MethodConstraintChecker (
1795 definition, definition.GetGenericArguments (),
1796 instantiated.GetGenericArguments (), loc);
1798 return checker.CheckConstraints (ec);
1801 public static bool CheckConstraints (IResolveContext ec, Type gt, Type[] gen_params,
1802 Type[] atypes, Location loc)
1804 TypeConstraintChecker checker = new TypeConstraintChecker (
1805 gt, gen_params, atypes, loc);
1807 return checker.CheckConstraints (ec);
1810 protected class MethodConstraintChecker : ConstraintChecker
1812 MethodBase definition;
1814 public MethodConstraintChecker (MethodBase definition, Type[] gen_params,
1815 Type[] atypes, Location loc)
1816 : base (gen_params, atypes, loc)
1818 this.definition = definition;
1821 protected override string GetSignatureForError ()
1823 return TypeManager.CSharpSignature (definition);
1826 protected override void Report_SymbolRelatedToPreviousError ()
1828 Report.SymbolRelatedToPreviousError (definition);
1832 protected class TypeConstraintChecker : ConstraintChecker
1836 public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
1838 : base (gen_params, atypes, loc)
1843 protected override string GetSignatureForError ()
1845 return TypeManager.CSharpName (gt);
1848 protected override void Report_SymbolRelatedToPreviousError ()
1850 Report.SymbolRelatedToPreviousError (gt);
1856 /// A generic method definition.
1858 public class GenericMethod : DeclSpace
1860 Expression return_type;
1861 Parameters parameters;
1863 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
1864 Expression return_type, Parameters parameters)
1865 : base (ns, parent, name, null)
1867 this.return_type = return_type;
1868 this.parameters = parameters;
1871 public override TypeBuilder DefineType ()
1873 throw new Exception ();
1876 public override bool Define ()
1878 for (int i = 0; i < TypeParameters.Length; i++)
1879 if (!TypeParameters [i].Resolve (this))
1886 /// Define and resolve the type parameters.
1887 /// We're called from Method.Define().
1889 public bool Define (MethodBuilder mb, ToplevelBlock block)
1891 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1892 string[] snames = new string [names.Length];
1893 for (int i = 0; i < names.Length; i++) {
1894 string type_argument_name = names[i].Name;
1895 Parameter p = parameters.GetParameterByName (type_argument_name);
1897 Error_ParameterNameCollision (p.Location, type_argument_name, "method parameter");
1901 snames[i] = type_argument_name;
1904 GenericTypeParameterBuilder[] gen_params = mb.DefineGenericParameters (snames);
1905 for (int i = 0; i < TypeParameters.Length; i++)
1906 TypeParameters [i].Define (gen_params [i]);
1911 for (int i = 0; i < TypeParameters.Length; i++) {
1912 if (!TypeParameters [i].ResolveType (this))
1919 internal static void Error_ParameterNameCollision (Location loc, string name, string collisionWith)
1921 Report.Error (412, loc, "The type parameter name `{0}' is the same as `{1}'",
1922 name, collisionWith);
1926 /// We're called from MethodData.Define() after creating the MethodBuilder.
1928 public bool DefineType (EmitContext ec, MethodBuilder mb,
1929 MethodInfo implementing, bool is_override)
1931 for (int i = 0; i < TypeParameters.Length; i++)
1932 if (!TypeParameters [i].DefineType (
1933 ec, mb, implementing, is_override))
1937 foreach (Parameter p in parameters.FixedParameters){
1938 if (!p.Resolve (ec))
1941 if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec, false) == null))
1947 public void EmitAttributes ()
1949 for (int i = 0; i < TypeParameters.Length; i++)
1950 TypeParameters [i].Emit ();
1952 if (OptAttributes != null)
1953 OptAttributes.Emit ();
1956 public override bool DefineMembers ()
1961 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1962 MemberFilter filter, object criteria)
1964 throw new Exception ();
1967 public override MemberCache MemberCache {
1973 public override AttributeTargets AttributeTargets {
1975 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1979 public override string DocCommentHeader {
1980 get { return "M:"; }
1983 public new void VerifyClsCompliance ()
1985 foreach (TypeParameter tp in TypeParameters) {
1986 if (tp.Constraints == null)
1989 tp.Constraints.VerifyClsCompliance ();
1994 public class NullableType : TypeExpr
1996 Expression underlying;
1998 public NullableType (Expression underlying, Location l)
2000 this.underlying = underlying;
2003 eclass = ExprClass.Type;
2006 public NullableType (Type type, Location loc)
2007 : this (new TypeExpression (type, loc), loc)
2010 public override string Name {
2011 get { return underlying.ToString () + "?"; }
2014 public override string FullName {
2015 get { return underlying.ToString () + "?"; }
2018 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
2020 TypeArguments args = new TypeArguments (loc);
2021 args.Add (underlying);
2023 ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
2024 return ctype.ResolveAsTypeTerminal (ec, false);
2028 public partial class TypeManager
2031 // A list of core types that the compiler requires or uses
2033 static public Type activator_type;
2034 static public Type generic_ilist_type;
2035 static public Type generic_icollection_type;
2036 static public Type generic_ienumerator_type;
2037 static public Type generic_ienumerable_type;
2038 static public Type generic_nullable_type;
2041 // These methods are called by code generated by the compiler
2043 static public MethodInfo activator_create_instance;
2045 static void InitGenericCoreTypes ()
2047 activator_type = CoreLookupType ("System", "Activator");
2049 generic_ilist_type = CoreLookupType (
2050 "System.Collections.Generic", "IList", 1);
2051 generic_icollection_type = CoreLookupType (
2052 "System.Collections.Generic", "ICollection", 1);
2053 generic_ienumerator_type = CoreLookupType (
2054 "System.Collections.Generic", "IEnumerator", 1);
2055 generic_ienumerable_type = CoreLookupType (
2056 "System.Collections.Generic", "IEnumerable", 1);
2057 generic_nullable_type = CoreLookupType (
2058 "System", "Nullable", 1);
2061 static void InitGenericCodeHelpers ()
2064 activator_create_instance = GetCoreMethod (
2065 activator_type, "CreateInstance", Type.EmptyTypes);
2068 static Type CoreLookupType (string ns, string name, int arity)
2070 return CoreLookupType (ns, MemberName.MakeName (name, arity));
2073 public static TypeContainer LookupGenericTypeContainer (Type t)
2075 t = DropGenericTypeArguments (t);
2076 return LookupTypeContainer (t);
2080 /// Check whether `a' and `b' may become equal generic types.
2081 /// The algorithm to do that is a little bit complicated.
2083 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_inferred,
2084 Type[] method_inferred)
2086 if (a.IsGenericParameter) {
2088 // If a is an array of a's type, they may never
2092 b = b.GetElementType ();
2098 // If b is a generic parameter or an actual type,
2099 // they may become equal:
2101 // class X<T,U> : I<T>, I<U>
2102 // class X<T> : I<T>, I<float>
2104 if (b.IsGenericParameter || !b.IsGenericType) {
2105 int pos = a.GenericParameterPosition;
2106 Type[] args = a.DeclaringMethod != null ? method_inferred : class_inferred;
2107 if (args [pos] == null) {
2112 return args [pos] == a;
2116 // We're now comparing a type parameter with a
2117 // generic instance. They may become equal unless
2118 // the type parameter appears anywhere in the
2119 // generic instance:
2121 // class X<T,U> : I<T>, I<X<U>>
2122 // -> error because you could instanciate it as
2125 // class X<T> : I<T>, I<X<T>> -> ok
2128 Type[] bargs = GetTypeArguments (b);
2129 for (int i = 0; i < bargs.Length; i++) {
2130 if (a.Equals (bargs [i]))
2137 if (b.IsGenericParameter)
2138 return MayBecomeEqualGenericTypes (b, a, class_inferred, method_inferred);
2141 // At this point, neither a nor b are a type parameter.
2143 // If one of them is a generic instance, let
2144 // MayBecomeEqualGenericInstances() compare them (if the
2145 // other one is not a generic instance, they can never
2149 if (a.IsGenericType || b.IsGenericType)
2150 return MayBecomeEqualGenericInstances (a, b, class_inferred, method_inferred);
2153 // If both of them are arrays.
2156 if (a.IsArray && b.IsArray) {
2157 if (a.GetArrayRank () != b.GetArrayRank ())
2160 a = a.GetElementType ();
2161 b = b.GetElementType ();
2163 return MayBecomeEqualGenericTypes (a, b, class_inferred, method_inferred);
2167 // Ok, two ordinary types.
2170 return a.Equals (b);
2174 // Checks whether two generic instances may become equal for some
2175 // particular instantiation (26.3.1).
2177 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
2178 Type[] class_inferred,
2179 Type[] method_inferred)
2181 if (!a.IsGenericType || !b.IsGenericType)
2183 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2186 return MayBecomeEqualGenericInstances (
2187 GetTypeArguments (a), GetTypeArguments (b), class_inferred, method_inferred);
2190 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
2191 Type[] class_inferred,
2192 Type[] method_inferred)
2194 if (aargs.Length != bargs.Length)
2197 for (int i = 0; i < aargs.Length; i++) {
2198 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_inferred, method_inferred))
2206 /// Type inference. Try to infer the type arguments from `method',
2207 /// which is invoked with the arguments `arguments'. This is used
2208 /// when resolving an Invocation or a DelegateInvocation and the user
2209 /// did not explicitly specify type arguments.
2211 public static int InferTypeArguments (EmitContext ec,
2212 ArrayList arguments,
2213 ref MethodBase method)
2215 ATypeInference ti = ATypeInference.CreateInstance (arguments);
2216 Type[] i_args = ti.InferMethodArguments (ec, method);
2218 return ti.InferenceScore;
2220 if (i_args.Length == 0)
2223 method = ((MethodInfo) method).MakeGenericMethod (i_args);
2230 public static bool InferTypeArguments (ParameterData apd,
2231 ref MethodBase method)
2233 if (!TypeManager.IsGenericMethod (method))
2236 ATypeInference ti = ATypeInference.CreateInstance (ArrayList.Adapter (apd.Types));
2237 Type[] i_args = ti.InferDelegateArguments (method);
2241 method = ((MethodInfo) method).MakeGenericMethod (i_args);
2246 abstract class ATypeInference
2248 protected readonly ArrayList arguments;
2249 protected readonly int arg_count;
2251 protected ATypeInference (ArrayList arguments)
2253 this.arguments = arguments;
2254 if (arguments != null)
2255 arg_count = arguments.Count;
2258 public static ATypeInference CreateInstance (ArrayList arguments)
2260 if (RootContext.Version == LanguageVersion.ISO_2)
2261 return new TypeInferenceV2 (arguments);
2263 return new TypeInferenceV3 (arguments);
2266 public virtual int InferenceScore {
2268 return int.MaxValue;
2272 public abstract Type[] InferMethodArguments (EmitContext ec, MethodBase method);
2273 public abstract Type[] InferDelegateArguments (MethodBase method);
2277 // Implements C# 2.0 type inference
2279 class TypeInferenceV2 : ATypeInference
2281 public TypeInferenceV2 (ArrayList arguments)
2286 public override Type[] InferDelegateArguments (MethodBase method)
2288 ParameterData pd = TypeManager.GetParameterData (method);
2289 if (arg_count != pd.Count)
2292 Type[] method_args = method.GetGenericArguments ();
2293 Type[] inferred_types = new Type[method_args.Length];
2295 Type[] param_types = new Type[pd.Count];
2296 Type[] arg_types = (Type[])arguments.ToArray (typeof (Type));
2298 for (int i = 0; i < arg_count; i++) {
2299 param_types[i] = pd.ParameterType (i);
2302 if (!InferTypeArguments (param_types, arg_types, inferred_types))
2305 return inferred_types;
2308 public override Type[] InferMethodArguments (EmitContext ec, MethodBase method)
2310 ParameterData pd = TypeManager.GetParameterData (method);
2311 Type[] method_generic_args = method.GetGenericArguments ();
2312 Type [] inferred_types = new Type [method_generic_args.Length];
2313 Type[] arg_types = new Type [pd.Count];
2315 int a_count = arg_types.Length;
2319 for (int i = 0; i < a_count; i++) {
2320 Argument a = (Argument) arguments[i];
2321 if (a.Expr is NullLiteral || a.Expr is MethodGroupExpr || a.Expr is AnonymousMethodExpression)
2324 if (!TypeInferenceV2.UnifyType (pd.ParameterType (i), a.Type, inferred_types))
2329 Type element_type = TypeManager.GetElementType (pd.ParameterType (a_count));
2330 for (int i = a_count; i < arg_count; i++) {
2331 Argument a = (Argument) arguments [i];
2332 if (a.Expr is NullLiteral || a.Expr is MethodGroupExpr || a.Expr is AnonymousMethodExpression)
2335 if (!TypeInferenceV2.UnifyType (element_type, a.Type, inferred_types))
2340 for (int i = 0; i < inferred_types.Length; i++)
2341 if (inferred_types [i] == null)
2344 return inferred_types;
2347 static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
2348 Type[] inferred_types)
2350 for (int i = 0; i < arg_types.Length; i++) {
2351 if (arg_types[i] == null)
2354 if (!UnifyType (param_types[i], arg_types[i], inferred_types))
2358 for (int i = 0; i < inferred_types.Length; ++i)
2359 if (inferred_types[i] == null)
2365 public static bool UnifyType (Type pt, Type at, Type[] inferred)
2367 if (pt.IsGenericParameter) {
2368 if (pt.DeclaringMethod == null)
2371 int pos = pt.GenericParameterPosition;
2373 if (inferred [pos] == null)
2374 inferred [pos] = at;
2376 return inferred [pos] == at;
2379 if (!pt.ContainsGenericParameters) {
2380 if (at.ContainsGenericParameters)
2381 return UnifyType (at, pt, inferred);
2388 if (at.GetArrayRank () != pt.GetArrayRank ())
2391 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2394 if (!pt.IsGenericType)
2397 Type gt = pt.GetGenericTypeDefinition ();
2398 if ((gt != TypeManager.generic_ilist_type) && (gt != TypeManager.generic_icollection_type) &&
2399 (gt != TypeManager.generic_ienumerable_type))
2402 Type[] args = TypeManager.GetTypeArguments (pt);
2403 return UnifyType (args[0], at.GetElementType (), inferred);
2408 (pt.GetArrayRank () != at.GetArrayRank ()))
2411 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2414 if (pt.IsByRef && at.IsByRef)
2415 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2416 ArrayList list = new ArrayList ();
2417 if (at.IsGenericType)
2419 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
2422 list.AddRange (TypeManager.GetInterfaces (at));
2424 foreach (Type type in list) {
2425 if (!type.IsGenericType)
2428 if (TypeManager.DropGenericTypeArguments (pt) != TypeManager.DropGenericTypeArguments (type))
2431 if (!UnifyTypes (pt.GetGenericArguments (), type.GetGenericArguments (), inferred))
2438 static bool UnifyTypes (Type[] pts, Type[] ats, Type[] inferred)
2440 for (int i = 0; i < ats.Length; i++) {
2441 if (!UnifyType (pts [i], ats [i], inferred))
2449 // Implements C# 3.0 type inference
2451 class TypeInferenceV3 : ATypeInference
2454 // Tracks successful rate of type inference
2456 int score = int.MaxValue;
2458 public TypeInferenceV3 (ArrayList arguments)
2463 public override int InferenceScore {
2469 public override Type[] InferDelegateArguments (MethodBase method)
2471 ParameterData pd = TypeManager.GetParameterData (method);
2472 if (arg_count != pd.Count)
2475 Type[] d_gargs = method.GetGenericArguments ();
2476 TypeInferenceContext context = new TypeInferenceContext (d_gargs);
2478 // A lower-bound inference is made from each argument type Uj of D
2479 // to the corresponding parameter type Tj of M
2480 for (int i = 0; i < arg_count; ++i) {
2481 Type t = pd.Types [i];
2482 if (!t.IsGenericParameter)
2485 context.LowerBoundInference ((Type)arguments[i], t);
2488 if (!context.FixAllTypes ())
2491 return context.InferredTypeArguments;
2494 public override Type[] InferMethodArguments (EmitContext ec, MethodBase method)
2496 Type[] method_generic_args = method.GetGenericArguments ();
2497 TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2498 if (!context.UnfixedVariableExists)
2499 return Type.EmptyTypes;
2501 ParameterData pd = TypeManager.GetParameterData (method);
2502 if (!InferInPhases (ec, context, pd))
2505 return context.InferredTypeArguments;
2509 // Implements method type arguments inference
2511 bool InferInPhases (EmitContext ec, TypeInferenceContext tic, ParameterData methodParameters)
2513 int params_arguments_start;
2514 if (methodParameters.HasParams) {
2515 params_arguments_start = methodParameters.Count - 1;
2517 params_arguments_start = arg_count;
2521 // The first inference phase
2523 Type method_parameter = null;
2524 for (int i = 0; i < arg_count; i++) {
2525 Argument a = (Argument) arguments [i];
2527 if (i < params_arguments_start) {
2528 method_parameter = methodParameters.Types [i];
2529 } else if (i == params_arguments_start) {
2530 if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2531 method_parameter = methodParameters.Types [params_arguments_start];
2533 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2537 // When a lambda expression, an anonymous method
2538 // is used an explicit argument type inference takes a place
2540 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2542 if (am.ExplicitTypeInference (tic, method_parameter))
2547 if (a.Expr.Type == TypeManager.null_type)
2551 // Otherwise an output type inference is made
2553 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2557 // Part of the second phase but because it happens only once
2558 // we don't need to call it in cycle
2560 bool fixed_any = false;
2561 if (!tic.FixIndependentTypeArguments (methodParameters, ref fixed_any))
2564 return DoSecondPhase (ec, tic, methodParameters, !fixed_any);
2567 bool DoSecondPhase (EmitContext ec, TypeInferenceContext tic, ParameterData methodParameters, bool fixDependent)
2569 bool fixed_any = false;
2570 if (fixDependent && !tic.FixDependentTypes (methodParameters, ref fixed_any))
2573 // If no further unfixed type variables exist, type inference succeeds
2574 if (!tic.UnfixedVariableExists)
2577 if (!fixed_any && fixDependent)
2580 // For all arguments where the corresponding argument output types
2581 // contain unfixed type variables but the input types do not,
2582 // an output type inference is made
2583 for (int i = 0; i < arg_count; i++) {
2584 Type t_i = methodParameters.ParameterType (i);
2585 if (!TypeManager.IsDelegateType (t_i)) {
2586 if (TypeManager.DropGenericTypeArguments (t_i) != TypeManager.expression_type)
2589 t_i = t_i.GetGenericArguments () [0];
2592 MethodInfo mi = Delegate.GetInvokeMethod (t_i, t_i);
2593 Type rtype = mi.ReturnType;
2596 // Blablabla, because reflection does not work with dynamic types
2597 Type[] g_args = t_i.GetGenericArguments ();
2598 rtype = g_args[rtype.GenericParameterPosition];
2601 if (tic.IsReturnTypeNonDependent (mi, rtype))
2602 score -= tic.OutputTypeInference (ec, ((Argument) arguments [i]).Expr, t_i);
2606 return DoSecondPhase (ec, tic, methodParameters, true);
2610 public class TypeInferenceContext
2612 readonly Type[] unfixed_types;
2613 readonly Type[] fixed_types;
2614 readonly ArrayList[] bounds;
2616 public TypeInferenceContext (Type[] typeArguments)
2618 if (typeArguments.Length == 0)
2619 throw new ArgumentException ("Empty generic arguments");
2621 fixed_types = new Type [typeArguments.Length];
2622 for (int i = 0; i < typeArguments.Length; ++i) {
2623 if (typeArguments [i].IsGenericParameter) {
2624 if (bounds == null) {
2625 bounds = new ArrayList [typeArguments.Length];
2626 unfixed_types = new Type [typeArguments.Length];
2628 unfixed_types [i] = typeArguments [i];
2630 fixed_types [i] = typeArguments [i];
2635 public Type[] InferredTypeArguments {
2641 void AddToBounds (Type t, int index)
2643 ArrayList a = bounds [index];
2645 a = new ArrayList ();
2653 // SPEC: does not cover type inference using constraints
2655 if (TypeManager.IsGenericParameter (t)) {
2656 GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
2657 if (constraints != null) {
2658 //if (constraints.EffectiveBaseClass != null)
2659 // t = constraints.EffectiveBaseClass;
2665 bool AllTypesAreFixed (Type[] types)
2667 foreach (Type t in types) {
2668 if (t.IsGenericParameter) {
2674 if (t.IsGenericType)
2675 return AllTypesAreFixed (t.GetGenericArguments ());
2682 // 26.3.3.8 Exact Inference
2684 public int ExactInference (Type u, Type v)
2686 // If V is an array type
2691 if (u.GetArrayRank () != v.GetArrayRank ())
2694 return ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
2697 // If V is constructed type and U is constructed type
2698 if (v.IsGenericType && !v.IsGenericTypeDefinition) {
2699 if (!u.IsGenericType)
2702 Type [] ga_u = u.GetGenericArguments ();
2703 Type [] ga_v = v.GetGenericArguments ();
2704 if (ga_u.Length != ga_v.Length)
2708 for (int i = 0; i < ga_u.Length; ++i)
2709 score += ExactInference (ga_u [i], ga_v [i]);
2711 return score > 0 ? 1 : 0;
2714 // If V is one of the unfixed type arguments
2715 int pos = IsUnfixed (v);
2719 AddToBounds (u, pos);
2723 public bool FixAllTypes ()
2725 for (int i = 0; i < unfixed_types.Length; ++i) {
2733 // All unfixed type variables Xi are fixed for which all of the following hold:
2734 // a, There is at least one type variable Xj that depends on Xi
2735 // b, Xi has a non-empty set of bounds
2737 public bool FixDependentTypes (ParameterData methodParameters, ref bool fixed_any)
2739 for (int i = 0; i < unfixed_types.Length; ++i) {
2740 if (unfixed_types[i] == null)
2743 if (bounds[i] == null)
2756 // All unfixed type variables Xi which depend on no Xj are fixed
2758 public bool FixIndependentTypeArguments (ParameterData methodParameters, ref bool fixed_any)
2760 ArrayList types_to_fix = new ArrayList (unfixed_types);
2761 for (int i = 0; i < methodParameters.Types.Length; ++i) {
2762 Type t = methodParameters.Types [i];
2763 if (t.IsGenericParameter)
2766 if (!TypeManager.IsDelegateType (t)) {
2767 if (TypeManager.DropGenericTypeArguments (t) != TypeManager.expression_type)
2770 t = t.GetGenericArguments () [0];
2773 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
2774 Type rtype = invoke.ReturnType;
2775 if (!rtype.IsGenericParameter && !rtype.IsGenericType)
2779 // Blablabla, because reflection does not work with dynamic types
2780 if (rtype.IsGenericParameter) {
2781 Type [] g_args = t.GetGenericArguments ();
2782 rtype = g_args [rtype.GenericParameterPosition];
2785 // Remove dependent types, they cannot be fixed yet
2786 RemoveDependentTypes (types_to_fix, rtype);
2789 foreach (Type t in types_to_fix) {
2793 int idx = IsUnfixed (t);
2794 if (idx >= 0 && !FixType (idx)) {
2799 fixed_any = types_to_fix.Count > 0;
2806 public bool FixType (int i)
2808 // It's already fixed
2809 if (unfixed_types[i] == null)
2810 throw new InternalErrorException ("Type argument has been already fixed");
2812 ArrayList candidates = (ArrayList)bounds [i];
2813 if (candidates == null)
2816 if (candidates.Count == 1) {
2817 unfixed_types[i] = null;
2818 fixed_types[i] = (Type)candidates[0];
2823 // Determines a unique type from which there is
2824 // a standard implicit conversion to all the other
2827 Type best_candidate = null;
2829 int candidates_count = candidates.Count;
2830 for (int ci = 0; ci < candidates_count; ++ci) {
2831 Type candidate = (Type)candidates [ci];
2832 for (cii = 0; cii < candidates_count; ++cii) {
2836 if (!Convert.ImplicitConversionExists (null,
2837 new TypeExpression ((Type)candidates [cii], Location.Null), candidate)) {
2842 if (cii != candidates_count)
2845 if (best_candidate != null)
2848 best_candidate = candidate;
2851 if (best_candidate == null)
2854 unfixed_types[i] = null;
2855 fixed_types[i] = best_candidate;
2860 // Uses inferred types to inflate delegate type argument
2862 public Type InflateGenericArgument (Type parameter)
2864 if (parameter.IsGenericParameter)
2865 return fixed_types [parameter.GenericParameterPosition];
2867 if (parameter.IsGenericType) {
2868 Type [] parameter_targs = parameter.GetGenericArguments ();
2869 for (int ii = 0; ii < parameter_targs.Length; ++ii) {
2870 parameter_targs [ii] = InflateGenericArgument (parameter_targs [ii]);
2872 return parameter.GetGenericTypeDefinition ().MakeGenericType (parameter_targs);
2879 // Tests whether all delegate input arguments are fixed and generic output type
2880 // requires output type inference
2882 public bool IsReturnTypeNonDependent (MethodInfo invoke, Type returnType)
2884 if (returnType.IsGenericParameter) {
2885 if (IsFixed (returnType))
2887 } else if (returnType.IsGenericType) {
2888 if (TypeManager.IsDelegateType (returnType)) {
2889 invoke = Delegate.GetInvokeMethod (returnType, returnType);
2890 return IsReturnTypeNonDependent (invoke, invoke.ReturnType);
2893 Type[] g_args = returnType.GetGenericArguments ();
2895 // At least one unfixed return type has to exist
2896 if (AllTypesAreFixed (g_args))
2902 // All generic input arguments have to be fixed
2903 ParameterData d_parameters = TypeManager.GetParameterData (invoke);
2904 return AllTypesAreFixed (d_parameters.Types);
2907 bool IsFixed (Type type)
2909 return IsUnfixed (type) == -1;
2912 int IsUnfixed (Type type)
2914 if (!type.IsGenericParameter)
2917 //return unfixed_types[type.GenericParameterPosition] != null;
2918 for (int i = 0; i < unfixed_types.Length; ++i) {
2919 if (unfixed_types [i] == type)
2927 // 26.3.3.9 Lower-bound Inference
2929 public int LowerBoundInference (Type u, Type v)
2931 // Remove ref, out modifiers
2933 v = v.GetElementType ();
2935 // If V is one of the unfixed type arguments
2936 int pos = IsUnfixed (v);
2938 AddToBounds (u, pos);
2942 // If U is an array type
2944 int u_dim = u.GetArrayRank ();
2946 Type u_e = TypeManager.GetElementType (u);
2949 if (u_dim != v.GetArrayRank ())
2952 v_e = TypeManager.GetElementType (v);
2955 return LowerBoundInference (u_e, v_e);
2958 return ExactInference (u_e, v_e);
2964 if (v.IsGenericType) {
2965 Type g_v = v.GetGenericTypeDefinition ();
2966 if ((g_v != TypeManager.generic_ilist_type) && (g_v != TypeManager.generic_icollection_type) &&
2967 (g_v != TypeManager.generic_ienumerable_type))
2970 v_e = TypeManager.GetTypeArguments (v)[0];
2973 return LowerBoundInference (u_e, v_e);
2976 return ExactInference (u_e, v_e);
2978 } else if (v.IsGenericType && !v.IsGenericTypeDefinition) {
2980 // if V is a constructed type C<V1..Vk> and there is a unique set of types U1..Uk
2981 // such that a standard implicit conversion exists from U to C<U1..Uk> then an exact
2982 // inference is made from each Ui for the corresponding Vi
2984 ArrayList u_candidates = new ArrayList ();
2985 if (u.IsGenericType)
2986 u_candidates.Add (u);
2988 for (Type t = u.BaseType; t != null; t = t.BaseType) {
2989 if (t.IsGenericType && !t.IsGenericTypeDefinition)
2990 u_candidates.Add (t);
2993 // TODO: Implement GetGenericInterfaces only and remove
2994 // the if from foreach
2995 u_candidates.AddRange (TypeManager.GetInterfaces (u));
2997 Type open_v = v.GetGenericTypeDefinition ();
2999 foreach (Type u_candidate in u_candidates) {
3000 if (!u_candidate.IsGenericType || u_candidate.IsGenericTypeDefinition)
3003 if (TypeManager.DropGenericTypeArguments (u_candidate) != open_v)
3006 Type [] ga_u = u_candidate.GetGenericArguments ();
3007 Type [] ga_v = v.GetGenericArguments ();
3008 bool all_exact = true;
3009 for (int i = 0; i < ga_u.Length; ++i)
3010 if (ExactInference (ga_u [i], ga_v [i]) == 0)
3013 if (all_exact && score == 0)
3023 // 26.3.3.6 Output Type Inference
3025 public int OutputTypeInference (EmitContext ec, Expression e, Type t)
3027 // If e is a lambda or anonymous method with inferred return type
3028 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
3030 Type rt = ame.InferReturnType (ec, this, t);
3031 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
3034 ParameterData pd = TypeManager.GetParameterData (invoke);
3035 return ame.Parameters.Count == pd.Count ? 1 : 0;
3038 Type rtype = invoke.ReturnType;
3040 // Blablabla, because reflection does not work with dynamic types
3041 Type [] g_args = t.GetGenericArguments ();
3042 rtype = g_args [rtype.GenericParameterPosition];
3044 return LowerBoundInference (rt, rtype) + 1;
3047 if (e is MethodGroupExpr) {
3048 if (!TypeManager.IsDelegateType (t))
3051 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
3052 Type rtype = invoke.ReturnType;
3053 if (!TypeManager.IsGenericType (rtype))
3056 throw new NotImplementedException ();
3060 // if e is an expression with type U, then
3061 // a lower-bound inference is made from U for T
3063 return LowerBoundInference (e.Type, t) * 2;
3066 static void RemoveDependentTypes (ArrayList types, Type returnType)
3068 if (returnType.IsGenericParameter) {
3069 types [returnType.GenericParameterPosition] = null;
3073 if (returnType.IsGenericType) {
3074 foreach (Type t in returnType.GetGenericArguments ()) {
3075 RemoveDependentTypes (types, t);
3080 public bool UnfixedVariableExists {
3082 if (unfixed_types == null)
3085 foreach (Type ut in unfixed_types)
3093 public abstract class Nullable
3095 public sealed class NullableInfo
3097 public readonly Type Type;
3098 public readonly Type UnderlyingType;
3099 public readonly MethodInfo HasValue;
3100 public readonly MethodInfo Value;
3101 public readonly ConstructorInfo Constructor;
3103 public NullableInfo (Type type)
3106 UnderlyingType = TypeManager.GetTypeArguments (type) [0];
3108 PropertyInfo has_value_pi = TypeManager.GetCoreProperty (type, "HasValue");
3109 PropertyInfo value_pi = TypeManager.GetCoreProperty (type, "Value");
3111 HasValue = has_value_pi.GetGetMethod (false);
3112 Value = value_pi.GetGetMethod (false);
3113 Constructor = type.GetConstructor (new Type[] { UnderlyingType });
3117 public class HasValue : Expression
3122 private HasValue (Expression expr)
3127 public static Expression Create (Expression expr, EmitContext ec)
3129 return new HasValue (expr).Resolve (ec);
3132 public override void Emit (EmitContext ec)
3134 IMemoryLocation memory_loc = expr as IMemoryLocation;
3135 if (memory_loc == null) {
3136 LocalTemporary temp = new LocalTemporary (expr.Type);
3141 memory_loc.AddressOf (ec, AddressOp.LoadStore);
3142 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
3145 public override Expression DoResolve (EmitContext ec)
3147 this.info = new NullableInfo (expr.Type);
3149 type = TypeManager.bool_type;
3150 eclass = expr.eclass;
3155 public class Unwrap : Expression, IMemoryLocation, IAssignMethod
3160 LocalTemporary temp;
3163 protected Unwrap (Expression expr)
3166 this.loc = expr.Location;
3169 public static Unwrap Create (Expression expr, EmitContext ec)
3171 return new Unwrap (expr).Resolve (ec) as Unwrap;
3174 public override Expression CreateExpressionTree (EmitContext ec)
3176 return expr.CreateExpressionTree (ec);
3179 public override Expression DoResolve (EmitContext ec)
3184 temp = new LocalTemporary (expr.Type);
3186 info = new NullableInfo (expr.Type);
3187 type = info.UnderlyingType;
3188 eclass = expr.eclass;
3192 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
3194 return DoResolve (ec);
3197 public override void Emit (EmitContext ec)
3199 AddressOf (ec, AddressOp.LoadStore);
3200 ec.ig.EmitCall (OpCodes.Call, info.Value, null);
3203 public void EmitCheck (EmitContext ec)
3205 AddressOf (ec, AddressOp.LoadStore);
3206 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
3209 public override bool IsNull {
3215 public void Store (EmitContext ec)
3220 void create_temp (EmitContext ec)
3222 if ((temp != null) && !has_temp) {
3229 public void AddressOf (EmitContext ec, AddressOp mode)
3233 temp.AddressOf (ec, AddressOp.LoadStore);
3235 ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
3238 public void Emit (EmitContext ec, bool leave_copy)
3251 public void EmitAssign (EmitContext ec, Expression source,
3252 bool leave_copy, bool prepare_for_load)
3254 InternalWrap wrap = new InternalWrap (source, info, loc);
3255 ((IAssignMethod) expr).EmitAssign (ec, wrap, leave_copy, false);
3258 protected class InternalWrap : Expression
3260 public Expression expr;
3261 public NullableInfo info;
3263 public InternalWrap (Expression expr, NullableInfo info, Location loc)
3270 eclass = ExprClass.Value;
3273 public override Expression DoResolve (EmitContext ec)
3278 public override void Emit (EmitContext ec)
3281 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
3286 public class Wrap : Expression
3291 protected Wrap (Expression expr)
3294 this.loc = expr.Location;
3297 public static Wrap Create (Expression expr, EmitContext ec)
3299 return new Wrap (expr).Resolve (ec) as Wrap;
3302 public override Expression CreateExpressionTree (EmitContext ec)
3304 ArrayList args = new ArrayList (2);
3305 args.Add (new Argument (expr.CreateExpressionTree (ec)));
3306 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
3307 return CreateExpressionFactoryCall ("Convert", args);
3310 public override Expression DoResolve (EmitContext ec)
3315 TypeExpr target_type = new NullableType (expr.Type, loc);
3316 target_type = target_type.ResolveAsTypeTerminal (ec, false);
3317 if (target_type == null)
3320 type = target_type.Type;
3321 info = new NullableInfo (type);
3322 eclass = ExprClass.Value;
3326 public override void Emit (EmitContext ec)
3329 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
3334 // Represents null value converted to nullable type
3336 public class Null : Expression, IMemoryLocation
3338 public Null (Type target_type, Location loc)
3340 this.type = target_type;
3343 eclass = ExprClass.Value;
3346 public override Expression CreateExpressionTree (EmitContext ec)
3348 return EmptyCast.Create (new NullConstant (loc), type).CreateExpressionTree (ec);
3351 public override Expression DoResolve (EmitContext ec)
3356 public override void Emit (EmitContext ec)
3358 LocalTemporary value_target = new LocalTemporary (type);
3360 value_target.AddressOf (ec, AddressOp.Store);
3361 ec.ig.Emit (OpCodes.Initobj, type);
3362 value_target.Emit (ec);
3365 public override bool IsNull {
3371 public void AddressOf (EmitContext ec, AddressOp Mode)
3373 LocalTemporary value_target = new LocalTemporary (type);
3375 value_target.AddressOf (ec, AddressOp.Store);
3376 ec.ig.Emit (OpCodes.Initobj, type);
3377 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
3381 public abstract class Lifted : Expression, IMemoryLocation
3383 Expression expr, underlying, wrap, null_value;
3386 protected Lifted (Expression expr, Location loc)
3392 public override Expression CreateExpressionTree (EmitContext ec)
3394 return expr.CreateExpressionTree (ec);
3397 public override Expression DoResolve (EmitContext ec)
3399 expr = expr.Resolve (ec);
3403 unwrap = Unwrap.Create (expr, ec);
3407 underlying = ResolveUnderlying (unwrap, ec);
3408 if (underlying == null)
3411 wrap = Wrap.Create (underlying, ec);
3415 null_value = new Null (wrap.Type, loc).Resolve (ec);
3416 if (null_value == null)
3420 eclass = ExprClass.Value;
3424 protected abstract Expression ResolveUnderlying (Expression unwrap, EmitContext ec);
3426 public override void Emit (EmitContext ec)
3428 ILGenerator ig = ec.ig;
3429 Label is_null_label = ig.DefineLabel ();
3430 Label end_label = ig.DefineLabel ();
3432 unwrap.EmitCheck (ec);
3433 ig.Emit (OpCodes.Brfalse, is_null_label);
3436 ig.Emit (OpCodes.Br, end_label);
3438 ig.MarkLabel (is_null_label);
3439 null_value.Emit (ec);
3441 ig.MarkLabel (end_label);
3444 public void AddressOf (EmitContext ec, AddressOp mode)
3446 unwrap.AddressOf (ec, mode);
3450 public class LiftedConversion : Lifted
3452 public readonly bool IsUser;
3453 public readonly bool IsExplicit;
3454 public readonly Type TargetType;
3456 public LiftedConversion (Expression expr, Type target_type, bool is_user,
3457 bool is_explicit, Location loc)
3460 this.IsUser = is_user;
3461 this.IsExplicit = is_explicit;
3462 this.TargetType = target_type;
3465 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
3467 Type type = TypeManager.GetTypeArguments (TargetType) [0];
3470 return Convert.UserDefinedConversion (ec, unwrap, type, loc, IsExplicit);
3473 return Convert.ExplicitConversion (ec, unwrap, type, loc);
3475 return Convert.ImplicitConversion (ec, unwrap, type, loc);
3480 public class LiftedUnaryOperator : Lifted
3482 public readonly Unary.Operator Oper;
3484 public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
3490 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
3492 return new Unary (Oper, unwrap, loc).Resolve (ec);
3496 public class LiftedBinaryOperator : Binary
3498 Expression underlying, null_value, bool_wrap;
3499 Unwrap left_unwrap, right_unwrap;
3500 bool is_equality, is_comparision, is_boolean;
3502 public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
3504 : base (op, left, right)
3509 public override Expression DoResolve (EmitContext ec)
3511 if ((Oper == Binary.Operator.LogicalAnd) ||
3512 (Oper == Binary.Operator.LogicalOr)) {
3513 Error_OperatorCannotBeApplied ();
3518 // Optimize null comparisons
3520 if (Oper == Binary.Operator.Equality) {
3522 return new Unary (Unary.Operator.LogicalNot, Nullable.HasValue.Create (right, ec), loc).Resolve (ec);
3524 return new Unary (Unary.Operator.LogicalNot, Nullable.HasValue.Create (left, ec), loc).Resolve (ec);
3526 if (Oper == Binary.Operator.Inequality) {
3528 return Nullable.HasValue.Create (right, ec);
3530 return Nullable.HasValue.Create (left, ec);
3533 if (TypeManager.IsNullableType (left.Type)) {
3534 left = left_unwrap = Unwrap.Create (left, ec);
3539 if (TypeManager.IsNullableType (right.Type)) {
3540 right = right_unwrap = Unwrap.Create (right, ec);
3545 if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr)) &&
3546 ((left.Type == TypeManager.bool_type) && (right.Type == TypeManager.bool_type))) {
3547 Expression empty = new EmptyExpression (TypeManager.bool_type);
3548 bool_wrap = Wrap.Create (empty, ec);
3549 null_value = new Null (bool_wrap.Type, loc).Resolve (ec);
3551 type = bool_wrap.Type;
3553 } else if ((Oper == Binary.Operator.Equality) || (Oper == Binary.Operator.Inequality)) {
3554 underlying = new Binary (Oper, left, right).Resolve (ec);
3555 if (underlying == null)
3557 type = TypeManager.bool_type;
3559 } else if ((Oper == Binary.Operator.LessThan) ||
3560 (Oper == Binary.Operator.GreaterThan) ||
3561 (Oper == Binary.Operator.LessThanOrEqual) ||
3562 (Oper == Binary.Operator.GreaterThanOrEqual)) {
3563 underlying = new Binary (Oper, left, right).Resolve (ec);
3564 if (underlying == null)
3567 type = TypeManager.bool_type;
3568 is_comparision = true;
3570 underlying = new Binary (Oper, left, right).Resolve (ec);
3571 if (underlying == null)
3574 underlying = Wrap.Create (underlying, ec);
3575 if (underlying == null)
3578 type = underlying.Type;
3579 null_value = new Null (type, loc).Resolve (ec);
3582 eclass = ExprClass.Value;
3586 void EmitBoolean (EmitContext ec)
3588 ILGenerator ig = ec.ig;
3590 Label left_is_null_label = ig.DefineLabel ();
3591 Label right_is_null_label = ig.DefineLabel ();
3592 Label is_null_label = ig.DefineLabel ();
3593 Label wrap_label = ig.DefineLabel ();
3594 Label end_label = ig.DefineLabel ();
3596 if (left_unwrap != null) {
3597 left_unwrap.EmitCheck (ec);
3598 ig.Emit (OpCodes.Brfalse, left_is_null_label);
3602 ig.Emit (OpCodes.Dup);
3603 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3604 ig.Emit (OpCodes.Brtrue, wrap_label);
3606 ig.Emit (OpCodes.Brfalse, wrap_label);
3608 if (right_unwrap != null) {
3609 right_unwrap.EmitCheck (ec);
3610 ig.Emit (OpCodes.Brfalse, right_is_null_label);
3613 if ((Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr))
3614 ig.Emit (OpCodes.Pop);
3617 if (Oper == Binary.Operator.BitwiseOr)
3618 ig.Emit (OpCodes.Or);
3619 else if (Oper == Binary.Operator.BitwiseAnd)
3620 ig.Emit (OpCodes.And);
3621 ig.Emit (OpCodes.Br, wrap_label);
3623 ig.MarkLabel (left_is_null_label);
3624 if (right_unwrap != null) {
3625 right_unwrap.EmitCheck (ec);
3626 ig.Emit (OpCodes.Brfalse, is_null_label);
3630 ig.Emit (OpCodes.Dup);
3631 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3632 ig.Emit (OpCodes.Brtrue, wrap_label);
3634 ig.Emit (OpCodes.Brfalse, wrap_label);
3636 ig.MarkLabel (right_is_null_label);
3637 ig.Emit (OpCodes.Pop);
3638 ig.MarkLabel (is_null_label);
3639 null_value.Emit (ec);
3640 ig.Emit (OpCodes.Br, end_label);
3642 ig.MarkLabel (wrap_label);
3643 ig.Emit (OpCodes.Nop);
3644 bool_wrap.Emit (ec);
3645 ig.Emit (OpCodes.Nop);
3647 ig.MarkLabel (end_label);
3650 void EmitEquality (EmitContext ec)
3652 if (left.IsNull || right.IsNull)
3653 throw new InternalErrorException ("Unoptimized nullable comparison");
3655 ILGenerator ig = ec.ig;
3657 Label both_have_value_label = ig.DefineLabel ();
3658 Label end_label = ig.DefineLabel ();
3660 if (left_unwrap != null && right_unwrap != null) {
3661 Label dissimilar_label = ig.DefineLabel ();
3663 left_unwrap.EmitCheck (ec);
3664 ig.Emit (OpCodes.Dup);
3665 right_unwrap.EmitCheck (ec);
3666 ig.Emit (OpCodes.Bne_Un, dissimilar_label);
3668 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3671 if (Oper == Binary.Operator.Equality)
3672 ig.Emit (OpCodes.Ldc_I4_1);
3674 ig.Emit (OpCodes.Ldc_I4_0);
3675 ig.Emit (OpCodes.Br, end_label);
3677 ig.MarkLabel (dissimilar_label);
3678 ig.Emit (OpCodes.Pop);
3679 } else if (left_unwrap != null) {
3680 left_unwrap.EmitCheck (ec);
3681 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3682 } else if (right_unwrap != null) {
3683 right_unwrap.EmitCheck (ec);
3684 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3686 throw new InternalErrorException ("shouldn't get here");
3689 // one is null while the other isn't
3690 if (Oper == Binary.Operator.Equality)
3691 ig.Emit (OpCodes.Ldc_I4_0);
3693 ig.Emit (OpCodes.Ldc_I4_1);
3694 ig.Emit (OpCodes.Br, end_label);
3696 ig.MarkLabel (both_have_value_label);
3697 underlying.Emit (ec);
3699 ig.MarkLabel (end_label);
3702 void EmitComparision (EmitContext ec)
3704 ILGenerator ig = ec.ig;
3706 Label is_null_label = ig.DefineLabel ();
3707 Label end_label = ig.DefineLabel ();
3709 if (left_unwrap != null) {
3710 left_unwrap.EmitCheck (ec);
3711 ig.Emit (OpCodes.Brfalse, is_null_label);
3714 if (right_unwrap != null) {
3715 right_unwrap.EmitCheck (ec);
3716 ig.Emit (OpCodes.Brfalse, is_null_label);
3719 underlying.Emit (ec);
3720 ig.Emit (OpCodes.Br, end_label);
3722 ig.MarkLabel (is_null_label);
3723 ig.Emit (OpCodes.Ldc_I4_0);
3725 ig.MarkLabel (end_label);
3728 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
3731 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
3734 public override void Emit (EmitContext ec)
3736 if (left_unwrap != null)
3737 left_unwrap.Store (ec);
3738 if (right_unwrap != null)
3739 right_unwrap.Store (ec);
3744 } else if (is_equality) {
3747 } else if (is_comparision) {
3748 EmitComparision (ec);
3752 ILGenerator ig = ec.ig;
3754 Label is_null_label = ig.DefineLabel ();
3755 Label end_label = ig.DefineLabel ();
3757 if (left_unwrap != null) {
3758 left_unwrap.EmitCheck (ec);
3759 ig.Emit (OpCodes.Brfalse, is_null_label);
3762 if (right_unwrap != null) {
3763 right_unwrap.EmitCheck (ec);
3764 ig.Emit (OpCodes.Brfalse, is_null_label);
3767 underlying.Emit (ec);
3768 ig.Emit (OpCodes.Br, end_label);
3770 ig.MarkLabel (is_null_label);
3771 null_value.Emit (ec);
3773 ig.MarkLabel (end_label);
3777 public class NullCoalescingOperator : Expression
3779 Expression left, right;
3782 public NullCoalescingOperator (Expression left, Expression right, Location loc)
3789 public override Expression CreateExpressionTree (EmitContext ec)
3791 UserCast uc = left as UserCast;
3792 Expression conversion = null;
3796 ArrayList c_args = new ArrayList (2);
3797 c_args.Add (new Argument (uc.CreateExpressionTree (ec)));
3798 c_args.Add (new Argument (left.CreateExpressionTree (ec)));
3799 conversion = CreateExpressionFactoryCall ("Lambda", c_args);
3802 ArrayList args = new ArrayList (3);
3803 args.Add (new Argument (left.CreateExpressionTree (ec)));
3804 args.Add (new Argument (right.CreateExpressionTree (ec)));
3805 if (conversion != null)
3806 args.Add (new Argument (conversion));
3808 return CreateExpressionFactoryCall ("Coalesce", args);
3811 public override Expression DoResolve (EmitContext ec)
3816 left = left.Resolve (ec);
3817 right = right.Resolve (ec);
3819 if (left == null || right == null)
3822 eclass = ExprClass.Value;
3823 Type ltype = left.Type, rtype = right.Type;
3826 if (TypeManager.IsNullableType (ltype)) {
3827 NullableInfo info = new NullableInfo (ltype);
3829 unwrap = Unwrap.Create (left, ec);
3833 expr = Convert.ImplicitConversion (ec, right, info.UnderlyingType, loc);
3840 } else if (!TypeManager.IsReferenceType (ltype)) {
3841 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3845 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
3852 Expression left_null = unwrap != null ? unwrap : left;
3853 expr = Convert.ImplicitConversion (ec, left_null, rtype, loc);
3860 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3864 public override void Emit (EmitContext ec)
3866 ILGenerator ig = ec.ig;
3868 Label is_null_label = ig.DefineLabel ();
3869 Label end_label = ig.DefineLabel ();
3871 if (unwrap != null) {
3872 unwrap.EmitCheck (ec);
3873 ig.Emit (OpCodes.Brfalse, is_null_label);
3876 ig.Emit (OpCodes.Br, end_label);
3878 ig.MarkLabel (is_null_label);
3881 ig.MarkLabel (end_label);
3884 ig.Emit (OpCodes.Dup);
3885 ig.Emit (OpCodes.Brtrue, end_label);
3887 ig.MarkLabel (is_null_label);
3889 ig.Emit (OpCodes.Pop);
3892 ig.MarkLabel (end_label);
3895 protected override void CloneTo (CloneContext clonectx, Expression t)
3897 NullCoalescingOperator target = (NullCoalescingOperator) t;
3899 target.left = left.Clone (clonectx);
3900 target.right = right.Clone (clonectx);
3904 public class LiftedUnaryMutator : ExpressionStatement
3906 public readonly UnaryMutator.Mode Mode;
3907 Expression expr, null_value;
3908 UnaryMutator underlying;
3911 public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
3917 eclass = ExprClass.Value;
3920 public override Expression DoResolve (EmitContext ec)
3922 expr = expr.Resolve (ec);
3926 unwrap = Unwrap.Create (expr, ec);
3930 underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
3931 if (underlying == null)
3934 null_value = new Null (expr.Type, loc).Resolve (ec);
3935 if (null_value == null)
3942 void DoEmit (EmitContext ec, bool is_expr)
3944 ILGenerator ig = ec.ig;
3945 Label is_null_label = ig.DefineLabel ();
3946 Label end_label = ig.DefineLabel ();
3948 unwrap.EmitCheck (ec);
3949 ig.Emit (OpCodes.Brfalse, is_null_label);
3952 underlying.Emit (ec);
3954 underlying.EmitStatement (ec);
3955 ig.Emit (OpCodes.Br, end_label);
3957 ig.MarkLabel (is_null_label);
3959 null_value.Emit (ec);
3961 ig.MarkLabel (end_label);
3964 public override void Emit (EmitContext ec)
3969 public override void EmitStatement (EmitContext ec)