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
609 GenericConstraints gc;
610 Constraints constraints;
612 GenericTypeParameterBuilder type;
613 MemberCache member_cache;
615 public TypeParameter (DeclSpace parent, DeclSpace decl, string name,
616 Constraints constraints, Attributes attrs, Location loc)
617 : base (parent, new MemberName (name, loc), attrs)
621 this.constraints = constraints;
625 public GenericConstraints GenericConstraints {
626 get { return gc != null ? gc : constraints; }
629 public Constraints Constraints {
630 get { return constraints; }
633 public DeclSpace DeclSpace {
642 /// This is the first method which is called during the resolving
643 /// process; we're called immediately after creating the type parameters
644 /// with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
647 /// We're either called from TypeContainer.DefineType() or from
648 /// GenericMethod.Define() (called from Method.Define()).
650 public void Define (GenericTypeParameterBuilder type)
652 if (this.type != null)
653 throw new InvalidOperationException ();
656 TypeManager.AddTypeParameter (type, this);
660 /// This is the second method which is called during the resolving
661 /// process - in case of class type parameters, we're called from
662 /// TypeContainer.ResolveType() - after it resolved the class'es
663 /// base class and interfaces. For method type parameters, we're
664 /// called immediately after Define().
666 /// We're just resolving the constraints into expressions here, we
667 /// don't resolve them into actual types.
669 /// Note that in the special case of partial generic classes, we may be
670 /// called _before_ Define() and we may also be called multiple types.
672 public bool Resolve (DeclSpace ds)
674 if (constraints != null) {
675 if (!constraints.Resolve (ds)) {
685 /// This is the third method which is called during the resolving
686 /// process. We're called immediately after calling DefineConstraints()
687 /// on all of the current class'es type parameters.
689 /// Our job is to resolve the constraints to actual types.
691 /// Note that we may have circular dependencies on type parameters - this
692 /// is why Resolve() and ResolveType() are separate.
694 public bool ResolveType (IResolveContext ec)
696 if (constraints != null) {
697 if (!constraints.ResolveTypes (ec)) {
707 /// This is the fourth 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 public bool DefineType (IResolveContext ec)
713 return DefineType (ec, null, null, false);
717 /// This is the fith and last method which is called during the resolving
718 /// process. We're called after everything is fully resolved and actually
719 /// register the constraints with SRE and the TypeManager.
721 /// The `builder', `implementing' and `is_override' arguments are only
722 /// applicable to method type parameters.
724 public bool DefineType (IResolveContext ec, MethodBuilder builder,
725 MethodInfo implementing, bool is_override)
727 if (!ResolveType (ec))
730 if (implementing != null) {
731 if (is_override && (constraints != null)) {
732 Report.Error (460, loc,
733 "`{0}': Cannot specify constraints for overrides or explicit interface implementation methods",
734 TypeManager.CSharpSignature (builder));
738 MethodBase mb = TypeManager.DropGenericMethodArguments (implementing);
740 int pos = type.GenericParameterPosition;
741 Type mparam = mb.GetGenericArguments () [pos];
742 GenericConstraints temp_gc = ReflectionConstraints.GetConstraints (mparam);
745 gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
746 else if (constraints != null)
747 gc = new InflatedConstraints (constraints, implementing.DeclaringType);
750 if (constraints != null) {
753 else if (!constraints.CheckInterfaceMethod (gc))
756 if (!is_override && (temp_gc != null))
761 Report.SymbolRelatedToPreviousError (implementing);
764 425, loc, "The constraints for type " +
765 "parameter `{0}' of method `{1}' must match " +
766 "the constraints for type parameter `{2}' " +
767 "of interface method `{3}'. Consider using " +
768 "an explicit interface implementation instead",
769 Name, TypeManager.CSharpSignature (builder),
770 TypeManager.CSharpName (mparam), TypeManager.CSharpSignature (mb));
773 } else if (DeclSpace is CompilerGeneratedClass) {
774 TypeParameter[] tparams = DeclSpace.TypeParameters;
775 Type[] types = new Type [tparams.Length];
776 for (int i = 0; i < tparams.Length; i++)
777 types [i] = tparams [i].Type;
779 if (constraints != null)
780 gc = new InflatedConstraints (constraints, types);
782 gc = (GenericConstraints) constraints;
788 if (gc.HasClassConstraint)
789 type.SetBaseTypeConstraint (gc.ClassConstraint);
791 type.SetInterfaceConstraints (gc.InterfaceConstraints);
792 type.SetGenericParameterAttributes (gc.Attributes);
793 TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
799 /// Check whether there are no conflicts in our type parameter constraints.
801 /// This is an example:
805 /// where U : T, struct
807 public bool CheckDependencies ()
809 if (constraints != null)
810 return constraints.CheckDependencies ();
816 /// This is called for each part of a partial generic type definition.
818 /// If `new_constraints' is not null and we don't already have constraints,
819 /// they become our constraints. If we already have constraints, we must
820 /// check that they're the same.
823 public bool UpdateConstraints (IResolveContext ec, Constraints new_constraints)
826 throw new InvalidOperationException ();
828 if (new_constraints == null)
831 if (!new_constraints.Resolve (ec))
833 if (!new_constraints.ResolveTypes (ec))
836 if (constraints != null)
837 return constraints.CheckInterfaceMethod (new_constraints);
839 constraints = new_constraints;
843 public override void Emit ()
845 if (OptAttributes != null)
846 OptAttributes.Emit ();
851 public override string DocCommentHeader {
853 throw new InvalidOperationException (
854 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
862 public override bool Define ()
867 public override void ApplyAttributeBuilder (Attribute a,
868 CustomAttributeBuilder cb)
870 type.SetCustomAttribute (cb);
873 public override AttributeTargets AttributeTargets {
875 return (AttributeTargets) AttributeTargets.GenericParameter;
879 public override string[] ValidAttributeTargets {
881 return new string [] { "type parameter" };
889 string IMemberContainer.Name {
893 MemberCache IMemberContainer.BaseCache {
898 if (gc.EffectiveBaseClass.BaseType == null)
901 return TypeManager.LookupMemberCache (gc.EffectiveBaseClass.BaseType);
905 bool IMemberContainer.IsInterface {
906 get { return false; }
909 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
911 throw new NotSupportedException ();
914 public MemberCache MemberCache {
916 if (member_cache != null)
922 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
923 member_cache = new MemberCache (this, gc.EffectiveBaseClass, ifaces);
929 public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
930 MemberFilter filter, object criteria)
933 return MemberList.Empty;
935 ArrayList members = new ArrayList ();
937 if (gc.HasClassConstraint) {
938 MemberList list = TypeManager.FindMembers (
939 gc.ClassConstraint, mt, bf, filter, criteria);
941 members.AddRange (list);
944 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
945 foreach (Type t in ifaces) {
946 MemberList list = TypeManager.FindMembers (
947 t, mt, bf, filter, criteria);
949 members.AddRange (list);
952 return new MemberList (members);
955 public bool IsSubclassOf (Type t)
960 if (constraints != null)
961 return constraints.IsSubclassOf (t);
966 public override string ToString ()
968 return "TypeParameter[" + name + "]";
971 public static string GetSignatureForError (TypeParameter[] tp)
973 if (tp == null || tp.Length == 0)
976 StringBuilder sb = new StringBuilder ("<");
977 for (int i = 0; i < tp.Length; ++i) {
980 sb.Append (tp[i].GetSignatureForError ());
983 return sb.ToString ();
986 public void InflateConstraints (Type declaring)
988 if (constraints != null)
989 gc = new InflatedConstraints (constraints, declaring);
992 public override bool IsClsComplianceRequired ()
997 protected class InflatedConstraints : GenericConstraints
999 GenericConstraints gc;
1001 Type class_constraint;
1002 Type[] iface_constraints;
1005 public InflatedConstraints (GenericConstraints gc, Type declaring)
1006 : this (gc, TypeManager.GetTypeArguments (declaring))
1009 public InflatedConstraints (GenericConstraints gc, Type[] dargs)
1014 ArrayList list = new ArrayList ();
1015 if (gc.HasClassConstraint)
1016 list.Add (inflate (gc.ClassConstraint));
1017 foreach (Type iface in gc.InterfaceConstraints)
1018 list.Add (inflate (iface));
1020 bool has_class_constr = false;
1021 if (list.Count > 0) {
1022 Type first = (Type) list [0];
1023 has_class_constr = !first.IsGenericParameter && !first.IsInterface;
1026 if ((list.Count > 0) && has_class_constr) {
1027 class_constraint = (Type) list [0];
1028 iface_constraints = new Type [list.Count - 1];
1029 list.CopyTo (1, iface_constraints, 0, list.Count - 1);
1031 iface_constraints = new Type [list.Count];
1032 list.CopyTo (iface_constraints, 0);
1035 if (HasValueTypeConstraint)
1036 base_type = TypeManager.value_type;
1037 else if (class_constraint != null)
1038 base_type = class_constraint;
1040 base_type = TypeManager.object_type;
1043 Type inflate (Type t)
1047 if (t.IsGenericParameter)
1048 return dargs [t.GenericParameterPosition];
1049 if (t.IsGenericType) {
1050 Type[] args = t.GetGenericArguments ();
1051 Type[] inflated = new Type [args.Length];
1053 for (int i = 0; i < args.Length; i++)
1054 inflated [i] = inflate (args [i]);
1056 t = t.GetGenericTypeDefinition ();
1057 t = t.MakeGenericType (inflated);
1063 public override string TypeParameter {
1064 get { return gc.TypeParameter; }
1067 public override GenericParameterAttributes Attributes {
1068 get { return gc.Attributes; }
1071 public override Type ClassConstraint {
1072 get { return class_constraint; }
1075 public override Type EffectiveBaseClass {
1076 get { return base_type; }
1079 public override Type[] InterfaceConstraints {
1080 get { return iface_constraints; }
1086 /// A TypeExpr which already resolved to a type parameter.
1088 public class TypeParameterExpr : TypeExpr {
1089 TypeParameter type_parameter;
1091 public override string Name {
1093 return type_parameter.Name;
1097 public override string FullName {
1099 return type_parameter.Name;
1103 public TypeParameter TypeParameter {
1105 return type_parameter;
1109 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1111 this.type_parameter = type_parameter;
1115 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1117 type = type_parameter.Type;
1122 public override bool IsInterface {
1123 get { return false; }
1126 public override bool CheckAccessLevel (DeclSpace ds)
1131 public void Error_CannotUseAsUnmanagedType (Location loc)
1133 Report.Error (-203, loc, "Can not use type parameter as unmanaged type");
1138 /// Tracks the type arguments when instantiating a generic type. We're used in
1139 /// ConstructedType.
1141 public class TypeArguments {
1142 public readonly Location Location;
1149 public TypeArguments (Location loc)
1151 args = new ArrayList ();
1152 this.Location = loc;
1155 public TypeArguments (Location loc, params Expression[] types)
1157 this.Location = loc;
1158 this.args = new ArrayList (types);
1161 public TypeArguments (int dimension, Location loc)
1163 this.dimension = dimension;
1164 this.Location = loc;
1167 public void Add (Expression type)
1170 throw new InvalidOperationException ();
1175 public void Add (TypeArguments new_args)
1178 throw new InvalidOperationException ();
1180 args.AddRange (new_args.args);
1184 /// We're used during the parsing process: the parser can't distinguish
1185 /// between type parameters and type arguments. Because of that, the
1186 /// parser creates a `MemberName' with `TypeArguments' for both cases and
1187 /// in case of a generic type definition, we call GetDeclarations().
1189 public TypeParameterName[] GetDeclarations ()
1191 TypeParameterName[] ret = new TypeParameterName [args.Count];
1192 for (int i = 0; i < args.Count; i++) {
1193 TypeParameterName name = args [i] as TypeParameterName;
1198 SimpleName sn = args [i] as SimpleName;
1200 ret [i] = new TypeParameterName (sn.Name, null, sn.Location);
1204 Report.Error (81, Location, "Type parameter declaration " +
1205 "must be an identifier not a type");
1212 /// We may only be used after Resolve() is called and return the fully
1215 public Type[] Arguments {
1221 public bool HasTypeArguments {
1223 return has_type_args;
1236 public bool IsUnbound {
1238 return dimension > 0;
1242 public override string ToString ()
1244 StringBuilder s = new StringBuilder ();
1247 for (int i = 0; i < count; i++){
1249 // FIXME: Use TypeManager.CSharpname once we have the type
1252 s.Append (args [i].ToString ());
1256 return s.ToString ();
1259 public string GetSignatureForError()
1261 StringBuilder sb = new StringBuilder();
1262 for (int i = 0; i < Count; ++i)
1264 Expression expr = (Expression)args [i];
1265 sb.Append(expr.GetSignatureForError());
1269 return sb.ToString();
1273 /// Resolve the type arguments.
1275 public bool Resolve (IResolveContext ec)
1277 int count = args.Count;
1280 atypes = new Type [count];
1282 for (int i = 0; i < count; i++){
1283 TypeExpr te = ((Expression) args [i]).ResolveAsTypeTerminal (ec, false);
1289 atypes[i] = te.Type;
1290 if (te.Type.IsGenericParameter) {
1291 if (te is TypeParameterExpr)
1292 has_type_args = true;
1296 if (te.Type.IsSealed && te.Type.IsAbstract) {
1297 Report.Error (718, Location, "`{0}': static classes cannot be used as generic arguments",
1298 te.GetSignatureForError ());
1302 if (te.Type.IsPointer) {
1303 Report.Error (306, Location, "The type `{0}' may not be used " +
1304 "as a type argument", TypeManager.CSharpName (te.Type));
1308 if (te.Type == TypeManager.void_type) {
1309 Expression.Error_VoidInvalidInTheContext (Location);
1316 public TypeArguments Clone ()
1318 TypeArguments copy = new TypeArguments (Location);
1319 foreach (Expression ta in args)
1326 public class TypeParameterName : SimpleName
1328 Attributes attributes;
1330 public TypeParameterName (string name, Attributes attrs, Location loc)
1336 public Attributes OptAttributes {
1344 /// An instantiation of a generic type.
1346 public class ConstructedType : TypeExpr {
1348 FullNamedExpression name;
1350 Type[] gen_params, atypes;
1354 /// Instantiate the generic type `fname' with the type arguments `args'.
1356 public ConstructedType (FullNamedExpression fname, TypeArguments args, Location l)
1362 eclass = ExprClass.Type;
1363 full_name = name + "<" + args.ToString () + ">";
1366 protected ConstructedType (TypeArguments args, Location l)
1371 eclass = ExprClass.Type;
1374 protected ConstructedType (TypeParameter[] type_params, Location l)
1378 args = new TypeArguments (l);
1379 foreach (TypeParameter type_param in type_params)
1380 args.Add (new TypeParameterExpr (type_param, l));
1382 eclass = ExprClass.Type;
1386 /// This is used to construct the `this' type inside a generic type definition.
1388 public ConstructedType (Type t, TypeParameter[] type_params, Location l)
1389 : this (type_params, l)
1391 gt = t.GetGenericTypeDefinition ();
1393 this.name = new TypeExpression (gt, l);
1394 full_name = gt.FullName + "<" + args.ToString () + ">";
1398 /// Instantiate the generic type `t' with the type arguments `args'.
1399 /// Use this constructor if you already know the fully resolved
1402 public ConstructedType (Type t, TypeArguments args, Location l)
1405 gt = t.GetGenericTypeDefinition ();
1407 this.name = new TypeExpression (gt, l);
1408 full_name = gt.FullName + "<" + args.ToString () + ">";
1411 public TypeArguments TypeArguments {
1412 get { return args; }
1415 public override string GetSignatureForError ()
1417 return TypeManager.RemoveGenericArity (gt.FullName) + "<" + args.GetSignatureForError () + ">";
1420 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1422 if (!ResolveConstructedType (ec))
1429 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1430 /// after fully resolving the constructed type.
1432 public bool CheckConstraints (IResolveContext ec)
1434 return ConstraintChecker.CheckConstraints (ec, gt, gen_params, atypes, loc);
1438 /// Resolve the constructed type, but don't check the constraints.
1440 public bool ResolveConstructedType (IResolveContext ec)
1444 // If we already know the fully resolved generic type.
1446 return DoResolveType (ec);
1452 Report.Error (246, loc, "Cannot find type `{0}'<...>", Name);
1456 num_args = TypeManager.GetNumberOfTypeArguments (t);
1457 if (num_args == 0) {
1458 Report.Error (308, loc,
1459 "The non-generic type `{0}' cannot " +
1460 "be used with type arguments.",
1461 TypeManager.CSharpName (t));
1465 gt = t.GetGenericTypeDefinition ();
1466 return DoResolveType (ec);
1469 bool DoResolveType (IResolveContext ec)
1472 // Resolve the arguments.
1474 if (args.Resolve (ec) == false)
1477 gen_params = gt.GetGenericArguments ();
1478 atypes = args.Arguments;
1480 if (atypes.Length != gen_params.Length) {
1481 Report.Error (305, loc,
1482 "Using the generic type `{0}' " +
1483 "requires {1} type arguments",
1484 TypeManager.CSharpName (gt),
1485 gen_params.Length.ToString ());
1490 // Now bind the parameters.
1492 type = gt.MakeGenericType (atypes);
1496 public Expression GetSimpleName (EmitContext ec)
1501 public override bool CheckAccessLevel (DeclSpace ds)
1503 return ds.CheckAccessLevel (gt);
1506 public override bool AsAccessible (DeclSpace ds)
1508 foreach (Type t in atypes) {
1509 if (!ds.IsAccessibleAs (t))
1513 return ds.IsAccessibleAs (gt);
1516 public override bool IsClass {
1517 get { return gt.IsClass; }
1520 public override bool IsValueType {
1521 get { return gt.IsValueType; }
1524 public override bool IsInterface {
1525 get { return gt.IsInterface; }
1528 public override bool IsSealed {
1529 get { return gt.IsSealed; }
1532 public override bool Equals (object obj)
1534 ConstructedType cobj = obj as ConstructedType;
1538 if ((type == null) || (cobj.type == null))
1541 return type == cobj.type;
1544 public override int GetHashCode ()
1546 return base.GetHashCode ();
1549 public override string Name {
1555 public override string FullName {
1562 public abstract class ConstraintChecker
1564 protected readonly Type[] gen_params;
1565 protected readonly Type[] atypes;
1566 protected readonly Location loc;
1568 protected ConstraintChecker (Type[] gen_params, Type[] atypes, Location loc)
1570 this.gen_params = gen_params;
1571 this.atypes = atypes;
1576 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1577 /// after fully resolving the constructed type.
1579 public bool CheckConstraints (IResolveContext ec)
1581 for (int i = 0; i < gen_params.Length; i++) {
1582 if (!CheckConstraints (ec, i))
1589 protected bool CheckConstraints (IResolveContext ec, int index)
1591 Type atype = atypes [index];
1592 Type ptype = gen_params [index];
1597 Expression aexpr = new EmptyExpression (atype);
1599 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1603 bool is_class, is_struct;
1604 if (atype.IsGenericParameter) {
1605 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1607 if (agc is Constraints)
1608 ((Constraints) agc).Resolve (ec);
1609 is_class = agc.IsReferenceType;
1610 is_struct = agc.IsValueType;
1612 is_class = is_struct = false;
1617 if (!atype.IsGenericType)
1619 is_class = atype.IsClass || atype.IsInterface;
1620 is_struct = atype.IsValueType && !TypeManager.IsNullableType (atype);
1624 // First, check the `class' and `struct' constraints.
1626 if (gc.HasReferenceTypeConstraint && !is_class) {
1627 Report.Error (452, loc, "The type `{0}' must be " +
1628 "a reference type in order to use it " +
1629 "as type parameter `{1}' in the " +
1630 "generic type or method `{2}'.",
1631 TypeManager.CSharpName (atype),
1632 TypeManager.CSharpName (ptype),
1633 GetSignatureForError ());
1635 } else if (gc.HasValueTypeConstraint && !is_struct) {
1636 Report.Error (453, loc, "The type `{0}' must be a " +
1637 "non-nullable value type in order to use it " +
1638 "as type parameter `{1}' in the " +
1639 "generic type or method `{2}'.",
1640 TypeManager.CSharpName (atype),
1641 TypeManager.CSharpName (ptype),
1642 GetSignatureForError ());
1647 // The class constraint comes next.
1649 if (gc.HasClassConstraint) {
1650 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint))
1655 // Now, check the interface constraints.
1657 if (gc.InterfaceConstraints != null) {
1658 foreach (Type it in gc.InterfaceConstraints) {
1659 if (!CheckConstraint (ec, ptype, aexpr, it))
1665 // Finally, check the constructor constraint.
1668 if (!gc.HasConstructorConstraint)
1671 if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
1674 if (HasDefaultConstructor (atype))
1677 Report_SymbolRelatedToPreviousError ();
1678 Report.SymbolRelatedToPreviousError (atype);
1679 Report.Error (310, loc, "The type `{0}' must have a public " +
1680 "parameterless constructor in order to use it " +
1681 "as parameter `{1}' in the generic type or " +
1683 TypeManager.CSharpName (atype),
1684 TypeManager.CSharpName (ptype),
1685 GetSignatureForError ());
1689 protected bool CheckConstraint (IResolveContext ec, Type ptype, Expression expr,
1692 if (TypeManager.HasGenericArguments (ctype)) {
1693 Type[] types = TypeManager.GetTypeArguments (ctype);
1695 TypeArguments new_args = new TypeArguments (loc);
1697 for (int i = 0; i < types.Length; i++) {
1700 if (t.IsGenericParameter) {
1701 int pos = t.GenericParameterPosition;
1704 new_args.Add (new TypeExpression (t, loc));
1707 TypeExpr ct = new ConstructedType (ctype, new_args, loc);
1708 if (ct.ResolveAsTypeStep (ec, false) == null)
1711 } else if (ctype.IsGenericParameter) {
1712 int pos = ctype.GenericParameterPosition;
1713 ctype = atypes [pos];
1716 if (Convert.ImplicitStandardConversionExists (expr, ctype))
1719 Error_TypeMustBeConvertible (expr.Type, ctype, ptype);
1723 bool HasDefaultConstructor (Type atype)
1725 if (atype.IsAbstract)
1729 atype = TypeManager.DropGenericTypeArguments (atype);
1730 if (atype is TypeBuilder) {
1731 TypeContainer tc = TypeManager.LookupTypeContainer (atype);
1732 if (tc.InstanceConstructors == null) {
1733 atype = atype.BaseType;
1737 foreach (Constructor c in tc.InstanceConstructors) {
1738 if ((c.ModFlags & Modifiers.PUBLIC) == 0)
1740 if ((c.Parameters.FixedParameters != null) &&
1741 (c.Parameters.FixedParameters.Length != 0))
1743 if (c.Parameters.HasArglist || c.Parameters.HasParams)
1750 TypeParameter tparam = TypeManager.LookupTypeParameter (atype);
1751 if (tparam != null) {
1752 if (tparam.GenericConstraints == null)
1755 return tparam.GenericConstraints.HasConstructorConstraint ||
1756 tparam.GenericConstraints.HasValueTypeConstraint;
1759 MemberInfo [] list = TypeManager.MemberLookup (null, null, atype, MemberTypes.Constructor,
1760 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
1761 ConstructorInfo.ConstructorName, null);
1766 foreach (MethodBase mb in list) {
1767 ParameterData pd = TypeManager.GetParameterData (mb);
1775 protected abstract string GetSignatureForError ();
1776 protected abstract void Report_SymbolRelatedToPreviousError ();
1778 void Error_TypeMustBeConvertible (Type atype, Type gc, Type ptype)
1780 Report_SymbolRelatedToPreviousError ();
1781 Report.SymbolRelatedToPreviousError (atype);
1782 Report.Error (309, loc,
1783 "The type `{0}' must be convertible to `{1}' in order to " +
1784 "use it as parameter `{2}' in the generic type or method `{3}'",
1785 TypeManager.CSharpName (atype), TypeManager.CSharpName (gc),
1786 TypeManager.CSharpName (ptype), GetSignatureForError ());
1789 public static bool CheckConstraints (EmitContext ec, MethodBase definition,
1790 MethodBase instantiated, Location loc)
1792 MethodConstraintChecker checker = new MethodConstraintChecker (
1793 definition, definition.GetGenericArguments (),
1794 instantiated.GetGenericArguments (), loc);
1796 return checker.CheckConstraints (ec);
1799 public static bool CheckConstraints (IResolveContext ec, Type gt, Type[] gen_params,
1800 Type[] atypes, Location loc)
1802 TypeConstraintChecker checker = new TypeConstraintChecker (
1803 gt, gen_params, atypes, loc);
1805 return checker.CheckConstraints (ec);
1808 protected class MethodConstraintChecker : ConstraintChecker
1810 MethodBase definition;
1812 public MethodConstraintChecker (MethodBase definition, Type[] gen_params,
1813 Type[] atypes, Location loc)
1814 : base (gen_params, atypes, loc)
1816 this.definition = definition;
1819 protected override string GetSignatureForError ()
1821 return TypeManager.CSharpSignature (definition);
1824 protected override void Report_SymbolRelatedToPreviousError ()
1826 Report.SymbolRelatedToPreviousError (definition);
1830 protected class TypeConstraintChecker : ConstraintChecker
1834 public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
1836 : base (gen_params, atypes, loc)
1841 protected override string GetSignatureForError ()
1843 return TypeManager.CSharpName (gt);
1846 protected override void Report_SymbolRelatedToPreviousError ()
1848 Report.SymbolRelatedToPreviousError (gt);
1854 /// A generic method definition.
1856 public class GenericMethod : DeclSpace
1858 Expression return_type;
1859 Parameters parameters;
1861 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
1862 Expression return_type, Parameters parameters)
1863 : base (ns, parent, name, null)
1865 this.return_type = return_type;
1866 this.parameters = parameters;
1869 public override TypeBuilder DefineType ()
1871 throw new Exception ();
1874 public override bool Define ()
1876 for (int i = 0; i < TypeParameters.Length; i++)
1877 if (!TypeParameters [i].Resolve (this))
1884 /// Define and resolve the type parameters.
1885 /// We're called from Method.Define().
1887 public bool Define (MethodBuilder mb, ToplevelBlock block)
1889 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1890 string[] snames = new string [names.Length];
1891 for (int i = 0; i < names.Length; i++) {
1892 string type_argument_name = names[i].Name;
1893 Parameter p = parameters.GetParameterByName (type_argument_name);
1895 Error_ParameterNameCollision (p.Location, type_argument_name, "method parameter");
1899 snames[i] = type_argument_name;
1902 GenericTypeParameterBuilder[] gen_params = mb.DefineGenericParameters (snames);
1903 for (int i = 0; i < TypeParameters.Length; i++)
1904 TypeParameters [i].Define (gen_params [i]);
1909 for (int i = 0; i < TypeParameters.Length; i++) {
1910 if (!TypeParameters [i].ResolveType (this))
1917 internal static void Error_ParameterNameCollision (Location loc, string name, string collisionWith)
1919 Report.Error (412, loc, "The type parameter name `{0}' is the same as `{1}'",
1920 name, collisionWith);
1924 /// We're called from MethodData.Define() after creating the MethodBuilder.
1926 public bool DefineType (EmitContext ec, MethodBuilder mb,
1927 MethodInfo implementing, bool is_override)
1929 for (int i = 0; i < TypeParameters.Length; i++)
1930 if (!TypeParameters [i].DefineType (
1931 ec, mb, implementing, is_override))
1935 foreach (Parameter p in parameters.FixedParameters){
1936 if (!p.Resolve (ec))
1939 if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec, false) == null))
1945 public void EmitAttributes ()
1947 for (int i = 0; i < TypeParameters.Length; i++)
1948 TypeParameters [i].Emit ();
1950 if (OptAttributes != null)
1951 OptAttributes.Emit ();
1954 public override bool DefineMembers ()
1959 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1960 MemberFilter filter, object criteria)
1962 throw new Exception ();
1965 public override MemberCache MemberCache {
1971 public override AttributeTargets AttributeTargets {
1973 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1977 public override string DocCommentHeader {
1978 get { return "M:"; }
1981 public new void VerifyClsCompliance ()
1983 foreach (TypeParameter tp in TypeParameters) {
1984 if (tp.Constraints == null)
1987 tp.Constraints.VerifyClsCompliance ();
1992 public class NullableType : TypeExpr
1994 Expression underlying;
1996 public NullableType (Expression underlying, Location l)
1998 this.underlying = underlying;
2001 eclass = ExprClass.Type;
2004 public NullableType (Type type, Location loc)
2005 : this (new TypeExpression (type, loc), loc)
2008 public override string Name {
2009 get { return underlying.ToString () + "?"; }
2012 public override string FullName {
2013 get { return underlying.ToString () + "?"; }
2016 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
2018 TypeArguments args = new TypeArguments (loc);
2019 args.Add (underlying);
2021 ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
2022 return ctype.ResolveAsTypeTerminal (ec, false);
2026 public partial class TypeManager
2029 // A list of core types that the compiler requires or uses
2031 static public Type activator_type;
2032 static public Type generic_ilist_type;
2033 static public Type generic_icollection_type;
2034 static public Type generic_ienumerator_type;
2035 static public Type generic_ienumerable_type;
2036 static public Type generic_nullable_type;
2039 // These methods are called by code generated by the compiler
2041 static public MethodInfo activator_create_instance;
2043 static void InitGenericCoreTypes ()
2045 activator_type = CoreLookupType ("System", "Activator");
2047 generic_ilist_type = CoreLookupType (
2048 "System.Collections.Generic", "IList", 1);
2049 generic_icollection_type = CoreLookupType (
2050 "System.Collections.Generic", "ICollection", 1);
2051 generic_ienumerator_type = CoreLookupType (
2052 "System.Collections.Generic", "IEnumerator", 1);
2053 generic_ienumerable_type = CoreLookupType (
2054 "System.Collections.Generic", "IEnumerable", 1);
2055 generic_nullable_type = CoreLookupType (
2056 "System", "Nullable", 1);
2059 static void InitGenericCodeHelpers ()
2062 activator_create_instance = GetCoreMethod (
2063 activator_type, "CreateInstance", Type.EmptyTypes);
2066 static Type CoreLookupType (string ns, string name, int arity)
2068 return CoreLookupType (ns, MemberName.MakeName (name, arity));
2071 public static TypeContainer LookupGenericTypeContainer (Type t)
2073 t = DropGenericTypeArguments (t);
2074 return LookupTypeContainer (t);
2078 /// Check whether `a' and `b' may become equal generic types.
2079 /// The algorithm to do that is a little bit complicated.
2081 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_inferred,
2082 Type[] method_inferred)
2084 if (a.IsGenericParameter) {
2086 // If a is an array of a's type, they may never
2090 b = b.GetElementType ();
2096 // If b is a generic parameter or an actual type,
2097 // they may become equal:
2099 // class X<T,U> : I<T>, I<U>
2100 // class X<T> : I<T>, I<float>
2102 if (b.IsGenericParameter || !b.IsGenericType) {
2103 int pos = a.GenericParameterPosition;
2104 Type[] args = a.DeclaringMethod != null ? method_inferred : class_inferred;
2105 if (args [pos] == null) {
2110 return args [pos] == a;
2114 // We're now comparing a type parameter with a
2115 // generic instance. They may become equal unless
2116 // the type parameter appears anywhere in the
2117 // generic instance:
2119 // class X<T,U> : I<T>, I<X<U>>
2120 // -> error because you could instanciate it as
2123 // class X<T> : I<T>, I<X<T>> -> ok
2126 Type[] bargs = GetTypeArguments (b);
2127 for (int i = 0; i < bargs.Length; i++) {
2128 if (a.Equals (bargs [i]))
2135 if (b.IsGenericParameter)
2136 return MayBecomeEqualGenericTypes (b, a, class_inferred, method_inferred);
2139 // At this point, neither a nor b are a type parameter.
2141 // If one of them is a generic instance, let
2142 // MayBecomeEqualGenericInstances() compare them (if the
2143 // other one is not a generic instance, they can never
2147 if (a.IsGenericType || b.IsGenericType)
2148 return MayBecomeEqualGenericInstances (a, b, class_inferred, method_inferred);
2151 // If both of them are arrays.
2154 if (a.IsArray && b.IsArray) {
2155 if (a.GetArrayRank () != b.GetArrayRank ())
2158 a = a.GetElementType ();
2159 b = b.GetElementType ();
2161 return MayBecomeEqualGenericTypes (a, b, class_inferred, method_inferred);
2165 // Ok, two ordinary types.
2168 return a.Equals (b);
2172 // Checks whether two generic instances may become equal for some
2173 // particular instantiation (26.3.1).
2175 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
2176 Type[] class_inferred,
2177 Type[] method_inferred)
2179 if (!a.IsGenericType || !b.IsGenericType)
2181 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2184 return MayBecomeEqualGenericInstances (
2185 GetTypeArguments (a), GetTypeArguments (b), class_inferred, method_inferred);
2188 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
2189 Type[] class_inferred,
2190 Type[] method_inferred)
2192 if (aargs.Length != bargs.Length)
2195 for (int i = 0; i < aargs.Length; i++) {
2196 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_inferred, method_inferred))
2204 /// Type inference. Try to infer the type arguments from `method',
2205 /// which is invoked with the arguments `arguments'. This is used
2206 /// when resolving an Invocation or a DelegateInvocation and the user
2207 /// did not explicitly specify type arguments.
2209 public static int InferTypeArguments (EmitContext ec,
2210 ArrayList arguments,
2211 ref MethodBase method)
2213 ATypeInference ti = ATypeInference.CreateInstance (arguments);
2214 Type[] i_args = ti.InferMethodArguments (ec, method);
2216 return ti.InferenceScore;
2218 if (i_args.Length == 0)
2221 method = ((MethodInfo) method).MakeGenericMethod (i_args);
2228 public static bool InferTypeArguments (ParameterData apd,
2229 ref MethodBase method)
2231 if (!TypeManager.IsGenericMethod (method))
2234 ATypeInference ti = ATypeInference.CreateInstance (ArrayList.Adapter (apd.Types));
2235 Type[] i_args = ti.InferDelegateArguments (method);
2239 method = ((MethodInfo) method).MakeGenericMethod (i_args);
2244 abstract class ATypeInference
2246 protected readonly ArrayList arguments;
2247 protected readonly int arg_count;
2249 protected ATypeInference (ArrayList arguments)
2251 this.arguments = arguments;
2252 if (arguments != null)
2253 arg_count = arguments.Count;
2256 public static ATypeInference CreateInstance (ArrayList arguments)
2258 if (RootContext.Version == LanguageVersion.ISO_2)
2259 return new TypeInferenceV2 (arguments);
2261 return new TypeInferenceV3 (arguments);
2264 public virtual int InferenceScore {
2266 return int.MaxValue;
2270 public abstract Type[] InferMethodArguments (EmitContext ec, MethodBase method);
2271 public abstract Type[] InferDelegateArguments (MethodBase method);
2275 // Implements C# 2.0 type inference
2277 class TypeInferenceV2 : ATypeInference
2279 public TypeInferenceV2 (ArrayList arguments)
2284 public override Type[] InferDelegateArguments (MethodBase method)
2286 ParameterData pd = TypeManager.GetParameterData (method);
2287 if (arg_count != pd.Count)
2290 Type[] method_args = method.GetGenericArguments ();
2291 Type[] inferred_types = new Type[method_args.Length];
2293 Type[] param_types = new Type[pd.Count];
2294 Type[] arg_types = (Type[])arguments.ToArray (typeof (Type));
2296 for (int i = 0; i < arg_count; i++) {
2297 param_types[i] = pd.ParameterType (i);
2300 if (!InferTypeArguments (param_types, arg_types, inferred_types))
2303 return inferred_types;
2306 public override Type[] InferMethodArguments (EmitContext ec, MethodBase method)
2308 ParameterData pd = TypeManager.GetParameterData (method);
2309 Type[] method_generic_args = method.GetGenericArguments ();
2310 Type [] inferred_types = new Type [method_generic_args.Length];
2311 Type[] arg_types = new Type [pd.Count];
2313 int a_count = arg_types.Length;
2317 for (int i = 0; i < a_count; i++) {
2318 Argument a = (Argument) arguments[i];
2319 if (a.Expr is NullLiteral || a.Expr is MethodGroupExpr || a.Expr is AnonymousMethodExpression)
2322 if (!TypeInferenceV2.UnifyType (pd.ParameterType (i), a.Type, inferred_types))
2327 Type element_type = TypeManager.GetElementType (pd.ParameterType (a_count));
2328 for (int i = a_count; i < arg_count; i++) {
2329 Argument a = (Argument) arguments [i];
2330 if (a.Expr is NullLiteral || a.Expr is MethodGroupExpr || a.Expr is AnonymousMethodExpression)
2333 if (!TypeInferenceV2.UnifyType (element_type, a.Type, inferred_types))
2338 for (int i = 0; i < inferred_types.Length; i++)
2339 if (inferred_types [i] == null)
2342 return inferred_types;
2345 static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
2346 Type[] inferred_types)
2348 for (int i = 0; i < arg_types.Length; i++) {
2349 if (arg_types[i] == null)
2352 if (!UnifyType (param_types[i], arg_types[i], inferred_types))
2356 for (int i = 0; i < inferred_types.Length; ++i)
2357 if (inferred_types[i] == null)
2363 public static bool UnifyType (Type pt, Type at, Type[] inferred)
2365 if (pt.IsGenericParameter) {
2366 if (pt.DeclaringMethod == null)
2369 int pos = pt.GenericParameterPosition;
2371 if (inferred [pos] == null)
2372 inferred [pos] = at;
2374 return inferred [pos] == at;
2377 if (!pt.ContainsGenericParameters) {
2378 if (at.ContainsGenericParameters)
2379 return UnifyType (at, pt, inferred);
2386 if (at.GetArrayRank () != pt.GetArrayRank ())
2389 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2392 if (!pt.IsGenericType)
2395 Type gt = pt.GetGenericTypeDefinition ();
2396 if ((gt != TypeManager.generic_ilist_type) && (gt != TypeManager.generic_icollection_type) &&
2397 (gt != TypeManager.generic_ienumerable_type))
2400 Type[] args = TypeManager.GetTypeArguments (pt);
2401 return UnifyType (args[0], at.GetElementType (), inferred);
2406 (pt.GetArrayRank () != at.GetArrayRank ()))
2409 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2412 if (pt.IsByRef && at.IsByRef)
2413 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2414 ArrayList list = new ArrayList ();
2415 if (at.IsGenericType)
2417 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
2420 list.AddRange (TypeManager.GetInterfaces (at));
2422 foreach (Type type in list) {
2423 if (!type.IsGenericType)
2426 if (TypeManager.DropGenericTypeArguments (pt) != TypeManager.DropGenericTypeArguments (type))
2429 if (!UnifyTypes (pt.GetGenericArguments (), type.GetGenericArguments (), inferred))
2436 static bool UnifyTypes (Type[] pts, Type[] ats, Type[] inferred)
2438 for (int i = 0; i < ats.Length; i++) {
2439 if (!UnifyType (pts [i], ats [i], inferred))
2447 // Implements C# 3.0 type inference
2449 class TypeInferenceV3 : ATypeInference
2452 // Tracks successful rate of type inference
2454 int score = int.MaxValue;
2456 public TypeInferenceV3 (ArrayList arguments)
2461 public override int InferenceScore {
2467 public override Type[] InferDelegateArguments (MethodBase method)
2469 ParameterData pd = TypeManager.GetParameterData (method);
2470 if (arg_count != pd.Count)
2473 Type[] d_gargs = method.GetGenericArguments ();
2474 TypeInferenceContext context = new TypeInferenceContext (d_gargs);
2476 // A lower-bound inference is made from each argument type Uj of D
2477 // to the corresponding parameter type Tj of M
2478 for (int i = 0; i < arg_count; ++i) {
2479 Type t = pd.Types [i];
2480 if (!t.IsGenericParameter)
2483 context.LowerBoundInference ((Type)arguments[i], t);
2486 if (!context.FixAllTypes ())
2489 return context.InferredTypeArguments;
2492 public override Type[] InferMethodArguments (EmitContext ec, MethodBase method)
2494 Type[] method_generic_args = method.GetGenericArguments ();
2495 TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2496 if (!context.UnfixedVariableExists)
2497 return Type.EmptyTypes;
2499 ParameterData pd = TypeManager.GetParameterData (method);
2500 if (!InferInPhases (ec, context, pd))
2503 return context.InferredTypeArguments;
2507 // Implements method type arguments inference
2509 bool InferInPhases (EmitContext ec, TypeInferenceContext tic, ParameterData methodParameters)
2511 int params_arguments_start;
2512 if (methodParameters.HasParams) {
2513 params_arguments_start = methodParameters.Count - 1;
2515 params_arguments_start = arg_count;
2519 // The first inference phase
2521 Type method_parameter = null;
2522 for (int i = 0; i < arg_count; i++) {
2523 Argument a = (Argument) arguments [i];
2525 if (i < params_arguments_start) {
2526 method_parameter = methodParameters.Types [i];
2527 } else if (i == params_arguments_start) {
2528 if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2529 method_parameter = methodParameters.Types [params_arguments_start];
2531 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2535 // When a lambda expression, an anonymous method
2536 // is used an explicit argument type inference takes a place
2538 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2540 if (am.ExplicitTypeInference (tic, method_parameter))
2545 if (a.Expr.Type == TypeManager.null_type)
2549 // Otherwise an output type inference is made
2551 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2555 // Part of the second phase but because it happens only once
2556 // we don't need to call it in cycle
2558 bool fixed_any = false;
2559 if (!tic.FixIndependentTypeArguments (methodParameters, ref fixed_any))
2562 return DoSecondPhase (ec, tic, methodParameters, !fixed_any);
2565 bool DoSecondPhase (EmitContext ec, TypeInferenceContext tic, ParameterData methodParameters, bool fixDependent)
2567 bool fixed_any = false;
2568 if (fixDependent && !tic.FixDependentTypes (methodParameters, ref fixed_any))
2571 // If no further unfixed type variables exist, type inference succeeds
2572 if (!tic.UnfixedVariableExists)
2575 if (!fixed_any && fixDependent)
2578 // For all arguments where the corresponding argument output types
2579 // contain unfixed type variables but the input types do not,
2580 // an output type inference is made
2581 for (int i = 0; i < arg_count; i++) {
2582 Type t_i = methodParameters.ParameterType (i);
2583 if (!TypeManager.IsDelegateType (t_i)) {
2584 if (TypeManager.DropGenericTypeArguments (t_i) != TypeManager.expression_type)
2587 t_i = t_i.GetGenericArguments () [0];
2590 MethodInfo mi = Delegate.GetInvokeMethod (t_i, t_i);
2591 Type rtype = mi.ReturnType;
2594 // Blablabla, because reflection does not work with dynamic types
2595 Type[] g_args = t_i.GetGenericArguments ();
2596 rtype = g_args[rtype.GenericParameterPosition];
2599 if (tic.IsReturnTypeNonDependent (mi, rtype))
2600 score -= tic.OutputTypeInference (ec, ((Argument) arguments [i]).Expr, t_i);
2604 return DoSecondPhase (ec, tic, methodParameters, true);
2608 public class TypeInferenceContext
2610 readonly Type[] unfixed_types;
2611 readonly Type[] fixed_types;
2612 readonly ArrayList[] bounds;
2614 public TypeInferenceContext (Type[] typeArguments)
2616 if (typeArguments.Length == 0)
2617 throw new ArgumentException ("Empty generic arguments");
2619 fixed_types = new Type [typeArguments.Length];
2620 for (int i = 0; i < typeArguments.Length; ++i) {
2621 if (typeArguments [i].IsGenericParameter) {
2622 if (bounds == null) {
2623 bounds = new ArrayList [typeArguments.Length];
2624 unfixed_types = new Type [typeArguments.Length];
2626 unfixed_types [i] = typeArguments [i];
2628 fixed_types [i] = typeArguments [i];
2633 public Type[] InferredTypeArguments {
2639 void AddToBounds (Type t, int index)
2641 ArrayList a = bounds [index];
2643 a = new ArrayList ();
2651 // SPEC: does not cover type inference using constraints
2653 if (TypeManager.IsGenericParameter (t)) {
2654 GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
2655 if (constraints != null) {
2656 //if (constraints.EffectiveBaseClass != null)
2657 // t = constraints.EffectiveBaseClass;
2663 bool AllTypesAreFixed (Type[] types)
2665 foreach (Type t in types) {
2666 if (t.IsGenericParameter) {
2672 if (t.IsGenericType)
2673 return AllTypesAreFixed (t.GetGenericArguments ());
2680 // 26.3.3.8 Exact Inference
2682 public int ExactInference (Type u, Type v)
2684 // If V is an array type
2689 if (u.GetArrayRank () != v.GetArrayRank ())
2692 return ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
2695 // If V is constructed type and U is constructed type
2696 if (v.IsGenericType && !v.IsGenericTypeDefinition) {
2697 if (!u.IsGenericType)
2700 Type [] ga_u = u.GetGenericArguments ();
2701 Type [] ga_v = v.GetGenericArguments ();
2702 if (ga_u.Length != ga_v.Length)
2706 for (int i = 0; i < ga_u.Length; ++i)
2707 score += ExactInference (ga_u [i], ga_v [i]);
2709 return score > 0 ? 1 : 0;
2712 // If V is one of the unfixed type arguments
2713 int pos = IsUnfixed (v);
2717 AddToBounds (u, pos);
2721 public bool FixAllTypes ()
2723 for (int i = 0; i < unfixed_types.Length; ++i) {
2731 // All unfixed type variables Xi are fixed for which all of the following hold:
2732 // a, There is at least one type variable Xj that depends on Xi
2733 // b, Xi has a non-empty set of bounds
2735 public bool FixDependentTypes (ParameterData methodParameters, ref bool fixed_any)
2737 for (int i = 0; i < unfixed_types.Length; ++i) {
2738 if (unfixed_types[i] == null)
2741 if (bounds[i] == null)
2754 // All unfixed type variables Xi which depend on no Xj are fixed
2756 public bool FixIndependentTypeArguments (ParameterData methodParameters, ref bool fixed_any)
2758 ArrayList types_to_fix = new ArrayList (unfixed_types);
2759 for (int i = 0; i < methodParameters.Types.Length; ++i) {
2760 Type t = methodParameters.Types [i];
2761 if (t.IsGenericParameter)
2764 if (!TypeManager.IsDelegateType (t)) {
2765 if (TypeManager.DropGenericTypeArguments (t) != TypeManager.expression_type)
2768 t = t.GetGenericArguments () [0];
2771 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
2772 Type rtype = invoke.ReturnType;
2773 if (!rtype.IsGenericParameter && !rtype.IsGenericType)
2777 // Blablabla, because reflection does not work with dynamic types
2778 if (rtype.IsGenericParameter) {
2779 Type [] g_args = t.GetGenericArguments ();
2780 rtype = g_args [rtype.GenericParameterPosition];
2783 // Remove dependent types, they cannot be fixed yet
2784 RemoveDependentTypes (types_to_fix, rtype);
2787 foreach (Type t in types_to_fix) {
2791 int idx = IsUnfixed (t);
2792 if (idx >= 0 && !FixType (idx)) {
2797 fixed_any = types_to_fix.Count > 0;
2804 public bool FixType (int i)
2806 // It's already fixed
2807 if (unfixed_types[i] == null)
2808 throw new InternalErrorException ("Type argument has been already fixed");
2810 ArrayList candidates = (ArrayList)bounds [i];
2811 if (candidates == null)
2814 if (candidates.Count == 1) {
2815 unfixed_types[i] = null;
2816 fixed_types[i] = (Type)candidates[0];
2821 // Determines a unique type from which there is
2822 // a standard implicit conversion to all the other
2825 Type best_candidate = null;
2827 int candidates_count = candidates.Count;
2828 for (int ci = 0; ci < candidates_count; ++ci) {
2829 Type candidate = (Type)candidates [ci];
2830 for (cii = 0; cii < candidates_count; ++cii) {
2834 if (!Convert.ImplicitConversionExists (null,
2835 new TypeExpression ((Type)candidates [cii], Location.Null), candidate)) {
2840 if (cii != candidates_count)
2843 if (best_candidate != null)
2846 best_candidate = candidate;
2849 if (best_candidate == null)
2852 unfixed_types[i] = null;
2853 fixed_types[i] = best_candidate;
2858 // Uses inferred types to inflate delegate type argument
2860 public Type InflateGenericArgument (Type parameter)
2862 if (parameter.IsGenericParameter)
2863 return fixed_types [parameter.GenericParameterPosition];
2865 if (parameter.IsGenericType) {
2866 Type [] parameter_targs = parameter.GetGenericArguments ();
2867 for (int ii = 0; ii < parameter_targs.Length; ++ii) {
2868 parameter_targs [ii] = InflateGenericArgument (parameter_targs [ii]);
2870 return parameter.GetGenericTypeDefinition ().MakeGenericType (parameter_targs);
2877 // Tests whether all delegate input arguments are fixed and generic output type
2878 // requires output type inference
2880 public bool IsReturnTypeNonDependent (MethodInfo invoke, Type returnType)
2882 if (returnType.IsGenericParameter) {
2883 if (IsFixed (returnType))
2885 } else if (returnType.IsGenericType) {
2886 if (TypeManager.IsDelegateType (returnType)) {
2887 invoke = Delegate.GetInvokeMethod (returnType, returnType);
2888 return IsReturnTypeNonDependent (invoke, invoke.ReturnType);
2891 Type[] g_args = returnType.GetGenericArguments ();
2893 // At least one unfixed return type has to exist
2894 if (AllTypesAreFixed (g_args))
2900 // All generic input arguments have to be fixed
2901 ParameterData d_parameters = TypeManager.GetParameterData (invoke);
2902 return AllTypesAreFixed (d_parameters.Types);
2905 bool IsFixed (Type type)
2907 return IsUnfixed (type) == -1;
2910 int IsUnfixed (Type type)
2912 if (!type.IsGenericParameter)
2915 //return unfixed_types[type.GenericParameterPosition] != null;
2916 for (int i = 0; i < unfixed_types.Length; ++i) {
2917 if (unfixed_types [i] == type)
2925 // 26.3.3.9 Lower-bound Inference
2927 public int LowerBoundInference (Type u, Type v)
2929 // Remove ref, out modifiers
2931 v = v.GetElementType ();
2933 // If V is one of the unfixed type arguments
2934 int pos = IsUnfixed (v);
2936 AddToBounds (u, pos);
2940 // If U is an array type
2942 int u_dim = u.GetArrayRank ();
2944 Type u_e = TypeManager.GetElementType (u);
2947 if (u_dim != v.GetArrayRank ())
2950 v_e = TypeManager.GetElementType (v);
2953 return LowerBoundInference (u_e, v_e);
2956 return ExactInference (u_e, v_e);
2962 if (v.IsGenericType) {
2963 Type g_v = v.GetGenericTypeDefinition ();
2964 if ((g_v != TypeManager.generic_ilist_type) && (g_v != TypeManager.generic_icollection_type) &&
2965 (g_v != TypeManager.generic_ienumerable_type))
2968 v_e = TypeManager.GetTypeArguments (v)[0];
2971 return LowerBoundInference (u_e, v_e);
2974 return ExactInference (u_e, v_e);
2976 } else if (v.IsGenericType && !v.IsGenericTypeDefinition) {
2978 // if V is a constructed type C<V1..Vk> and there is a unique set of types U1..Uk
2979 // such that a standard implicit conversion exists from U to C<U1..Uk> then an exact
2980 // inference is made from each Ui for the corresponding Vi
2982 ArrayList u_candidates = new ArrayList ();
2983 if (u.IsGenericType)
2984 u_candidates.Add (u);
2986 for (Type t = u.BaseType; t != null; t = t.BaseType) {
2987 if (t.IsGenericType && !t.IsGenericTypeDefinition)
2988 u_candidates.Add (t);
2991 // TODO: Implement GetGenericInterfaces only and remove
2992 // the if from foreach
2993 u_candidates.AddRange (TypeManager.GetInterfaces (u));
2995 Type open_v = v.GetGenericTypeDefinition ();
2997 foreach (Type u_candidate in u_candidates) {
2998 if (!u_candidate.IsGenericType || u_candidate.IsGenericTypeDefinition)
3001 if (TypeManager.DropGenericTypeArguments (u_candidate) != open_v)
3004 Type [] ga_u = u_candidate.GetGenericArguments ();
3005 Type [] ga_v = v.GetGenericArguments ();
3006 bool all_exact = true;
3007 for (int i = 0; i < ga_u.Length; ++i)
3008 if (ExactInference (ga_u [i], ga_v [i]) == 0)
3011 if (all_exact && score == 0)
3021 // 26.3.3.6 Output Type Inference
3023 public int OutputTypeInference (EmitContext ec, Expression e, Type t)
3025 // If e is a lambda or anonymous method with inferred return type
3026 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
3028 Type rt = ame.InferReturnType (ec, this, t);
3029 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
3032 ParameterData pd = TypeManager.GetParameterData (invoke);
3033 return ame.Parameters.Count == pd.Count ? 1 : 0;
3036 Type rtype = invoke.ReturnType;
3038 // Blablabla, because reflection does not work with dynamic types
3039 Type [] g_args = t.GetGenericArguments ();
3040 rtype = g_args [rtype.GenericParameterPosition];
3042 return LowerBoundInference (rt, rtype) + 1;
3045 if (e is MethodGroupExpr) {
3046 if (!TypeManager.IsDelegateType (t))
3049 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
3050 Type rtype = invoke.ReturnType;
3051 if (!TypeManager.IsGenericType (rtype))
3054 throw new NotImplementedException ();
3058 // if e is an expression with type U, then
3059 // a lower-bound inference is made from U for T
3061 return LowerBoundInference (e.Type, t) * 2;
3064 static void RemoveDependentTypes (ArrayList types, Type returnType)
3066 if (returnType.IsGenericParameter) {
3067 types [returnType.GenericParameterPosition] = null;
3071 if (returnType.IsGenericType) {
3072 foreach (Type t in returnType.GetGenericArguments ()) {
3073 RemoveDependentTypes (types, t);
3078 public bool UnfixedVariableExists {
3080 if (unfixed_types == null)
3083 foreach (Type ut in unfixed_types)
3091 public abstract class Nullable
3093 public sealed class NullableInfo
3095 public readonly Type Type;
3096 public readonly Type UnderlyingType;
3097 public readonly MethodInfo HasValue;
3098 public readonly MethodInfo Value;
3099 public readonly ConstructorInfo Constructor;
3101 public NullableInfo (Type type)
3104 UnderlyingType = TypeManager.GetTypeArguments (type) [0];
3106 PropertyInfo has_value_pi = TypeManager.GetCoreProperty (type, "HasValue");
3107 PropertyInfo value_pi = TypeManager.GetCoreProperty (type, "Value");
3109 HasValue = has_value_pi.GetGetMethod (false);
3110 Value = value_pi.GetGetMethod (false);
3111 Constructor = type.GetConstructor (new Type[] { UnderlyingType });
3115 public class HasValue : Expression
3120 private HasValue (Expression expr)
3125 public static Expression Create (Expression expr, EmitContext ec)
3127 return new HasValue (expr).Resolve (ec);
3130 public override void Emit (EmitContext ec)
3132 IMemoryLocation memory_loc = expr as IMemoryLocation;
3133 if (memory_loc == null) {
3134 LocalTemporary temp = new LocalTemporary (expr.Type);
3139 memory_loc.AddressOf (ec, AddressOp.LoadStore);
3140 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
3143 public override Expression DoResolve (EmitContext ec)
3145 this.info = new NullableInfo (expr.Type);
3147 type = TypeManager.bool_type;
3148 eclass = expr.eclass;
3153 public class Unwrap : Expression, IMemoryLocation, IAssignMethod
3158 LocalTemporary temp;
3161 protected Unwrap (Expression expr)
3164 this.loc = expr.Location;
3167 public static Unwrap Create (Expression expr, EmitContext ec)
3169 return new Unwrap (expr).Resolve (ec) as Unwrap;
3172 public override Expression CreateExpressionTree (EmitContext ec)
3174 return expr.CreateExpressionTree (ec);
3177 public override Expression DoResolve (EmitContext ec)
3182 temp = new LocalTemporary (expr.Type);
3184 info = new NullableInfo (expr.Type);
3185 type = info.UnderlyingType;
3186 eclass = expr.eclass;
3190 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
3192 return DoResolve (ec);
3195 public override void Emit (EmitContext ec)
3197 AddressOf (ec, AddressOp.LoadStore);
3198 ec.ig.EmitCall (OpCodes.Call, info.Value, null);
3201 public void EmitCheck (EmitContext ec)
3203 AddressOf (ec, AddressOp.LoadStore);
3204 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
3207 public override bool IsNull {
3213 public void Store (EmitContext ec)
3218 void create_temp (EmitContext ec)
3220 if ((temp != null) && !has_temp) {
3227 public void AddressOf (EmitContext ec, AddressOp mode)
3231 temp.AddressOf (ec, AddressOp.LoadStore);
3233 ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
3236 public void Emit (EmitContext ec, bool leave_copy)
3249 public void EmitAssign (EmitContext ec, Expression source,
3250 bool leave_copy, bool prepare_for_load)
3252 InternalWrap wrap = new InternalWrap (source, info, loc);
3253 ((IAssignMethod) expr).EmitAssign (ec, wrap, leave_copy, false);
3256 protected class InternalWrap : Expression
3258 public Expression expr;
3259 public NullableInfo info;
3261 public InternalWrap (Expression expr, NullableInfo info, Location loc)
3268 eclass = ExprClass.Value;
3271 public override Expression DoResolve (EmitContext ec)
3276 public override void Emit (EmitContext ec)
3279 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
3284 public class Wrap : Expression
3289 protected Wrap (Expression expr)
3292 this.loc = expr.Location;
3295 public static Wrap Create (Expression expr, EmitContext ec)
3297 return new Wrap (expr).Resolve (ec) as Wrap;
3300 public override Expression CreateExpressionTree (EmitContext ec)
3302 ArrayList args = new ArrayList (2);
3303 args.Add (new Argument (expr.CreateExpressionTree (ec)));
3304 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
3305 return CreateExpressionFactoryCall ("Convert", args);
3308 public override Expression DoResolve (EmitContext ec)
3313 TypeExpr target_type = new NullableType (expr.Type, loc);
3314 target_type = target_type.ResolveAsTypeTerminal (ec, false);
3315 if (target_type == null)
3318 type = target_type.Type;
3319 info = new NullableInfo (type);
3320 eclass = ExprClass.Value;
3324 public override void Emit (EmitContext ec)
3327 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
3332 // Represents null value converted to nullable type
3334 public class Null : Expression, IMemoryLocation
3336 public Null (Type target_type, Location loc)
3338 this.type = target_type;
3341 eclass = ExprClass.Value;
3344 public override Expression CreateExpressionTree (EmitContext ec)
3346 return EmptyCast.Create (new NullConstant (loc), type).CreateExpressionTree (ec);
3349 public override Expression DoResolve (EmitContext ec)
3354 public override void Emit (EmitContext ec)
3356 LocalTemporary value_target = new LocalTemporary (type);
3358 value_target.AddressOf (ec, AddressOp.Store);
3359 ec.ig.Emit (OpCodes.Initobj, type);
3360 value_target.Emit (ec);
3363 public override bool IsNull {
3369 public void AddressOf (EmitContext ec, AddressOp Mode)
3371 LocalTemporary value_target = new LocalTemporary (type);
3373 value_target.AddressOf (ec, AddressOp.Store);
3374 ec.ig.Emit (OpCodes.Initobj, type);
3375 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
3379 public abstract class Lifted : Expression, IMemoryLocation
3381 Expression expr, underlying, wrap, null_value;
3384 protected Lifted (Expression expr, Location loc)
3390 public override Expression CreateExpressionTree (EmitContext ec)
3392 return expr.CreateExpressionTree (ec);
3395 public override Expression DoResolve (EmitContext ec)
3397 expr = expr.Resolve (ec);
3401 unwrap = Unwrap.Create (expr, ec);
3405 underlying = ResolveUnderlying (unwrap, ec);
3406 if (underlying == null)
3409 wrap = Wrap.Create (underlying, ec);
3413 null_value = new Null (wrap.Type, loc).Resolve (ec);
3414 if (null_value == null)
3418 eclass = ExprClass.Value;
3422 protected abstract Expression ResolveUnderlying (Expression unwrap, EmitContext ec);
3424 public override void Emit (EmitContext ec)
3426 ILGenerator ig = ec.ig;
3427 Label is_null_label = ig.DefineLabel ();
3428 Label end_label = ig.DefineLabel ();
3430 unwrap.EmitCheck (ec);
3431 ig.Emit (OpCodes.Brfalse, is_null_label);
3434 ig.Emit (OpCodes.Br, end_label);
3436 ig.MarkLabel (is_null_label);
3437 null_value.Emit (ec);
3439 ig.MarkLabel (end_label);
3442 public void AddressOf (EmitContext ec, AddressOp mode)
3444 unwrap.AddressOf (ec, mode);
3448 public class LiftedConversion : Lifted
3450 public readonly bool IsUser;
3451 public readonly bool IsExplicit;
3452 public readonly Type TargetType;
3454 public LiftedConversion (Expression expr, Type target_type, bool is_user,
3455 bool is_explicit, Location loc)
3458 this.IsUser = is_user;
3459 this.IsExplicit = is_explicit;
3460 this.TargetType = target_type;
3463 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
3465 Type type = TypeManager.GetTypeArguments (TargetType) [0];
3468 return Convert.UserDefinedConversion (ec, unwrap, type, loc, IsExplicit);
3471 return Convert.ExplicitConversion (ec, unwrap, type, loc);
3473 return Convert.ImplicitConversion (ec, unwrap, type, loc);
3478 public class LiftedUnaryOperator : Lifted
3480 public readonly Unary.Operator Oper;
3482 public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
3488 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
3490 return new Unary (Oper, unwrap, loc).Resolve (ec);
3494 public class LiftedBinaryOperator : Binary
3496 Expression underlying, null_value, bool_wrap;
3497 Unwrap left_unwrap, right_unwrap;
3498 bool is_equality, is_comparision, is_boolean;
3500 public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
3502 : base (op, left, right)
3507 public override Expression DoResolve (EmitContext ec)
3509 if ((Oper == Binary.Operator.LogicalAnd) ||
3510 (Oper == Binary.Operator.LogicalOr)) {
3511 Error_OperatorCannotBeApplied ();
3516 // Optimize null comparisons
3518 if (Oper == Binary.Operator.Equality) {
3520 return new Unary (Unary.Operator.LogicalNot, Nullable.HasValue.Create (right, ec), loc).Resolve (ec);
3522 return new Unary (Unary.Operator.LogicalNot, Nullable.HasValue.Create (left, ec), loc).Resolve (ec);
3524 if (Oper == Binary.Operator.Inequality) {
3526 return Nullable.HasValue.Create (right, ec);
3528 return Nullable.HasValue.Create (left, ec);
3531 if (TypeManager.IsNullableType (left.Type)) {
3532 left = left_unwrap = Unwrap.Create (left, ec);
3537 if (TypeManager.IsNullableType (right.Type)) {
3538 right = right_unwrap = Unwrap.Create (right, ec);
3543 if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr)) &&
3544 ((left.Type == TypeManager.bool_type) && (right.Type == TypeManager.bool_type))) {
3545 Expression empty = new EmptyExpression (TypeManager.bool_type);
3546 bool_wrap = Wrap.Create (empty, ec);
3547 null_value = new Null (bool_wrap.Type, loc).Resolve (ec);
3549 type = bool_wrap.Type;
3551 } else if ((Oper == Binary.Operator.Equality) || (Oper == Binary.Operator.Inequality)) {
3552 underlying = new Binary (Oper, left, right).Resolve (ec);
3553 if (underlying == null)
3555 type = TypeManager.bool_type;
3557 } else if ((Oper == Binary.Operator.LessThan) ||
3558 (Oper == Binary.Operator.GreaterThan) ||
3559 (Oper == Binary.Operator.LessThanOrEqual) ||
3560 (Oper == Binary.Operator.GreaterThanOrEqual)) {
3561 underlying = new Binary (Oper, left, right).Resolve (ec);
3562 if (underlying == null)
3565 type = TypeManager.bool_type;
3566 is_comparision = true;
3568 underlying = new Binary (Oper, left, right).Resolve (ec);
3569 if (underlying == null)
3572 underlying = Wrap.Create (underlying, ec);
3573 if (underlying == null)
3576 type = underlying.Type;
3577 null_value = new Null (type, loc).Resolve (ec);
3580 eclass = ExprClass.Value;
3584 void EmitBoolean (EmitContext ec)
3586 ILGenerator ig = ec.ig;
3588 Label left_is_null_label = ig.DefineLabel ();
3589 Label right_is_null_label = ig.DefineLabel ();
3590 Label is_null_label = ig.DefineLabel ();
3591 Label wrap_label = ig.DefineLabel ();
3592 Label end_label = ig.DefineLabel ();
3594 if (left_unwrap != null) {
3595 left_unwrap.EmitCheck (ec);
3596 ig.Emit (OpCodes.Brfalse, left_is_null_label);
3600 ig.Emit (OpCodes.Dup);
3601 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3602 ig.Emit (OpCodes.Brtrue, wrap_label);
3604 ig.Emit (OpCodes.Brfalse, wrap_label);
3606 if (right_unwrap != null) {
3607 right_unwrap.EmitCheck (ec);
3608 ig.Emit (OpCodes.Brfalse, right_is_null_label);
3611 if ((Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr))
3612 ig.Emit (OpCodes.Pop);
3615 if (Oper == Binary.Operator.BitwiseOr)
3616 ig.Emit (OpCodes.Or);
3617 else if (Oper == Binary.Operator.BitwiseAnd)
3618 ig.Emit (OpCodes.And);
3619 ig.Emit (OpCodes.Br, wrap_label);
3621 ig.MarkLabel (left_is_null_label);
3622 if (right_unwrap != null) {
3623 right_unwrap.EmitCheck (ec);
3624 ig.Emit (OpCodes.Brfalse, is_null_label);
3628 ig.Emit (OpCodes.Dup);
3629 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3630 ig.Emit (OpCodes.Brtrue, wrap_label);
3632 ig.Emit (OpCodes.Brfalse, wrap_label);
3634 ig.MarkLabel (right_is_null_label);
3635 ig.Emit (OpCodes.Pop);
3636 ig.MarkLabel (is_null_label);
3637 null_value.Emit (ec);
3638 ig.Emit (OpCodes.Br, end_label);
3640 ig.MarkLabel (wrap_label);
3641 ig.Emit (OpCodes.Nop);
3642 bool_wrap.Emit (ec);
3643 ig.Emit (OpCodes.Nop);
3645 ig.MarkLabel (end_label);
3648 void EmitEquality (EmitContext ec)
3650 if (left.IsNull || right.IsNull)
3651 throw new InternalErrorException ("Unoptimized nullable comparison");
3653 ILGenerator ig = ec.ig;
3655 Label both_have_value_label = ig.DefineLabel ();
3656 Label end_label = ig.DefineLabel ();
3658 if (left_unwrap != null && right_unwrap != null) {
3659 Label dissimilar_label = ig.DefineLabel ();
3661 left_unwrap.EmitCheck (ec);
3662 ig.Emit (OpCodes.Dup);
3663 right_unwrap.EmitCheck (ec);
3664 ig.Emit (OpCodes.Bne_Un, dissimilar_label);
3666 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3669 if (Oper == Binary.Operator.Equality)
3670 ig.Emit (OpCodes.Ldc_I4_1);
3672 ig.Emit (OpCodes.Ldc_I4_0);
3673 ig.Emit (OpCodes.Br, end_label);
3675 ig.MarkLabel (dissimilar_label);
3676 ig.Emit (OpCodes.Pop);
3677 } else if (left_unwrap != null) {
3678 left_unwrap.EmitCheck (ec);
3679 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3680 } else if (right_unwrap != null) {
3681 right_unwrap.EmitCheck (ec);
3682 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3684 throw new InternalErrorException ("shouldn't get here");
3687 // one is null while the other isn't
3688 if (Oper == Binary.Operator.Equality)
3689 ig.Emit (OpCodes.Ldc_I4_0);
3691 ig.Emit (OpCodes.Ldc_I4_1);
3692 ig.Emit (OpCodes.Br, end_label);
3694 ig.MarkLabel (both_have_value_label);
3695 underlying.Emit (ec);
3697 ig.MarkLabel (end_label);
3700 void EmitComparision (EmitContext ec)
3702 ILGenerator ig = ec.ig;
3704 Label is_null_label = ig.DefineLabel ();
3705 Label end_label = ig.DefineLabel ();
3707 if (left_unwrap != null) {
3708 left_unwrap.EmitCheck (ec);
3709 ig.Emit (OpCodes.Brfalse, is_null_label);
3712 if (right_unwrap != null) {
3713 right_unwrap.EmitCheck (ec);
3714 ig.Emit (OpCodes.Brfalse, is_null_label);
3717 underlying.Emit (ec);
3718 ig.Emit (OpCodes.Br, end_label);
3720 ig.MarkLabel (is_null_label);
3721 ig.Emit (OpCodes.Ldc_I4_0);
3723 ig.MarkLabel (end_label);
3726 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
3729 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
3732 public override void Emit (EmitContext ec)
3734 if (left_unwrap != null)
3735 left_unwrap.Store (ec);
3736 if (right_unwrap != null)
3737 right_unwrap.Store (ec);
3742 } else if (is_equality) {
3745 } else if (is_comparision) {
3746 EmitComparision (ec);
3750 ILGenerator ig = ec.ig;
3752 Label is_null_label = ig.DefineLabel ();
3753 Label end_label = ig.DefineLabel ();
3755 if (left_unwrap != null) {
3756 left_unwrap.EmitCheck (ec);
3757 ig.Emit (OpCodes.Brfalse, is_null_label);
3760 if (right_unwrap != null) {
3761 right_unwrap.EmitCheck (ec);
3762 ig.Emit (OpCodes.Brfalse, is_null_label);
3765 underlying.Emit (ec);
3766 ig.Emit (OpCodes.Br, end_label);
3768 ig.MarkLabel (is_null_label);
3769 null_value.Emit (ec);
3771 ig.MarkLabel (end_label);
3775 public class NullCoalescingOperator : Expression
3777 Expression left, right;
3780 public NullCoalescingOperator (Expression left, Expression right, Location loc)
3787 public override Expression CreateExpressionTree (EmitContext ec)
3789 UserCast uc = left as UserCast;
3790 Expression conversion = null;
3794 ArrayList c_args = new ArrayList (2);
3795 c_args.Add (new Argument (uc.CreateExpressionTree (ec)));
3796 c_args.Add (new Argument (left.CreateExpressionTree (ec)));
3797 conversion = CreateExpressionFactoryCall ("Lambda", c_args);
3800 ArrayList args = new ArrayList (3);
3801 args.Add (new Argument (left.CreateExpressionTree (ec)));
3802 args.Add (new Argument (right.CreateExpressionTree (ec)));
3803 if (conversion != null)
3804 args.Add (new Argument (conversion));
3806 return CreateExpressionFactoryCall ("Coalesce", args);
3809 public override Expression DoResolve (EmitContext ec)
3814 left = left.Resolve (ec);
3815 right = right.Resolve (ec);
3817 if (left == null || right == null)
3820 eclass = ExprClass.Value;
3821 Type ltype = left.Type, rtype = right.Type;
3824 if (TypeManager.IsNullableType (ltype)) {
3825 NullableInfo info = new NullableInfo (ltype);
3827 unwrap = Unwrap.Create (left, ec);
3831 expr = Convert.ImplicitConversion (ec, right, info.UnderlyingType, loc);
3838 } else if (!TypeManager.IsReferenceType (ltype)) {
3839 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3843 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
3850 Expression left_null = unwrap != null ? unwrap : left;
3851 expr = Convert.ImplicitConversion (ec, left_null, rtype, loc);
3858 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3862 public override void Emit (EmitContext ec)
3864 ILGenerator ig = ec.ig;
3866 Label is_null_label = ig.DefineLabel ();
3867 Label end_label = ig.DefineLabel ();
3869 if (unwrap != null) {
3870 unwrap.EmitCheck (ec);
3871 ig.Emit (OpCodes.Brfalse, is_null_label);
3874 ig.Emit (OpCodes.Br, end_label);
3876 ig.MarkLabel (is_null_label);
3879 ig.MarkLabel (end_label);
3882 ig.Emit (OpCodes.Dup);
3883 ig.Emit (OpCodes.Brtrue, end_label);
3885 ig.MarkLabel (is_null_label);
3887 ig.Emit (OpCodes.Pop);
3890 ig.MarkLabel (end_label);
3893 protected override void CloneTo (CloneContext clonectx, Expression t)
3895 NullCoalescingOperator target = (NullCoalescingOperator) t;
3897 target.left = left.Clone (clonectx);
3898 target.right = right.Clone (clonectx);
3902 public class LiftedUnaryMutator : ExpressionStatement
3904 public readonly UnaryMutator.Mode Mode;
3905 Expression expr, null_value;
3906 UnaryMutator underlying;
3909 public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
3915 eclass = ExprClass.Value;
3918 public override Expression DoResolve (EmitContext ec)
3920 expr = expr.Resolve (ec);
3924 unwrap = Unwrap.Create (expr, ec);
3928 underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
3929 if (underlying == null)
3932 null_value = new Null (expr.Type, loc).Resolve (ec);
3933 if (null_value == null)
3940 void DoEmit (EmitContext ec, bool is_expr)
3942 ILGenerator ig = ec.ig;
3943 Label is_null_label = ig.DefineLabel ();
3944 Label end_label = ig.DefineLabel ();
3946 unwrap.EmitCheck (ec);
3947 ig.Emit (OpCodes.Brfalse, is_null_label);
3950 underlying.Emit (ec);
3952 underlying.EmitStatement (ec);
3953 ig.Emit (OpCodes.Br, end_label);
3955 ig.MarkLabel (is_null_label);
3957 null_value.Emit (ec);
3959 ig.MarkLabel (end_label);
3962 public override void Emit (EmitContext ec)
3967 public override void EmitStatement (EmitContext ec)