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 return FindMembers (mt, bf, null, null);
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 MemberList list = TypeManager.FindMembers (
1760 atype, MemberTypes.Constructor,
1761 BindingFlags.Public | BindingFlags.Instance |
1762 BindingFlags.DeclaredOnly, null, null);
1764 if (atype.IsAbstract || (list == null))
1767 foreach (MethodBase mb in list) {
1768 ParameterData pd = TypeManager.GetParameterData (mb);
1769 if ((pd.Count == 0) && mb.IsPublic && !mb.IsStatic)
1776 protected abstract string GetSignatureForError ();
1777 protected abstract void Report_SymbolRelatedToPreviousError ();
1779 void Error_TypeMustBeConvertible (Type atype, Type gc, Type ptype)
1781 Report_SymbolRelatedToPreviousError ();
1782 Report.SymbolRelatedToPreviousError (atype);
1783 Report.Error (309, loc,
1784 "The type `{0}' must be convertible to `{1}' in order to " +
1785 "use it as parameter `{2}' in the generic type or method `{3}'",
1786 TypeManager.CSharpName (atype), TypeManager.CSharpName (gc),
1787 TypeManager.CSharpName (ptype), GetSignatureForError ());
1790 public static bool CheckConstraints (EmitContext ec, MethodBase definition,
1791 MethodBase instantiated, Location loc)
1793 MethodConstraintChecker checker = new MethodConstraintChecker (
1794 definition, definition.GetGenericArguments (),
1795 instantiated.GetGenericArguments (), loc);
1797 return checker.CheckConstraints (ec);
1800 public static bool CheckConstraints (IResolveContext ec, Type gt, Type[] gen_params,
1801 Type[] atypes, Location loc)
1803 TypeConstraintChecker checker = new TypeConstraintChecker (
1804 gt, gen_params, atypes, loc);
1806 return checker.CheckConstraints (ec);
1809 protected class MethodConstraintChecker : ConstraintChecker
1811 MethodBase definition;
1813 public MethodConstraintChecker (MethodBase definition, Type[] gen_params,
1814 Type[] atypes, Location loc)
1815 : base (gen_params, atypes, loc)
1817 this.definition = definition;
1820 protected override string GetSignatureForError ()
1822 return TypeManager.CSharpSignature (definition);
1825 protected override void Report_SymbolRelatedToPreviousError ()
1827 Report.SymbolRelatedToPreviousError (definition);
1831 protected class TypeConstraintChecker : ConstraintChecker
1835 public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
1837 : base (gen_params, atypes, loc)
1842 protected override string GetSignatureForError ()
1844 return TypeManager.CSharpName (gt);
1847 protected override void Report_SymbolRelatedToPreviousError ()
1849 Report.SymbolRelatedToPreviousError (gt);
1855 /// A generic method definition.
1857 public class GenericMethod : DeclSpace
1859 Expression return_type;
1860 Parameters parameters;
1862 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
1863 Expression return_type, Parameters parameters)
1864 : base (ns, parent, name, null)
1866 this.return_type = return_type;
1867 this.parameters = parameters;
1870 public override TypeBuilder DefineType ()
1872 throw new Exception ();
1875 public override bool Define ()
1877 for (int i = 0; i < TypeParameters.Length; i++)
1878 if (!TypeParameters [i].Resolve (this))
1885 /// Define and resolve the type parameters.
1886 /// We're called from Method.Define().
1888 public bool Define (MethodBuilder mb, ToplevelBlock block)
1890 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1891 string[] snames = new string [names.Length];
1892 for (int i = 0; i < names.Length; i++) {
1893 string type_argument_name = names[i].Name;
1894 Parameter p = parameters.GetParameterByName (type_argument_name);
1896 Error_ParameterNameCollision (p.Location, type_argument_name, "method parameter");
1900 snames[i] = type_argument_name;
1903 GenericTypeParameterBuilder[] gen_params = mb.DefineGenericParameters (snames);
1904 for (int i = 0; i < TypeParameters.Length; i++)
1905 TypeParameters [i].Define (gen_params [i]);
1910 for (int i = 0; i < TypeParameters.Length; i++) {
1911 if (!TypeParameters [i].ResolveType (this))
1918 internal static void Error_ParameterNameCollision (Location loc, string name, string collisionWith)
1920 Report.Error (412, loc, "The type parameter name `{0}' is the same as `{1}'",
1921 name, collisionWith);
1925 /// We're called from MethodData.Define() after creating the MethodBuilder.
1927 public bool DefineType (EmitContext ec, MethodBuilder mb,
1928 MethodInfo implementing, bool is_override)
1930 for (int i = 0; i < TypeParameters.Length; i++)
1931 if (!TypeParameters [i].DefineType (
1932 ec, mb, implementing, is_override))
1936 foreach (Parameter p in parameters.FixedParameters){
1937 if (!p.Resolve (ec))
1940 if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec, false) == null))
1946 public void EmitAttributes ()
1948 for (int i = 0; i < TypeParameters.Length; i++)
1949 TypeParameters [i].Emit ();
1951 if (OptAttributes != null)
1952 OptAttributes.Emit ();
1955 public override bool DefineMembers ()
1960 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1961 MemberFilter filter, object criteria)
1963 throw new Exception ();
1966 public override MemberCache MemberCache {
1972 public override AttributeTargets AttributeTargets {
1974 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1978 public override string DocCommentHeader {
1979 get { return "M:"; }
1982 public new void VerifyClsCompliance ()
1984 foreach (TypeParameter tp in TypeParameters) {
1985 if (tp.Constraints == null)
1988 tp.Constraints.VerifyClsCompliance ();
1993 public class NullableType : TypeExpr
1995 Expression underlying;
1997 public NullableType (Expression underlying, Location l)
1999 this.underlying = underlying;
2002 eclass = ExprClass.Type;
2005 public NullableType (Type type, Location loc)
2006 : this (new TypeExpression (type, loc), loc)
2009 public override string Name {
2010 get { return underlying.ToString () + "?"; }
2013 public override string FullName {
2014 get { return underlying.ToString () + "?"; }
2017 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
2019 TypeArguments args = new TypeArguments (loc);
2020 args.Add (underlying);
2022 ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
2023 return ctype.ResolveAsTypeTerminal (ec, false);
2027 public partial class TypeManager
2030 // A list of core types that the compiler requires or uses
2032 static public Type activator_type;
2033 static public Type generic_ilist_type;
2034 static public Type generic_icollection_type;
2035 static public Type generic_ienumerator_type;
2036 static public Type generic_ienumerable_type;
2037 static public Type generic_nullable_type;
2040 // These methods are called by code generated by the compiler
2042 static public MethodInfo activator_create_instance;
2044 static void InitGenericCoreTypes ()
2046 activator_type = CoreLookupType ("System", "Activator");
2048 generic_ilist_type = CoreLookupType (
2049 "System.Collections.Generic", "IList", 1);
2050 generic_icollection_type = CoreLookupType (
2051 "System.Collections.Generic", "ICollection", 1);
2052 generic_ienumerator_type = CoreLookupType (
2053 "System.Collections.Generic", "IEnumerator", 1);
2054 generic_ienumerable_type = CoreLookupType (
2055 "System.Collections.Generic", "IEnumerable", 1);
2056 generic_nullable_type = CoreLookupType (
2057 "System", "Nullable", 1);
2060 static void InitGenericCodeHelpers ()
2063 activator_create_instance = GetCoreMethod (
2064 activator_type, "CreateInstance", Type.EmptyTypes);
2067 static Type CoreLookupType (string ns, string name, int arity)
2069 return CoreLookupType (ns, MemberName.MakeName (name, arity));
2072 public static TypeContainer LookupGenericTypeContainer (Type t)
2074 t = DropGenericTypeArguments (t);
2075 return LookupTypeContainer (t);
2079 /// Check whether `a' and `b' may become equal generic types.
2080 /// The algorithm to do that is a little bit complicated.
2082 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_inferred,
2083 Type[] method_inferred)
2085 if (a.IsGenericParameter) {
2087 // If a is an array of a's type, they may never
2091 b = b.GetElementType ();
2097 // If b is a generic parameter or an actual type,
2098 // they may become equal:
2100 // class X<T,U> : I<T>, I<U>
2101 // class X<T> : I<T>, I<float>
2103 if (b.IsGenericParameter || !b.IsGenericType) {
2104 int pos = a.GenericParameterPosition;
2105 Type[] args = a.DeclaringMethod != null ? method_inferred : class_inferred;
2106 if (args [pos] == null) {
2111 return args [pos] == a;
2115 // We're now comparing a type parameter with a
2116 // generic instance. They may become equal unless
2117 // the type parameter appears anywhere in the
2118 // generic instance:
2120 // class X<T,U> : I<T>, I<X<U>>
2121 // -> error because you could instanciate it as
2124 // class X<T> : I<T>, I<X<T>> -> ok
2127 Type[] bargs = GetTypeArguments (b);
2128 for (int i = 0; i < bargs.Length; i++) {
2129 if (a.Equals (bargs [i]))
2136 if (b.IsGenericParameter)
2137 return MayBecomeEqualGenericTypes (b, a, class_inferred, method_inferred);
2140 // At this point, neither a nor b are a type parameter.
2142 // If one of them is a generic instance, let
2143 // MayBecomeEqualGenericInstances() compare them (if the
2144 // other one is not a generic instance, they can never
2148 if (a.IsGenericType || b.IsGenericType)
2149 return MayBecomeEqualGenericInstances (a, b, class_inferred, method_inferred);
2152 // If both of them are arrays.
2155 if (a.IsArray && b.IsArray) {
2156 if (a.GetArrayRank () != b.GetArrayRank ())
2159 a = a.GetElementType ();
2160 b = b.GetElementType ();
2162 return MayBecomeEqualGenericTypes (a, b, class_inferred, method_inferred);
2166 // Ok, two ordinary types.
2169 return a.Equals (b);
2173 // Checks whether two generic instances may become equal for some
2174 // particular instantiation (26.3.1).
2176 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
2177 Type[] class_inferred,
2178 Type[] method_inferred)
2180 if (!a.IsGenericType || !b.IsGenericType)
2182 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2185 return MayBecomeEqualGenericInstances (
2186 GetTypeArguments (a), GetTypeArguments (b), class_inferred, method_inferred);
2189 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
2190 Type[] class_inferred,
2191 Type[] method_inferred)
2193 if (aargs.Length != bargs.Length)
2196 for (int i = 0; i < aargs.Length; i++) {
2197 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_inferred, method_inferred))
2205 /// Type inference. Try to infer the type arguments from `method',
2206 /// which is invoked with the arguments `arguments'. This is used
2207 /// when resolving an Invocation or a DelegateInvocation and the user
2208 /// did not explicitly specify type arguments.
2210 public static int InferTypeArguments (EmitContext ec,
2211 ArrayList arguments,
2212 ref MethodBase method)
2214 ATypeInference ti = ATypeInference.CreateInstance (arguments);
2215 Type[] i_args = ti.InferMethodArguments (ec, method);
2217 return ti.InferenceScore;
2219 if (i_args.Length == 0)
2222 method = ((MethodInfo) method).MakeGenericMethod (i_args);
2229 public static bool InferTypeArguments (ParameterData apd,
2230 ref MethodBase method)
2232 if (!TypeManager.IsGenericMethod (method))
2235 ATypeInference ti = ATypeInference.CreateInstance (ArrayList.Adapter (apd.Types));
2236 Type[] i_args = ti.InferDelegateArguments (method);
2240 method = ((MethodInfo) method).MakeGenericMethod (i_args);
2245 abstract class ATypeInference
2247 protected readonly ArrayList arguments;
2248 protected readonly int arg_count;
2250 protected ATypeInference (ArrayList arguments)
2252 this.arguments = arguments;
2253 if (arguments != null)
2254 arg_count = arguments.Count;
2257 public static ATypeInference CreateInstance (ArrayList arguments)
2259 if (RootContext.Version == LanguageVersion.ISO_2)
2260 return new TypeInferenceV2 (arguments);
2262 return new TypeInferenceV3 (arguments);
2265 public virtual int InferenceScore {
2267 return int.MaxValue;
2271 public abstract Type[] InferMethodArguments (EmitContext ec, MethodBase method);
2272 public abstract Type[] InferDelegateArguments (MethodBase method);
2276 // Implements C# 2.0 type inference
2278 class TypeInferenceV2 : ATypeInference
2280 public TypeInferenceV2 (ArrayList arguments)
2285 public override Type[] InferDelegateArguments (MethodBase method)
2287 ParameterData pd = TypeManager.GetParameterData (method);
2288 if (arg_count != pd.Count)
2291 Type[] method_args = method.GetGenericArguments ();
2292 Type[] inferred_types = new Type[method_args.Length];
2294 Type[] param_types = new Type[pd.Count];
2295 Type[] arg_types = (Type[])arguments.ToArray (typeof (Type));
2297 for (int i = 0; i < arg_count; i++) {
2298 param_types[i] = pd.ParameterType (i);
2301 if (!InferTypeArguments (param_types, arg_types, inferred_types))
2304 return inferred_types;
2307 public override Type[] InferMethodArguments (EmitContext ec, MethodBase method)
2309 ParameterData pd = TypeManager.GetParameterData (method);
2310 Type[] method_generic_args = method.GetGenericArguments ();
2311 Type [] inferred_types = new Type [method_generic_args.Length];
2312 Type[] arg_types = new Type [pd.Count];
2314 int a_count = arg_types.Length;
2318 for (int i = 0; i < a_count; i++) {
2319 Argument a = (Argument) arguments[i];
2320 if (a.Expr is NullLiteral || a.Expr is MethodGroupExpr || a.Expr is AnonymousMethodExpression)
2323 if (!TypeInferenceV2.UnifyType (pd.ParameterType (i), a.Type, inferred_types))
2328 Type element_type = TypeManager.GetElementType (pd.ParameterType (a_count));
2329 for (int i = a_count; i < arg_count; i++) {
2330 Argument a = (Argument) arguments [i];
2331 if (a.Expr is NullLiteral || a.Expr is MethodGroupExpr || a.Expr is AnonymousMethodExpression)
2334 if (!TypeInferenceV2.UnifyType (element_type, a.Type, inferred_types))
2339 for (int i = 0; i < inferred_types.Length; i++)
2340 if (inferred_types [i] == null)
2343 return inferred_types;
2346 static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
2347 Type[] inferred_types)
2349 for (int i = 0; i < arg_types.Length; i++) {
2350 if (arg_types[i] == null)
2353 if (!UnifyType (param_types[i], arg_types[i], inferred_types))
2357 for (int i = 0; i < inferred_types.Length; ++i)
2358 if (inferred_types[i] == null)
2364 public static bool UnifyType (Type pt, Type at, Type[] inferred)
2366 if (pt.IsGenericParameter) {
2367 if (pt.DeclaringMethod == null)
2370 int pos = pt.GenericParameterPosition;
2372 if (inferred [pos] == null)
2373 inferred [pos] = at;
2375 return inferred [pos] == at;
2378 if (!pt.ContainsGenericParameters) {
2379 if (at.ContainsGenericParameters)
2380 return UnifyType (at, pt, inferred);
2387 if (at.GetArrayRank () != pt.GetArrayRank ())
2390 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2393 if (!pt.IsGenericType)
2396 Type gt = pt.GetGenericTypeDefinition ();
2397 if ((gt != TypeManager.generic_ilist_type) && (gt != TypeManager.generic_icollection_type) &&
2398 (gt != TypeManager.generic_ienumerable_type))
2401 Type[] args = TypeManager.GetTypeArguments (pt);
2402 return UnifyType (args[0], at.GetElementType (), inferred);
2407 (pt.GetArrayRank () != at.GetArrayRank ()))
2410 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2413 if (pt.IsByRef && at.IsByRef)
2414 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2415 ArrayList list = new ArrayList ();
2416 if (at.IsGenericType)
2418 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
2421 list.AddRange (TypeManager.GetInterfaces (at));
2423 foreach (Type type in list) {
2424 if (!type.IsGenericType)
2427 if (TypeManager.DropGenericTypeArguments (pt) != TypeManager.DropGenericTypeArguments (type))
2430 if (!UnifyTypes (pt.GetGenericArguments (), type.GetGenericArguments (), inferred))
2437 static bool UnifyTypes (Type[] pts, Type[] ats, Type[] inferred)
2439 for (int i = 0; i < ats.Length; i++) {
2440 if (!UnifyType (pts [i], ats [i], inferred))
2448 // Implements C# 3.0 type inference
2450 class TypeInferenceV3 : ATypeInference
2453 // Tracks successful rate of type inference
2455 int score = int.MaxValue;
2457 public TypeInferenceV3 (ArrayList arguments)
2462 public override int InferenceScore {
2468 public override Type[] InferDelegateArguments (MethodBase method)
2470 ParameterData pd = TypeManager.GetParameterData (method);
2471 if (arg_count != pd.Count)
2474 Type[] d_gargs = method.GetGenericArguments ();
2475 TypeInferenceContext context = new TypeInferenceContext (d_gargs);
2477 // A lower-bound inference is made from each argument type Uj of D
2478 // to the corresponding parameter type Tj of M
2479 for (int i = 0; i < arg_count; ++i) {
2480 Type t = pd.Types [i];
2481 if (!t.IsGenericParameter)
2484 context.LowerBoundInference ((Type)arguments[i], t);
2487 if (!context.FixAllTypes ())
2490 return context.InferredTypeArguments;
2493 public override Type[] InferMethodArguments (EmitContext ec, MethodBase method)
2495 Type[] method_generic_args = method.GetGenericArguments ();
2496 TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2497 if (!context.UnfixedVariableExists)
2498 return Type.EmptyTypes;
2500 ParameterData pd = TypeManager.GetParameterData (method);
2501 if (!InferInPhases (ec, context, pd))
2504 return context.InferredTypeArguments;
2508 // Implements method type arguments inference
2510 bool InferInPhases (EmitContext ec, TypeInferenceContext tic, ParameterData methodParameters)
2512 int params_arguments_start;
2513 if (methodParameters.HasParams) {
2514 params_arguments_start = methodParameters.Count - 1;
2516 params_arguments_start = arg_count;
2520 // The first inference phase
2522 Type method_parameter = null;
2523 for (int i = 0; i < arg_count; i++) {
2524 Argument a = (Argument) arguments [i];
2526 if (i < params_arguments_start) {
2527 method_parameter = methodParameters.Types [i];
2528 } else if (i == params_arguments_start) {
2529 if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2530 method_parameter = methodParameters.Types [params_arguments_start];
2532 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2536 // When a lambda expression, an anonymous method
2537 // is used an explicit argument type inference takes a place
2539 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2541 if (am.ExplicitTypeInference (tic, method_parameter))
2546 if (a.Expr.Type == TypeManager.null_type)
2550 // Otherwise an output type inference is made
2552 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2556 // Part of the second phase but because it happens only once
2557 // we don't need to call it in cycle
2559 bool fixed_any = false;
2560 if (!tic.FixIndependentTypeArguments (methodParameters, ref fixed_any))
2563 return DoSecondPhase (ec, tic, methodParameters, !fixed_any);
2566 bool DoSecondPhase (EmitContext ec, TypeInferenceContext tic, ParameterData methodParameters, bool fixDependent)
2568 bool fixed_any = false;
2569 if (fixDependent && !tic.FixDependentTypes (methodParameters, ref fixed_any))
2572 // If no further unfixed type variables exist, type inference succeeds
2573 if (!tic.UnfixedVariableExists)
2576 if (!fixed_any && fixDependent)
2579 // For all arguments where the corresponding argument output types
2580 // contain unfixed type variables but the input types do not,
2581 // an output type inference is made
2582 for (int i = 0; i < arg_count; i++) {
2583 Type t_i = methodParameters.ParameterType (i);
2584 if (!TypeManager.IsDelegateType (t_i)) {
2585 if (TypeManager.DropGenericTypeArguments (t_i) != TypeManager.expression_type)
2588 t_i = t_i.GetGenericArguments () [0];
2591 MethodInfo mi = Delegate.GetInvokeMethod (t_i, t_i);
2592 Type rtype = mi.ReturnType;
2595 // Blablabla, because reflection does not work with dynamic types
2596 Type[] g_args = t_i.GetGenericArguments ();
2597 rtype = g_args[rtype.GenericParameterPosition];
2600 if (tic.IsReturnTypeNonDependent (mi, rtype))
2601 score -= tic.OutputTypeInference (ec, ((Argument) arguments [i]).Expr, t_i);
2605 return DoSecondPhase (ec, tic, methodParameters, true);
2609 public class TypeInferenceContext
2611 readonly Type[] unfixed_types;
2612 readonly Type[] fixed_types;
2613 readonly ArrayList[] bounds;
2615 public TypeInferenceContext (Type[] typeArguments)
2617 if (typeArguments.Length == 0)
2618 throw new ArgumentException ("Empty generic arguments");
2620 fixed_types = new Type [typeArguments.Length];
2621 for (int i = 0; i < typeArguments.Length; ++i) {
2622 if (typeArguments [i].IsGenericParameter) {
2623 if (bounds == null) {
2624 bounds = new ArrayList [typeArguments.Length];
2625 unfixed_types = new Type [typeArguments.Length];
2627 unfixed_types [i] = typeArguments [i];
2629 fixed_types [i] = typeArguments [i];
2634 public Type[] InferredTypeArguments {
2640 void AddToBounds (Type t, int index)
2642 ArrayList a = bounds [index];
2644 a = new ArrayList ();
2652 // SPEC: does not cover type inference using constraints
2654 if (TypeManager.IsGenericParameter (t)) {
2655 GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
2656 if (constraints != null) {
2657 //if (constraints.EffectiveBaseClass != null)
2658 // t = constraints.EffectiveBaseClass;
2664 bool AllTypesAreFixed (Type[] types)
2666 foreach (Type t in types) {
2667 if (t.IsGenericParameter) {
2673 if (t.IsGenericType)
2674 return AllTypesAreFixed (t.GetGenericArguments ());
2681 // 26.3.3.8 Exact Inference
2683 public int ExactInference (Type u, Type v)
2685 // If V is an array type
2690 if (u.GetArrayRank () != v.GetArrayRank ())
2693 return ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
2696 // If V is constructed type and U is constructed type
2697 if (v.IsGenericType && !v.IsGenericTypeDefinition) {
2698 if (!u.IsGenericType)
2701 Type [] ga_u = u.GetGenericArguments ();
2702 Type [] ga_v = v.GetGenericArguments ();
2703 if (ga_u.Length != ga_v.Length)
2707 for (int i = 0; i < ga_u.Length; ++i)
2708 score += ExactInference (ga_u [i], ga_v [i]);
2710 return score > 0 ? 1 : 0;
2713 // If V is one of the unfixed type arguments
2714 int pos = IsUnfixed (v);
2718 AddToBounds (u, pos);
2722 public bool FixAllTypes ()
2724 for (int i = 0; i < unfixed_types.Length; ++i) {
2732 // All unfixed type variables Xi are fixed for which all of the following hold:
2733 // a, There is at least one type variable Xj that depends on Xi
2734 // b, Xi has a non-empty set of bounds
2736 public bool FixDependentTypes (ParameterData methodParameters, ref bool fixed_any)
2738 for (int i = 0; i < unfixed_types.Length; ++i) {
2739 if (unfixed_types[i] == null)
2742 if (bounds[i] == null)
2755 // All unfixed type variables Xi which depend on no Xj are fixed
2757 public bool FixIndependentTypeArguments (ParameterData methodParameters, ref bool fixed_any)
2759 ArrayList types_to_fix = new ArrayList (unfixed_types);
2760 for (int i = 0; i < methodParameters.Types.Length; ++i) {
2761 Type t = methodParameters.Types [i];
2762 if (t.IsGenericParameter)
2765 if (!TypeManager.IsDelegateType (t)) {
2766 if (TypeManager.DropGenericTypeArguments (t) != TypeManager.expression_type)
2769 t = t.GetGenericArguments () [0];
2772 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
2773 Type rtype = invoke.ReturnType;
2774 if (!rtype.IsGenericParameter && !rtype.IsGenericType)
2778 // Blablabla, because reflection does not work with dynamic types
2779 if (rtype.IsGenericParameter) {
2780 Type [] g_args = t.GetGenericArguments ();
2781 rtype = g_args [rtype.GenericParameterPosition];
2784 // Remove dependent types, they cannot be fixed yet
2785 RemoveDependentTypes (types_to_fix, rtype);
2788 foreach (Type t in types_to_fix) {
2792 int idx = IsUnfixed (t);
2793 if (idx >= 0 && !FixType (idx)) {
2798 fixed_any = types_to_fix.Count > 0;
2805 public bool FixType (int i)
2807 // It's already fixed
2808 if (unfixed_types[i] == null)
2809 throw new InternalErrorException ("Type argument has been already fixed");
2811 ArrayList candidates = (ArrayList)bounds [i];
2812 if (candidates == null)
2815 if (candidates.Count == 1) {
2816 unfixed_types[i] = null;
2817 fixed_types[i] = (Type)candidates[0];
2822 // Determines a unique type from which there is
2823 // a standard implicit conversion to all the other
2826 Type best_candidate = null;
2828 int candidates_count = candidates.Count;
2829 for (int ci = 0; ci < candidates_count; ++ci) {
2830 Type candidate = (Type)candidates [ci];
2831 for (cii = 0; cii < candidates_count; ++cii) {
2835 if (!Convert.ImplicitConversionExists (null,
2836 new TypeExpression ((Type)candidates [cii], Location.Null), candidate)) {
2841 if (cii != candidates_count)
2844 if (best_candidate != null)
2847 best_candidate = candidate;
2850 if (best_candidate == null)
2853 unfixed_types[i] = null;
2854 fixed_types[i] = best_candidate;
2859 // Uses inferred types to inflate delegate type argument
2861 public Type InflateGenericArgument (Type parameter)
2863 if (parameter.IsGenericParameter)
2864 return fixed_types [parameter.GenericParameterPosition];
2866 if (parameter.IsGenericType) {
2867 Type [] parameter_targs = parameter.GetGenericArguments ();
2868 for (int ii = 0; ii < parameter_targs.Length; ++ii) {
2869 parameter_targs [ii] = InflateGenericArgument (parameter_targs [ii]);
2871 return parameter.GetGenericTypeDefinition ().MakeGenericType (parameter_targs);
2878 // Tests whether all delegate input arguments are fixed and generic output type
2879 // requires output type inference
2881 public bool IsReturnTypeNonDependent (MethodInfo invoke, Type returnType)
2883 if (returnType.IsGenericParameter) {
2884 if (IsFixed (returnType))
2886 } else if (returnType.IsGenericType) {
2887 if (TypeManager.IsDelegateType (returnType)) {
2888 invoke = Delegate.GetInvokeMethod (returnType, returnType);
2889 return IsReturnTypeNonDependent (invoke, invoke.ReturnType);
2892 Type[] g_args = returnType.GetGenericArguments ();
2894 // At least one unfixed return type has to exist
2895 if (AllTypesAreFixed (g_args))
2901 // All generic input arguments have to be fixed
2902 ParameterData d_parameters = TypeManager.GetParameterData (invoke);
2903 return AllTypesAreFixed (d_parameters.Types);
2906 bool IsFixed (Type type)
2908 return IsUnfixed (type) == -1;
2911 int IsUnfixed (Type type)
2913 if (!type.IsGenericParameter)
2916 //return unfixed_types[type.GenericParameterPosition] != null;
2917 for (int i = 0; i < unfixed_types.Length; ++i) {
2918 if (unfixed_types [i] == type)
2926 // 26.3.3.9 Lower-bound Inference
2928 public int LowerBoundInference (Type u, Type v)
2930 // Remove ref, out modifiers
2932 v = v.GetElementType ();
2934 // If V is one of the unfixed type arguments
2935 int pos = IsUnfixed (v);
2937 AddToBounds (u, pos);
2941 // If U is an array type
2943 int u_dim = u.GetArrayRank ();
2945 Type u_e = TypeManager.GetElementType (u);
2948 if (u_dim != v.GetArrayRank ())
2951 v_e = TypeManager.GetElementType (v);
2954 return LowerBoundInference (u_e, v_e);
2957 return ExactInference (u_e, v_e);
2963 if (v.IsGenericType) {
2964 Type g_v = v.GetGenericTypeDefinition ();
2965 if ((g_v != TypeManager.generic_ilist_type) && (g_v != TypeManager.generic_icollection_type) &&
2966 (g_v != TypeManager.generic_ienumerable_type))
2969 v_e = TypeManager.GetTypeArguments (v)[0];
2972 return LowerBoundInference (u_e, v_e);
2975 return ExactInference (u_e, v_e);
2977 } else if (v.IsGenericType && !v.IsGenericTypeDefinition) {
2979 // if V is a constructed type C<V1..Vk> and there is a unique set of types U1..Uk
2980 // such that a standard implicit conversion exists from U to C<U1..Uk> then an exact
2981 // inference is made from each Ui for the corresponding Vi
2983 ArrayList u_candidates = new ArrayList ();
2984 if (u.IsGenericType)
2985 u_candidates.Add (u);
2987 for (Type t = u.BaseType; t != null; t = t.BaseType) {
2988 if (t.IsGenericType && !t.IsGenericTypeDefinition)
2989 u_candidates.Add (t);
2992 // TODO: Implement GetGenericInterfaces only and remove
2993 // the if from foreach
2994 u_candidates.AddRange (TypeManager.GetInterfaces (u));
2996 Type open_v = v.GetGenericTypeDefinition ();
2998 foreach (Type u_candidate in u_candidates) {
2999 if (!u_candidate.IsGenericType || u_candidate.IsGenericTypeDefinition)
3002 if (TypeManager.DropGenericTypeArguments (u_candidate) != open_v)
3005 Type [] ga_u = u_candidate.GetGenericArguments ();
3006 Type [] ga_v = v.GetGenericArguments ();
3007 bool all_exact = true;
3008 for (int i = 0; i < ga_u.Length; ++i)
3009 if (ExactInference (ga_u [i], ga_v [i]) == 0)
3012 if (all_exact && score == 0)
3022 // 26.3.3.6 Output Type Inference
3024 public int OutputTypeInference (EmitContext ec, Expression e, Type t)
3026 // If e is a lambda or anonymous method with inferred return type
3027 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
3029 Type rt = ame.InferReturnType (ec, this, t);
3030 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
3033 ParameterData pd = TypeManager.GetParameterData (invoke);
3034 return ame.Parameters.Count == pd.Count ? 1 : 0;
3037 Type rtype = invoke.ReturnType;
3039 // Blablabla, because reflection does not work with dynamic types
3040 Type [] g_args = t.GetGenericArguments ();
3041 rtype = g_args [rtype.GenericParameterPosition];
3043 return LowerBoundInference (rt, rtype) + 1;
3046 if (e is MethodGroupExpr) {
3047 if (!TypeManager.IsDelegateType (t))
3050 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
3051 Type rtype = invoke.ReturnType;
3052 if (!TypeManager.IsGenericType (rtype))
3055 throw new NotImplementedException ();
3059 // if e is an expression with type U, then
3060 // a lower-bound inference is made from U for T
3062 return LowerBoundInference (e.Type, t) * 2;
3065 static void RemoveDependentTypes (ArrayList types, Type returnType)
3067 if (returnType.IsGenericParameter) {
3068 types [returnType.GenericParameterPosition] = null;
3072 if (returnType.IsGenericType) {
3073 foreach (Type t in returnType.GetGenericArguments ()) {
3074 RemoveDependentTypes (types, t);
3079 public bool UnfixedVariableExists {
3081 if (unfixed_types == null)
3084 foreach (Type ut in unfixed_types)
3092 public abstract class Nullable
3094 public sealed class NullableInfo
3096 public readonly Type Type;
3097 public readonly Type UnderlyingType;
3098 public readonly MethodInfo HasValue;
3099 public readonly MethodInfo Value;
3100 public readonly ConstructorInfo Constructor;
3102 public NullableInfo (Type type)
3105 UnderlyingType = TypeManager.GetTypeArguments (type) [0];
3107 PropertyInfo has_value_pi = TypeManager.GetProperty (type, "HasValue");
3108 PropertyInfo value_pi = TypeManager.GetProperty (type, "Value");
3110 HasValue = has_value_pi.GetGetMethod (false);
3111 Value = value_pi.GetGetMethod (false);
3112 Constructor = type.GetConstructor (new Type[] { UnderlyingType });
3116 public class HasValue : Expression
3121 private HasValue (Expression expr)
3126 public static Expression Create (Expression expr, EmitContext ec)
3128 return new HasValue (expr).Resolve (ec);
3131 public override void Emit (EmitContext ec)
3133 IMemoryLocation memory_loc = expr as IMemoryLocation;
3134 if (memory_loc == null) {
3135 LocalTemporary temp = new LocalTemporary (expr.Type);
3140 memory_loc.AddressOf (ec, AddressOp.LoadStore);
3141 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
3144 public override Expression DoResolve (EmitContext ec)
3146 this.info = new NullableInfo (expr.Type);
3148 type = TypeManager.bool_type;
3149 eclass = expr.eclass;
3154 public class Unwrap : Expression, IMemoryLocation, IAssignMethod
3159 LocalTemporary temp;
3162 protected Unwrap (Expression expr)
3165 this.loc = expr.Location;
3168 public static Unwrap Create (Expression expr, EmitContext ec)
3170 return new Unwrap (expr).Resolve (ec) as Unwrap;
3173 public override Expression CreateExpressionTree (EmitContext ec)
3175 return expr.CreateExpressionTree (ec);
3178 public override Expression DoResolve (EmitContext ec)
3183 temp = new LocalTemporary (expr.Type);
3185 info = new NullableInfo (expr.Type);
3186 type = info.UnderlyingType;
3187 eclass = expr.eclass;
3191 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
3193 return DoResolve (ec);
3196 public override void Emit (EmitContext ec)
3198 AddressOf (ec, AddressOp.LoadStore);
3199 ec.ig.EmitCall (OpCodes.Call, info.Value, null);
3202 public void EmitCheck (EmitContext ec)
3204 AddressOf (ec, AddressOp.LoadStore);
3205 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
3208 public override bool IsNull {
3214 public void Store (EmitContext ec)
3219 void create_temp (EmitContext ec)
3221 if ((temp != null) && !has_temp) {
3228 public void AddressOf (EmitContext ec, AddressOp mode)
3232 temp.AddressOf (ec, AddressOp.LoadStore);
3234 ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
3237 public void Emit (EmitContext ec, bool leave_copy)
3250 public void EmitAssign (EmitContext ec, Expression source,
3251 bool leave_copy, bool prepare_for_load)
3253 InternalWrap wrap = new InternalWrap (source, info, loc);
3254 ((IAssignMethod) expr).EmitAssign (ec, wrap, leave_copy, false);
3257 protected class InternalWrap : Expression
3259 public Expression expr;
3260 public NullableInfo info;
3262 public InternalWrap (Expression expr, NullableInfo info, Location loc)
3269 eclass = ExprClass.Value;
3272 public override Expression DoResolve (EmitContext ec)
3277 public override void Emit (EmitContext ec)
3280 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
3285 public class Wrap : Expression
3290 protected Wrap (Expression expr)
3293 this.loc = expr.Location;
3296 public static Wrap Create (Expression expr, EmitContext ec)
3298 return new Wrap (expr).Resolve (ec) as Wrap;
3301 public override Expression CreateExpressionTree (EmitContext ec)
3303 ArrayList args = new ArrayList (2);
3304 args.Add (new Argument (expr.CreateExpressionTree (ec)));
3305 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
3306 return CreateExpressionFactoryCall ("Convert", args);
3309 public override Expression DoResolve (EmitContext ec)
3314 TypeExpr target_type = new NullableType (expr.Type, loc);
3315 target_type = target_type.ResolveAsTypeTerminal (ec, false);
3316 if (target_type == null)
3319 type = target_type.Type;
3320 info = new NullableInfo (type);
3321 eclass = ExprClass.Value;
3325 public override void Emit (EmitContext ec)
3328 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
3333 // Represents null value converted to nullable type
3335 public class Null : Expression, IMemoryLocation
3337 public Null (Type target_type, Location loc)
3339 this.type = target_type;
3342 eclass = ExprClass.Value;
3345 public override Expression CreateExpressionTree (EmitContext ec)
3347 return EmptyCast.Create (new NullConstant (loc), type).CreateExpressionTree (ec);
3350 public override Expression DoResolve (EmitContext ec)
3355 public override void Emit (EmitContext ec)
3357 LocalTemporary value_target = new LocalTemporary (type);
3359 value_target.AddressOf (ec, AddressOp.Store);
3360 ec.ig.Emit (OpCodes.Initobj, type);
3361 value_target.Emit (ec);
3364 public override bool IsNull {
3370 public void AddressOf (EmitContext ec, AddressOp Mode)
3372 LocalTemporary value_target = new LocalTemporary (type);
3374 value_target.AddressOf (ec, AddressOp.Store);
3375 ec.ig.Emit (OpCodes.Initobj, type);
3376 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
3380 public abstract class Lifted : Expression, IMemoryLocation
3382 Expression expr, underlying, wrap, null_value;
3385 protected Lifted (Expression expr, Location loc)
3391 public override Expression CreateExpressionTree (EmitContext ec)
3393 return expr.CreateExpressionTree (ec);
3396 public override Expression DoResolve (EmitContext ec)
3398 expr = expr.Resolve (ec);
3402 unwrap = Unwrap.Create (expr, ec);
3406 underlying = ResolveUnderlying (unwrap, ec);
3407 if (underlying == null)
3410 wrap = Wrap.Create (underlying, ec);
3414 null_value = new Null (wrap.Type, loc).Resolve (ec);
3415 if (null_value == null)
3419 eclass = ExprClass.Value;
3423 protected abstract Expression ResolveUnderlying (Expression unwrap, EmitContext ec);
3425 public override void Emit (EmitContext ec)
3427 ILGenerator ig = ec.ig;
3428 Label is_null_label = ig.DefineLabel ();
3429 Label end_label = ig.DefineLabel ();
3431 unwrap.EmitCheck (ec);
3432 ig.Emit (OpCodes.Brfalse, is_null_label);
3435 ig.Emit (OpCodes.Br, end_label);
3437 ig.MarkLabel (is_null_label);
3438 null_value.Emit (ec);
3440 ig.MarkLabel (end_label);
3443 public void AddressOf (EmitContext ec, AddressOp mode)
3445 unwrap.AddressOf (ec, mode);
3449 public class LiftedConversion : Lifted
3451 public readonly bool IsUser;
3452 public readonly bool IsExplicit;
3453 public readonly Type TargetType;
3455 public LiftedConversion (Expression expr, Type target_type, bool is_user,
3456 bool is_explicit, Location loc)
3459 this.IsUser = is_user;
3460 this.IsExplicit = is_explicit;
3461 this.TargetType = target_type;
3464 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
3466 Type type = TypeManager.GetTypeArguments (TargetType) [0];
3469 return Convert.UserDefinedConversion (ec, unwrap, type, loc, IsExplicit);
3472 return Convert.ExplicitConversion (ec, unwrap, type, loc);
3474 return Convert.ImplicitConversion (ec, unwrap, type, loc);
3479 public class LiftedUnaryOperator : Lifted
3481 public readonly Unary.Operator Oper;
3483 public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
3489 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
3491 return new Unary (Oper, unwrap, loc).Resolve (ec);
3495 public class LiftedBinaryOperator : Binary
3497 Expression underlying, null_value, bool_wrap;
3498 Unwrap left_unwrap, right_unwrap;
3499 bool is_equality, is_comparision, is_boolean;
3501 public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
3503 : base (op, left, right)
3508 public override Expression DoResolve (EmitContext ec)
3510 if ((Oper == Binary.Operator.LogicalAnd) ||
3511 (Oper == Binary.Operator.LogicalOr)) {
3512 Error_OperatorCannotBeApplied ();
3517 // Optimize null comparisons
3519 if (Oper == Binary.Operator.Equality) {
3521 return new Unary (Unary.Operator.LogicalNot, Nullable.HasValue.Create (right, ec), loc).Resolve (ec);
3523 return new Unary (Unary.Operator.LogicalNot, Nullable.HasValue.Create (left, ec), loc).Resolve (ec);
3525 if (Oper == Binary.Operator.Inequality) {
3527 return Nullable.HasValue.Create (right, ec);
3529 return Nullable.HasValue.Create (left, ec);
3532 if (TypeManager.IsNullableType (left.Type)) {
3533 left = left_unwrap = Unwrap.Create (left, ec);
3538 if (TypeManager.IsNullableType (right.Type)) {
3539 right = right_unwrap = Unwrap.Create (right, ec);
3544 if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr)) &&
3545 ((left.Type == TypeManager.bool_type) && (right.Type == TypeManager.bool_type))) {
3546 Expression empty = new EmptyExpression (TypeManager.bool_type);
3547 bool_wrap = Wrap.Create (empty, ec);
3548 null_value = new Null (bool_wrap.Type, loc).Resolve (ec);
3550 type = bool_wrap.Type;
3552 } else if ((Oper == Binary.Operator.Equality) || (Oper == Binary.Operator.Inequality)) {
3553 underlying = new Binary (Oper, left, right).Resolve (ec);
3554 if (underlying == null)
3556 type = TypeManager.bool_type;
3558 } else if ((Oper == Binary.Operator.LessThan) ||
3559 (Oper == Binary.Operator.GreaterThan) ||
3560 (Oper == Binary.Operator.LessThanOrEqual) ||
3561 (Oper == Binary.Operator.GreaterThanOrEqual)) {
3562 underlying = new Binary (Oper, left, right).Resolve (ec);
3563 if (underlying == null)
3566 type = TypeManager.bool_type;
3567 is_comparision = true;
3569 underlying = new Binary (Oper, left, right).Resolve (ec);
3570 if (underlying == null)
3573 underlying = Wrap.Create (underlying, ec);
3574 if (underlying == null)
3577 type = underlying.Type;
3578 null_value = new Null (type, loc).Resolve (ec);
3581 eclass = ExprClass.Value;
3585 void EmitBoolean (EmitContext ec)
3587 ILGenerator ig = ec.ig;
3589 Label left_is_null_label = ig.DefineLabel ();
3590 Label right_is_null_label = ig.DefineLabel ();
3591 Label is_null_label = ig.DefineLabel ();
3592 Label wrap_label = ig.DefineLabel ();
3593 Label end_label = ig.DefineLabel ();
3595 if (left_unwrap != null) {
3596 left_unwrap.EmitCheck (ec);
3597 ig.Emit (OpCodes.Brfalse, left_is_null_label);
3601 ig.Emit (OpCodes.Dup);
3602 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3603 ig.Emit (OpCodes.Brtrue, wrap_label);
3605 ig.Emit (OpCodes.Brfalse, wrap_label);
3607 if (right_unwrap != null) {
3608 right_unwrap.EmitCheck (ec);
3609 ig.Emit (OpCodes.Brfalse, right_is_null_label);
3612 if ((Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr))
3613 ig.Emit (OpCodes.Pop);
3616 if (Oper == Binary.Operator.BitwiseOr)
3617 ig.Emit (OpCodes.Or);
3618 else if (Oper == Binary.Operator.BitwiseAnd)
3619 ig.Emit (OpCodes.And);
3620 ig.Emit (OpCodes.Br, wrap_label);
3622 ig.MarkLabel (left_is_null_label);
3623 if (right_unwrap != null) {
3624 right_unwrap.EmitCheck (ec);
3625 ig.Emit (OpCodes.Brfalse, is_null_label);
3629 ig.Emit (OpCodes.Dup);
3630 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3631 ig.Emit (OpCodes.Brtrue, wrap_label);
3633 ig.Emit (OpCodes.Brfalse, wrap_label);
3635 ig.MarkLabel (right_is_null_label);
3636 ig.Emit (OpCodes.Pop);
3637 ig.MarkLabel (is_null_label);
3638 null_value.Emit (ec);
3639 ig.Emit (OpCodes.Br, end_label);
3641 ig.MarkLabel (wrap_label);
3642 ig.Emit (OpCodes.Nop);
3643 bool_wrap.Emit (ec);
3644 ig.Emit (OpCodes.Nop);
3646 ig.MarkLabel (end_label);
3649 void EmitEquality (EmitContext ec)
3651 if (left.IsNull || right.IsNull)
3652 throw new InternalErrorException ("Unoptimized nullable comparison");
3654 ILGenerator ig = ec.ig;
3656 Label both_have_value_label = ig.DefineLabel ();
3657 Label end_label = ig.DefineLabel ();
3659 if (left_unwrap != null && right_unwrap != null) {
3660 Label dissimilar_label = ig.DefineLabel ();
3662 left_unwrap.EmitCheck (ec);
3663 ig.Emit (OpCodes.Dup);
3664 right_unwrap.EmitCheck (ec);
3665 ig.Emit (OpCodes.Bne_Un, dissimilar_label);
3667 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3670 if (Oper == Binary.Operator.Equality)
3671 ig.Emit (OpCodes.Ldc_I4_1);
3673 ig.Emit (OpCodes.Ldc_I4_0);
3674 ig.Emit (OpCodes.Br, end_label);
3676 ig.MarkLabel (dissimilar_label);
3677 ig.Emit (OpCodes.Pop);
3678 } else if (left_unwrap != null) {
3679 left_unwrap.EmitCheck (ec);
3680 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3681 } else if (right_unwrap != null) {
3682 right_unwrap.EmitCheck (ec);
3683 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3685 throw new InternalErrorException ("shouldn't get here");
3688 // one is null while the other isn't
3689 if (Oper == Binary.Operator.Equality)
3690 ig.Emit (OpCodes.Ldc_I4_0);
3692 ig.Emit (OpCodes.Ldc_I4_1);
3693 ig.Emit (OpCodes.Br, end_label);
3695 ig.MarkLabel (both_have_value_label);
3696 underlying.Emit (ec);
3698 ig.MarkLabel (end_label);
3701 void EmitComparision (EmitContext ec)
3703 ILGenerator ig = ec.ig;
3705 Label is_null_label = ig.DefineLabel ();
3706 Label end_label = ig.DefineLabel ();
3708 if (left_unwrap != null) {
3709 left_unwrap.EmitCheck (ec);
3710 ig.Emit (OpCodes.Brfalse, is_null_label);
3713 if (right_unwrap != null) {
3714 right_unwrap.EmitCheck (ec);
3715 ig.Emit (OpCodes.Brfalse, is_null_label);
3718 underlying.Emit (ec);
3719 ig.Emit (OpCodes.Br, end_label);
3721 ig.MarkLabel (is_null_label);
3722 ig.Emit (OpCodes.Ldc_I4_0);
3724 ig.MarkLabel (end_label);
3727 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
3730 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
3733 public override void Emit (EmitContext ec)
3735 if (left_unwrap != null)
3736 left_unwrap.Store (ec);
3737 if (right_unwrap != null)
3738 right_unwrap.Store (ec);
3743 } else if (is_equality) {
3746 } else if (is_comparision) {
3747 EmitComparision (ec);
3751 ILGenerator ig = ec.ig;
3753 Label is_null_label = ig.DefineLabel ();
3754 Label end_label = ig.DefineLabel ();
3756 if (left_unwrap != null) {
3757 left_unwrap.EmitCheck (ec);
3758 ig.Emit (OpCodes.Brfalse, is_null_label);
3761 if (right_unwrap != null) {
3762 right_unwrap.EmitCheck (ec);
3763 ig.Emit (OpCodes.Brfalse, is_null_label);
3766 underlying.Emit (ec);
3767 ig.Emit (OpCodes.Br, end_label);
3769 ig.MarkLabel (is_null_label);
3770 null_value.Emit (ec);
3772 ig.MarkLabel (end_label);
3776 public class NullCoalescingOperator : Expression
3778 Expression left, right;
3781 public NullCoalescingOperator (Expression left, Expression right, Location loc)
3788 public override Expression CreateExpressionTree (EmitContext ec)
3790 UserCast uc = left as UserCast;
3791 Expression conversion = null;
3795 ArrayList c_args = new ArrayList (2);
3796 c_args.Add (new Argument (uc.CreateExpressionTree (ec)));
3797 c_args.Add (new Argument (left.CreateExpressionTree (ec)));
3798 conversion = CreateExpressionFactoryCall ("Lambda", c_args);
3801 ArrayList args = new ArrayList (3);
3802 args.Add (new Argument (left.CreateExpressionTree (ec)));
3803 args.Add (new Argument (right.CreateExpressionTree (ec)));
3804 if (conversion != null)
3805 args.Add (new Argument (conversion));
3807 return CreateExpressionFactoryCall ("Coalesce", args);
3810 public override Expression DoResolve (EmitContext ec)
3815 left = left.Resolve (ec);
3816 right = right.Resolve (ec);
3818 if (left == null || right == null)
3821 eclass = ExprClass.Value;
3822 Type ltype = left.Type, rtype = right.Type;
3825 if (TypeManager.IsNullableType (ltype)) {
3826 NullableInfo info = new NullableInfo (ltype);
3828 unwrap = Unwrap.Create (left, ec);
3832 expr = Convert.ImplicitConversion (ec, right, info.UnderlyingType, loc);
3839 } else if (!TypeManager.IsReferenceType (ltype)) {
3840 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3844 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
3851 Expression left_null = unwrap != null ? unwrap : left;
3852 expr = Convert.ImplicitConversion (ec, left_null, rtype, loc);
3859 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3863 public override void Emit (EmitContext ec)
3865 ILGenerator ig = ec.ig;
3867 Label is_null_label = ig.DefineLabel ();
3868 Label end_label = ig.DefineLabel ();
3870 if (unwrap != null) {
3871 unwrap.EmitCheck (ec);
3872 ig.Emit (OpCodes.Brfalse, is_null_label);
3875 ig.Emit (OpCodes.Br, end_label);
3877 ig.MarkLabel (is_null_label);
3880 ig.MarkLabel (end_label);
3883 ig.Emit (OpCodes.Dup);
3884 ig.Emit (OpCodes.Brtrue, end_label);
3886 ig.MarkLabel (is_null_label);
3888 ig.Emit (OpCodes.Pop);
3891 ig.MarkLabel (end_label);
3894 protected override void CloneTo (CloneContext clonectx, Expression t)
3896 NullCoalescingOperator target = (NullCoalescingOperator) t;
3898 target.left = left.Clone (clonectx);
3899 target.right = right.Clone (clonectx);
3903 public class LiftedUnaryMutator : ExpressionStatement
3905 public readonly UnaryMutator.Mode Mode;
3906 Expression expr, null_value;
3907 UnaryMutator underlying;
3910 public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
3916 eclass = ExprClass.Value;
3919 public override Expression DoResolve (EmitContext ec)
3921 expr = expr.Resolve (ec);
3925 unwrap = Unwrap.Create (expr, ec);
3929 underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
3930 if (underlying == null)
3933 null_value = new Null (expr.Type, loc).Resolve (ec);
3934 if (null_value == null)
3941 void DoEmit (EmitContext ec, bool is_expr)
3943 ILGenerator ig = ec.ig;
3944 Label is_null_label = ig.DefineLabel ();
3945 Label end_label = ig.DefineLabel ();
3947 unwrap.EmitCheck (ec);
3948 ig.Emit (OpCodes.Brfalse, is_null_label);
3951 underlying.Emit (ec);
3953 underlying.EmitStatement (ec);
3954 ig.Emit (OpCodes.Br, end_label);
3956 ig.MarkLabel (is_null_label);
3958 null_value.Emit (ec);
3960 ig.MarkLabel (end_label);
3963 public override void Emit (EmitContext ec)
3968 public override void EmitStatement (EmitContext ec)