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 // Dual licensed under the terms of the MIT X11 or GNU GPL
10 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004-2008 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)
134 public enum SpecialConstraint
142 /// Tracks the constraints for a type parameter from a generic type definition.
144 public class Constraints : GenericConstraints {
146 ArrayList constraints;
150 // name is the identifier, constraints is an arraylist of
151 // Expressions (with types) or `true' for the constructor constraint.
153 public Constraints (string name, ArrayList constraints,
157 this.constraints = constraints;
161 public override string TypeParameter {
167 public Constraints Clone ()
169 return new Constraints (name, constraints, loc);
172 GenericParameterAttributes attrs;
173 TypeExpr class_constraint;
174 ArrayList iface_constraints;
175 ArrayList type_param_constraints;
177 Type class_constraint_type;
178 Type[] iface_constraint_types;
179 Type effective_base_type;
184 /// Resolve the constraints - but only resolve things into Expression's, not
185 /// into actual types.
187 public bool Resolve (IResolveContext ec)
192 iface_constraints = new ArrayList (2); // TODO: Too expensive allocation
193 type_param_constraints = new ArrayList ();
195 foreach (object obj in constraints) {
196 if (HasConstructorConstraint) {
197 Report.Error (401, loc,
198 "The new() constraint must be the last constraint specified");
202 if (obj is SpecialConstraint) {
203 SpecialConstraint sc = (SpecialConstraint) obj;
205 if (sc == SpecialConstraint.Constructor) {
206 if (!HasValueTypeConstraint) {
207 attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
211 Report.Error (451, loc, "The `new()' constraint " +
212 "cannot be used with the `struct' constraint");
216 if ((num_constraints > 0) || HasReferenceTypeConstraint || HasValueTypeConstraint) {
217 Report.Error (449, loc, "The `class' or `struct' " +
218 "constraint must be the first constraint specified");
222 if (sc == SpecialConstraint.ReferenceType)
223 attrs |= GenericParameterAttributes.ReferenceTypeConstraint;
225 attrs |= GenericParameterAttributes.NotNullableValueTypeConstraint;
229 int errors = Report.Errors;
230 FullNamedExpression fn = ((Expression) obj).ResolveAsTypeStep (ec, false);
233 if (errors != Report.Errors)
236 NamespaceEntry.Error_NamespaceNotFound (loc, ((Expression)obj).GetSignatureForError ());
241 GenericTypeExpr cexpr = fn as GenericTypeExpr;
243 expr = cexpr.ResolveAsBaseTerminal (ec, false);
245 expr = ((Expression) obj).ResolveAsTypeTerminal (ec, false);
247 if ((expr == null) || (expr.Type == null))
250 if (!ec.GenericDeclContainer.IsAccessibleAs (fn.Type)) {
251 Report.SymbolRelatedToPreviousError (fn.Type);
252 Report.Error (703, loc,
253 "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
254 fn.GetSignatureForError (), ec.GenericDeclContainer.GetSignatureForError ());
258 TypeParameterExpr texpr = expr as TypeParameterExpr;
260 type_param_constraints.Add (expr);
261 else if (expr.IsInterface)
262 iface_constraints.Add (expr);
263 else if (class_constraint != null || iface_constraints.Count != 0) {
264 Report.Error (406, loc,
265 "The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
266 expr.GetSignatureForError ());
268 } else if (HasReferenceTypeConstraint || HasValueTypeConstraint) {
269 Report.Error (450, loc, "`{0}': cannot specify both " +
270 "a constraint class and the `class' " +
271 "or `struct' constraint", expr.GetSignatureForError ());
274 class_constraint = expr;
279 ArrayList list = new ArrayList ();
280 foreach (TypeExpr iface_constraint in iface_constraints) {
281 foreach (Type type in list) {
282 if (!type.Equals (iface_constraint.Type))
285 Report.Error (405, loc,
286 "Duplicate constraint `{0}' for type " +
287 "parameter `{1}'.", iface_constraint.GetSignatureForError (),
292 list.Add (iface_constraint.Type);
295 foreach (TypeParameterExpr expr in type_param_constraints) {
296 foreach (Type type in list) {
297 if (!type.Equals (expr.Type))
300 Report.Error (405, loc,
301 "Duplicate constraint `{0}' for type " +
302 "parameter `{1}'.", expr.GetSignatureForError (), name);
306 list.Add (expr.Type);
309 iface_constraint_types = new Type [list.Count];
310 list.CopyTo (iface_constraint_types, 0);
312 if (class_constraint != null) {
313 class_constraint_type = class_constraint.Type;
314 if (class_constraint_type == null)
317 if (class_constraint_type.IsSealed) {
318 if (class_constraint_type.IsAbstract)
320 Report.Error (717, loc, "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
321 TypeManager.CSharpName (class_constraint_type));
325 Report.Error (701, loc, "`{0}' is not a valid constraint. A constraint must be an interface, " +
326 "a non-sealed class or a type parameter", TypeManager.CSharpName(class_constraint_type));
331 if ((class_constraint_type == TypeManager.array_type) ||
332 (class_constraint_type == TypeManager.delegate_type) ||
333 (class_constraint_type == TypeManager.enum_type) ||
334 (class_constraint_type == TypeManager.value_type) ||
335 (class_constraint_type == TypeManager.object_type) ||
336 class_constraint_type == TypeManager.multicast_delegate_type) {
337 Report.Error (702, loc,
338 "A constraint cannot be special class `{0}'",
339 TypeManager.CSharpName (class_constraint_type));
344 if (class_constraint_type != null)
345 effective_base_type = class_constraint_type;
346 else if (HasValueTypeConstraint)
347 effective_base_type = TypeManager.value_type;
349 effective_base_type = TypeManager.object_type;
351 if ((attrs & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0)
352 attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
358 bool CheckTypeParameterConstraints (TypeParameter tparam, ref TypeExpr prevConstraint, ArrayList seen)
362 Constraints constraints = tparam.Constraints;
363 if (constraints == null)
366 if (constraints.HasValueTypeConstraint) {
367 Report.Error (456, loc,
368 "Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
374 // Checks whether there are no conflicts between type parameter constraints
378 // where U : A, B // A and B are not convertible
380 if (constraints.HasClassConstraint) {
381 if (prevConstraint != null) {
382 Type t2 = constraints.ClassConstraint;
383 TypeExpr e2 = constraints.class_constraint;
385 if (!Convert.ImplicitReferenceConversionExists (prevConstraint, t2) &&
386 !Convert.ImplicitReferenceConversionExists (e2, prevConstraint.Type)) {
387 Report.Error (455, loc,
388 "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
389 name, TypeManager.CSharpName (prevConstraint.Type), TypeManager.CSharpName (t2));
394 prevConstraint = constraints.class_constraint;
397 if (constraints.type_param_constraints == null)
400 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
401 if (seen.Contains (expr.TypeParameter)) {
402 Report.Error (454, loc, "Circular constraint " +
403 "dependency involving `{0}' and `{1}'",
404 tparam.Name, expr.GetSignatureForError ());
408 if (!CheckTypeParameterConstraints (expr.TypeParameter, ref prevConstraint, seen))
416 /// Resolve the constraints into actual types.
418 public bool ResolveTypes (IResolveContext ec)
423 resolved_types = true;
425 foreach (object obj in constraints) {
426 GenericTypeExpr cexpr = obj as GenericTypeExpr;
430 if (!cexpr.CheckConstraints (ec))
434 if (type_param_constraints.Count != 0) {
435 ArrayList seen = new ArrayList ();
436 TypeExpr prev_constraint = class_constraint;
437 foreach (TypeParameterExpr expr in type_param_constraints) {
438 if (!CheckTypeParameterConstraints (expr.TypeParameter, ref prev_constraint, seen))
444 for (int i = 0; i < iface_constraints.Count; ++i) {
445 TypeExpr iface_constraint = (TypeExpr) iface_constraints [i];
446 iface_constraint = iface_constraint.ResolveAsTypeTerminal (ec, false);
447 if (iface_constraint == null)
449 iface_constraints [i] = iface_constraint;
452 if (class_constraint != null) {
453 class_constraint = class_constraint.ResolveAsTypeTerminal (ec, false);
454 if (class_constraint == null)
461 public override GenericParameterAttributes Attributes {
462 get { return attrs; }
465 public override bool HasClassConstraint {
466 get { return class_constraint != null; }
469 public override Type ClassConstraint {
470 get { return class_constraint_type; }
473 public override Type[] InterfaceConstraints {
474 get { return iface_constraint_types; }
477 public override Type EffectiveBaseClass {
478 get { return effective_base_type; }
481 public bool IsSubclassOf (Type t)
483 if ((class_constraint_type != null) &&
484 class_constraint_type.IsSubclassOf (t))
487 if (iface_constraint_types == null)
490 foreach (Type iface in iface_constraint_types) {
491 if (TypeManager.IsSubclassOf (iface, t))
498 public Location Location {
505 /// This is used when we're implementing a generic interface method.
506 /// Each method type parameter in implementing method must have the same
507 /// constraints than the corresponding type parameter in the interface
508 /// method. To do that, we're called on each of the implementing method's
511 public bool AreEqual (GenericConstraints gc)
513 if (gc.Attributes != attrs)
516 if (HasClassConstraint != gc.HasClassConstraint)
518 if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
521 int gc_icount = gc.InterfaceConstraints != null ?
522 gc.InterfaceConstraints.Length : 0;
523 int icount = InterfaceConstraints != null ?
524 InterfaceConstraints.Length : 0;
526 if (gc_icount != icount)
529 for (int i = 0; i < gc.InterfaceConstraints.Length; ++i) {
530 Type iface = gc.InterfaceConstraints [i];
531 if (iface.IsGenericType)
532 iface = iface.GetGenericTypeDefinition ();
535 for (int ii = 0; i < InterfaceConstraints.Length; ++ii) {
536 Type check = InterfaceConstraints [ii];
537 if (check.IsGenericType)
538 check = check.GetGenericTypeDefinition ();
540 if (TypeManager.IsEqual (iface, check)) {
553 public void VerifyClsCompliance ()
555 if (class_constraint_type != null && !AttributeTester.IsClsCompliant (class_constraint_type))
556 Warning_ConstrainIsNotClsCompliant (class_constraint_type, class_constraint.Location);
558 if (iface_constraint_types != null) {
559 for (int i = 0; i < iface_constraint_types.Length; ++i) {
560 if (!AttributeTester.IsClsCompliant (iface_constraint_types [i]))
561 Warning_ConstrainIsNotClsCompliant (iface_constraint_types [i],
562 ((TypeExpr)iface_constraints [i]).Location);
567 void Warning_ConstrainIsNotClsCompliant (Type t, Location loc)
569 Report.SymbolRelatedToPreviousError (t);
570 Report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
571 TypeManager.CSharpName (t));
576 /// A type parameter from a generic type definition.
578 public class TypeParameter : MemberCore, IMemberContainer
580 static readonly string[] attribute_target = new string [] { "type parameter" };
583 GenericConstraints gc;
584 Constraints constraints;
585 GenericTypeParameterBuilder type;
586 MemberCache member_cache;
589 public TypeParameter (DeclSpace parent, DeclSpace decl, string name,
590 Constraints constraints, Attributes attrs, Variance variance, Location loc)
591 : base (parent, new MemberName (name, loc), attrs)
594 this.constraints = constraints;
595 this.variance = variance;
596 if (variance != Variance.None && !(decl is Interface) && !(decl is Delegate)) {
597 Report.Error (-36, loc, "Generic variance can only be used with interfaces and delegates");
601 public GenericConstraints GenericConstraints {
602 get { return gc != null ? gc : constraints; }
605 public Constraints Constraints {
606 get { return constraints; }
609 public DeclSpace DeclSpace {
613 public Variance Variance {
614 get { return variance; }
622 /// This is the first method which is called during the resolving
623 /// process; we're called immediately after creating the type parameters
624 /// with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
627 /// We're either called from TypeContainer.DefineType() or from
628 /// GenericMethod.Define() (called from Method.Define()).
630 public void Define (GenericTypeParameterBuilder type)
632 if (this.type != null)
633 throw new InvalidOperationException ();
636 TypeManager.AddTypeParameter (type, this);
640 /// This is the second method which is called during the resolving
641 /// process - in case of class type parameters, we're called from
642 /// TypeContainer.ResolveType() - after it resolved the class'es
643 /// base class and interfaces. For method type parameters, we're
644 /// called immediately after Define().
646 /// We're just resolving the constraints into expressions here, we
647 /// don't resolve them into actual types.
649 /// Note that in the special case of partial generic classes, we may be
650 /// called _before_ Define() and we may also be called multiple types.
652 public bool Resolve (DeclSpace ds)
654 if (constraints != null) {
655 if (!constraints.Resolve (ds)) {
665 /// This is the third method which is called during the resolving
666 /// process. We're called immediately after calling DefineConstraints()
667 /// on all of the current class'es type parameters.
669 /// Our job is to resolve the constraints to actual types.
671 /// Note that we may have circular dependencies on type parameters - this
672 /// is why Resolve() and ResolveType() are separate.
674 public bool ResolveType (IResolveContext ec)
676 if (constraints != null) {
677 if (!constraints.ResolveTypes (ec)) {
687 /// This is the fourth and last method which is called during the resolving
688 /// process. We're called after everything is fully resolved and actually
689 /// register the constraints with SRE and the TypeManager.
691 public bool DefineType (IResolveContext ec)
693 return DefineType (ec, null, null, false);
697 /// This is the fith and last method which is called during the resolving
698 /// process. We're called after everything is fully resolved and actually
699 /// register the constraints with SRE and the TypeManager.
701 /// The `builder', `implementing' and `is_override' arguments are only
702 /// applicable to method type parameters.
704 public bool DefineType (IResolveContext ec, MethodBuilder builder,
705 MethodInfo implementing, bool is_override)
707 if (!ResolveType (ec))
710 if (implementing != null) {
711 if (is_override && (constraints != null)) {
712 Report.Error (460, Location,
713 "`{0}': Cannot specify constraints for overrides or explicit interface implementation methods",
714 TypeManager.CSharpSignature (builder));
718 MethodBase mb = TypeManager.DropGenericMethodArguments (implementing);
720 int pos = type.GenericParameterPosition;
721 Type mparam = mb.GetGenericArguments () [pos];
722 GenericConstraints temp_gc = ReflectionConstraints.GetConstraints (mparam);
725 gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
726 else if (constraints != null)
727 gc = new InflatedConstraints (constraints, implementing.DeclaringType);
730 if (constraints != null) {
733 else if (!constraints.AreEqual (gc))
736 if (!is_override && (temp_gc != null))
741 Report.SymbolRelatedToPreviousError (implementing);
744 425, Location, "The constraints for type " +
745 "parameter `{0}' of method `{1}' must match " +
746 "the constraints for type parameter `{2}' " +
747 "of interface method `{3}'. Consider using " +
748 "an explicit interface implementation instead",
749 Name, TypeManager.CSharpSignature (builder),
750 TypeManager.CSharpName (mparam), TypeManager.CSharpSignature (mb));
753 } else if (DeclSpace is CompilerGeneratedClass) {
754 TypeParameter[] tparams = DeclSpace.TypeParameters;
755 Type[] types = new Type [tparams.Length];
756 for (int i = 0; i < tparams.Length; i++)
757 types [i] = tparams [i].Type;
759 if (constraints != null)
760 gc = new InflatedConstraints (constraints, types);
762 gc = (GenericConstraints) constraints;
765 SetConstraints (type);
769 public void SetConstraints (GenericTypeParameterBuilder type)
771 GenericParameterAttributes attr = GenericParameterAttributes.None;
772 if (variance == Variance.Contravariant)
773 attr |= GenericParameterAttributes.Contravariant;
774 else if (variance == Variance.Covariant)
775 attr |= GenericParameterAttributes.Covariant;
778 if (gc.HasClassConstraint || gc.HasValueTypeConstraint)
779 type.SetBaseTypeConstraint (gc.EffectiveBaseClass);
781 attr |= gc.Attributes;
782 type.SetInterfaceConstraints (gc.InterfaceConstraints);
783 TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
786 type.SetGenericParameterAttributes (attr);
790 /// This is called for each part of a partial generic type definition.
792 /// If `new_constraints' is not null and we don't already have constraints,
793 /// they become our constraints. If we already have constraints, we must
794 /// check that they're the same.
797 public bool UpdateConstraints (IResolveContext ec, Constraints new_constraints)
800 throw new InvalidOperationException ();
802 if (new_constraints == null)
805 if (!new_constraints.Resolve (ec))
807 if (!new_constraints.ResolveTypes (ec))
810 if (constraints != null)
811 return constraints.AreEqual (new_constraints);
813 constraints = new_constraints;
817 public override void Emit ()
819 if (OptAttributes != null)
820 OptAttributes.Emit ();
825 public override string DocCommentHeader {
827 throw new InvalidOperationException (
828 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
836 public override bool Define ()
841 public override void ApplyAttributeBuilder (Attribute a,
842 CustomAttributeBuilder cb)
844 type.SetCustomAttribute (cb);
847 public override AttributeTargets AttributeTargets {
849 return AttributeTargets.GenericParameter;
853 public override string[] ValidAttributeTargets {
855 return attribute_target;
863 string IMemberContainer.Name {
867 MemberCache IMemberContainer.BaseCache {
872 if (gc.EffectiveBaseClass.BaseType == null)
875 return TypeManager.LookupMemberCache (gc.EffectiveBaseClass.BaseType);
879 bool IMemberContainer.IsInterface {
880 get { return false; }
883 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
885 throw new NotSupportedException ();
888 public MemberCache MemberCache {
890 if (member_cache != null)
896 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
897 member_cache = new MemberCache (this, gc.EffectiveBaseClass, ifaces);
903 public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
904 MemberFilter filter, object criteria)
907 return MemberList.Empty;
909 ArrayList members = new ArrayList ();
911 if (gc.HasClassConstraint) {
912 MemberList list = TypeManager.FindMembers (
913 gc.ClassConstraint, mt, bf, filter, criteria);
915 members.AddRange (list);
918 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
919 foreach (Type t in ifaces) {
920 MemberList list = TypeManager.FindMembers (
921 t, mt, bf, filter, criteria);
923 members.AddRange (list);
926 return new MemberList (members);
929 public bool IsSubclassOf (Type t)
934 if (constraints != null)
935 return constraints.IsSubclassOf (t);
940 public void InflateConstraints (Type declaring)
942 if (constraints != null)
943 gc = new InflatedConstraints (constraints, declaring);
946 public override bool IsClsComplianceRequired ()
951 protected class InflatedConstraints : GenericConstraints
953 GenericConstraints gc;
955 Type class_constraint;
956 Type[] iface_constraints;
959 public InflatedConstraints (GenericConstraints gc, Type declaring)
960 : this (gc, TypeManager.GetTypeArguments (declaring))
963 public InflatedConstraints (GenericConstraints gc, Type[] dargs)
968 ArrayList list = new ArrayList ();
969 if (gc.HasClassConstraint)
970 list.Add (inflate (gc.ClassConstraint));
971 foreach (Type iface in gc.InterfaceConstraints)
972 list.Add (inflate (iface));
974 bool has_class_constr = false;
975 if (list.Count > 0) {
976 Type first = (Type) list [0];
977 has_class_constr = !first.IsGenericParameter && !first.IsInterface;
980 if ((list.Count > 0) && has_class_constr) {
981 class_constraint = (Type) list [0];
982 iface_constraints = new Type [list.Count - 1];
983 list.CopyTo (1, iface_constraints, 0, list.Count - 1);
985 iface_constraints = new Type [list.Count];
986 list.CopyTo (iface_constraints, 0);
989 if (HasValueTypeConstraint)
990 base_type = TypeManager.value_type;
991 else if (class_constraint != null)
992 base_type = class_constraint;
994 base_type = TypeManager.object_type;
997 Type inflate (Type t)
1001 if (t.IsGenericParameter)
1002 return t.GenericParameterPosition < dargs.Length ? dargs [t.GenericParameterPosition] : t;
1003 if (t.IsGenericType) {
1004 Type[] args = t.GetGenericArguments ();
1005 Type[] inflated = new Type [args.Length];
1007 for (int i = 0; i < args.Length; i++)
1008 inflated [i] = inflate (args [i]);
1010 t = t.GetGenericTypeDefinition ();
1011 t = t.MakeGenericType (inflated);
1017 public override string TypeParameter {
1018 get { return gc.TypeParameter; }
1021 public override GenericParameterAttributes Attributes {
1022 get { return gc.Attributes; }
1025 public override Type ClassConstraint {
1026 get { return class_constraint; }
1029 public override Type EffectiveBaseClass {
1030 get { return base_type; }
1033 public override Type[] InterfaceConstraints {
1034 get { return iface_constraints; }
1040 /// A TypeExpr which already resolved to a type parameter.
1042 public class TypeParameterExpr : TypeExpr {
1043 TypeParameter type_parameter;
1045 public TypeParameter TypeParameter {
1047 return type_parameter;
1051 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1053 this.type_parameter = type_parameter;
1057 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1059 throw new NotSupportedException ();
1062 public override FullNamedExpression ResolveAsTypeStep (IResolveContext ec, bool silent)
1064 type = type_parameter.Type;
1065 eclass = ExprClass.TypeParameter;
1069 public override bool IsInterface {
1070 get { return false; }
1073 public override bool CheckAccessLevel (DeclSpace ds)
1080 // Tracks the type arguments when instantiating a generic type. It's used
1081 // by both type arguments and type parameters
1083 public class TypeArguments {
1087 public TypeArguments ()
1089 args = new ArrayList ();
1092 public TypeArguments (params FullNamedExpression[] types)
1094 this.args = new ArrayList (types);
1097 public void Add (FullNamedExpression type)
1102 public void Add (TypeArguments new_args)
1104 args.AddRange (new_args.args);
1107 // TODO: Should be deleted
1108 public TypeParameterName[] GetDeclarations ()
1110 return (TypeParameterName[]) args.ToArray (typeof (TypeParameterName));
1114 /// We may only be used after Resolve() is called and return the fully
1117 public Type[] Arguments {
1129 public string GetSignatureForError()
1131 StringBuilder sb = new StringBuilder();
1132 for (int i = 0; i < Count; ++i)
1134 Expression expr = (Expression)args [i];
1135 sb.Append(expr.GetSignatureForError());
1139 return sb.ToString();
1143 /// Resolve the type arguments.
1145 public bool Resolve (IResolveContext ec)
1148 return atypes.Length != 0;
1150 int count = args.Count;
1153 atypes = new Type [count];
1155 for (int i = 0; i < count; i++){
1156 TypeExpr te = ((FullNamedExpression) args[i]).ResolveAsTypeTerminal (ec, false);
1162 atypes[i] = te.Type;
1164 if (te.Type.IsSealed && te.Type.IsAbstract) {
1165 Report.Error (718, te.Location, "`{0}': static classes cannot be used as generic arguments",
1166 te.GetSignatureForError ());
1170 if (te.Type.IsPointer || TypeManager.IsSpecialType (te.Type)) {
1171 Report.Error (306, te.Location,
1172 "The type `{0}' may not be used as a type argument",
1173 te.GetSignatureForError ());
1179 atypes = Type.EmptyTypes;
1184 public TypeArguments Clone ()
1186 TypeArguments copy = new TypeArguments ();
1187 foreach (Expression ta in args)
1194 public class TypeParameterName : SimpleName
1196 Attributes attributes;
1199 public TypeParameterName (string name, Attributes attrs, Location loc)
1200 : this (name, attrs, Variance.None, loc)
1204 public TypeParameterName (string name, Attributes attrs, Variance variance, Location loc)
1208 this.variance = variance;
1211 public Attributes OptAttributes {
1217 public Variance Variance {
1225 /// A reference expression to generic type
1227 class GenericTypeExpr : TypeExpr
1230 Type[] gen_params; // TODO: Waiting for constrains check cleanup
1234 // Should be carefully used only with defined generic containers. Type parameters
1235 // can be used as type arguments in this case.
1237 // TODO: This could be GenericTypeExpr specialization
1239 public GenericTypeExpr (DeclSpace gType, Location l)
1241 open_type = gType.TypeBuilder.GetGenericTypeDefinition ();
1243 args = new TypeArguments ();
1244 foreach (TypeParameter type_param in gType.TypeParameters)
1245 args.Add (new TypeParameterExpr (type_param, l));
1251 /// Instantiate the generic type `t' with the type arguments `args'.
1252 /// Use this constructor if you already know the fully resolved
1255 public GenericTypeExpr (Type t, TypeArguments args, Location l)
1257 open_type = t.GetGenericTypeDefinition ();
1263 public TypeArguments TypeArguments {
1264 get { return args; }
1267 public override string GetSignatureForError ()
1269 return TypeManager.CSharpName (type);
1272 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1274 if (eclass != ExprClass.Invalid)
1277 eclass = ExprClass.Type;
1279 if (!args.Resolve (ec))
1282 gen_params = open_type.GetGenericArguments ();
1283 Type[] atypes = args.Arguments;
1285 if (atypes.Length != gen_params.Length) {
1286 Namespace.Error_InvalidNumberOfTypeArguments (open_type, loc);
1291 // Now bind the parameters
1293 type = open_type.MakeGenericType (atypes);
1298 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1299 /// after fully resolving the constructed type.
1301 public bool CheckConstraints (IResolveContext ec)
1303 return ConstraintChecker.CheckConstraints (ec, open_type, gen_params, args.Arguments, loc);
1306 static bool IsVariant (Type type)
1308 return (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) != 0;
1311 static bool IsCovariant (Type type)
1313 return (type.GenericParameterAttributes & GenericParameterAttributes.Covariant) != 0;
1316 static bool IsContravariant (Type type)
1318 return (type.GenericParameterAttributes & GenericParameterAttributes.Contravariant) != 0;
1321 public bool VerifyVariantTypeParameters ()
1323 for (int i = 0; i < args.Count; i++) {
1324 Type argument = args.Arguments[i];
1325 if (argument.IsGenericParameter && IsVariant (argument)) {
1326 if (IsContravariant (argument) && !IsContravariant (gen_params[i])) {
1327 Report.Error (-34, loc, "Contravariant type parameters can only be used " +
1328 "as type arguments in contravariant positions");
1331 else if (IsCovariant (argument) && !IsCovariant (gen_params[i])) {
1332 Report.Error (-35, loc, "Covariant type parameters can only be used " +
1333 "as type arguments in covariant positions");
1342 public override bool CheckAccessLevel (DeclSpace ds)
1344 return ds.CheckAccessLevel (open_type);
1347 public override bool AsAccessible (DeclSpace ds)
1349 foreach (Type t in args.Arguments) {
1350 if (!ds.IsAccessibleAs (t))
1354 return ds.IsAccessibleAs (open_type);
1357 public override bool IsClass {
1358 get { return open_type.IsClass; }
1361 public override bool IsValueType {
1362 get { return TypeManager.IsStruct (open_type); }
1365 public override bool IsInterface {
1366 get { return open_type.IsInterface; }
1369 public override bool IsSealed {
1370 get { return open_type.IsSealed; }
1373 public override bool Equals (object obj)
1375 GenericTypeExpr cobj = obj as GenericTypeExpr;
1379 if ((type == null) || (cobj.type == null))
1382 return type == cobj.type;
1385 public override int GetHashCode ()
1387 return base.GetHashCode ();
1391 public abstract class ConstraintChecker
1393 protected readonly Type[] gen_params;
1394 protected readonly Type[] atypes;
1395 protected readonly Location loc;
1397 protected ConstraintChecker (Type[] gen_params, Type[] atypes, Location loc)
1399 this.gen_params = gen_params;
1400 this.atypes = atypes;
1405 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1406 /// after fully resolving the constructed type.
1408 public bool CheckConstraints (IResolveContext ec)
1410 for (int i = 0; i < gen_params.Length; i++) {
1411 if (!CheckConstraints (ec, i))
1418 protected bool CheckConstraints (IResolveContext ec, int index)
1420 Type atype = atypes [index];
1421 Type ptype = gen_params [index];
1426 Expression aexpr = new EmptyExpression (atype);
1428 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1432 bool is_class, is_struct;
1433 if (atype.IsGenericParameter) {
1434 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1436 if (agc is Constraints)
1437 ((Constraints) agc).Resolve (ec);
1438 is_class = agc.IsReferenceType;
1439 is_struct = agc.IsValueType;
1441 is_class = is_struct = false;
1446 if (!atype.IsGenericType)
1448 is_class = atype.IsClass || atype.IsInterface;
1449 is_struct = TypeManager.IsValueType (atype) && !TypeManager.IsNullableType (atype);
1453 // First, check the `class' and `struct' constraints.
1455 if (gc.HasReferenceTypeConstraint && !is_class) {
1456 Report.Error (452, loc, "The type `{0}' must be " +
1457 "a reference type in order to use it " +
1458 "as type parameter `{1}' in the " +
1459 "generic type or method `{2}'.",
1460 TypeManager.CSharpName (atype),
1461 TypeManager.CSharpName (ptype),
1462 GetSignatureForError ());
1464 } else if (gc.HasValueTypeConstraint && !is_struct) {
1465 Report.Error (453, loc, "The type `{0}' must be a " +
1466 "non-nullable value type in order to use it " +
1467 "as type parameter `{1}' in the " +
1468 "generic type or method `{2}'.",
1469 TypeManager.CSharpName (atype),
1470 TypeManager.CSharpName (ptype),
1471 GetSignatureForError ());
1476 // The class constraint comes next.
1478 if (gc.HasClassConstraint) {
1479 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint))
1484 // Now, check the interface constraints.
1486 if (gc.InterfaceConstraints != null) {
1487 foreach (Type it in gc.InterfaceConstraints) {
1488 if (!CheckConstraint (ec, ptype, aexpr, it))
1494 // Finally, check the constructor constraint.
1497 if (!gc.HasConstructorConstraint)
1500 if (TypeManager.IsBuiltinType (atype) || TypeManager.IsValueType (atype))
1503 if (HasDefaultConstructor (atype))
1506 Report_SymbolRelatedToPreviousError ();
1507 Report.SymbolRelatedToPreviousError (atype);
1508 Report.Error (310, loc, "The type `{0}' must have a public " +
1509 "parameterless constructor in order to use it " +
1510 "as parameter `{1}' in the generic type or " +
1512 TypeManager.CSharpName (atype),
1513 TypeManager.CSharpName (ptype),
1514 GetSignatureForError ());
1518 protected bool CheckConstraint (IResolveContext ec, Type ptype, Expression expr,
1521 if (TypeManager.HasGenericArguments (ctype)) {
1522 Type[] types = TypeManager.GetTypeArguments (ctype);
1524 TypeArguments new_args = new TypeArguments ();
1526 for (int i = 0; i < types.Length; i++) {
1529 if (t.IsGenericParameter) {
1530 int pos = t.GenericParameterPosition;
1533 new_args.Add (new TypeExpression (t, loc));
1536 TypeExpr ct = new GenericTypeExpr (ctype, new_args, loc);
1537 if (ct.ResolveAsTypeStep (ec, false) == null)
1540 } else if (ctype.IsGenericParameter) {
1541 int pos = ctype.GenericParameterPosition;
1542 if (ctype.DeclaringMethod == null) {
1546 ctype = atypes [pos];
1550 if (Convert.ImplicitStandardConversionExists (expr, ctype))
1553 Report_SymbolRelatedToPreviousError ();
1554 Report.SymbolRelatedToPreviousError (expr.Type);
1556 if (TypeManager.IsNullableType (expr.Type) && ctype.IsInterface) {
1557 Report.Error (313, loc,
1558 "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. " +
1559 "The nullable type `{0}' never satisfies interface constraint of type `{3}'",
1560 TypeManager.CSharpName (expr.Type), TypeManager.CSharpName (ptype),
1561 GetSignatureForError (), TypeManager.CSharpName (ctype));
1563 Report.Error (309, loc,
1564 "The type `{0}' must be convertible to `{1}' in order to " +
1565 "use it as parameter `{2}' in the generic type or method `{3}'",
1566 TypeManager.CSharpName (expr.Type), TypeManager.CSharpName (ctype),
1567 TypeManager.CSharpName (ptype), GetSignatureForError ());
1572 static bool HasDefaultConstructor (Type atype)
1574 TypeParameter tparam = TypeManager.LookupTypeParameter (atype);
1575 if (tparam != null) {
1576 if (tparam.GenericConstraints == null)
1579 return tparam.GenericConstraints.HasConstructorConstraint ||
1580 tparam.GenericConstraints.HasValueTypeConstraint;
1583 if (atype.IsAbstract)
1587 atype = TypeManager.DropGenericTypeArguments (atype);
1588 if (atype is TypeBuilder) {
1589 TypeContainer tc = TypeManager.LookupTypeContainer (atype);
1590 if (tc.InstanceConstructors == null) {
1591 atype = atype.BaseType;
1595 foreach (Constructor c in tc.InstanceConstructors) {
1596 if ((c.ModFlags & Modifiers.PUBLIC) == 0)
1598 if ((c.Parameters.FixedParameters != null) &&
1599 (c.Parameters.FixedParameters.Length != 0))
1601 if (c.Parameters.HasArglist || c.Parameters.HasParams)
1608 MemberInfo [] list = TypeManager.MemberLookup (null, null, atype, MemberTypes.Constructor,
1609 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
1610 ConstructorInfo.ConstructorName, null);
1615 foreach (MethodBase mb in list) {
1616 AParametersCollection pd = TypeManager.GetParameterData (mb);
1624 protected abstract string GetSignatureForError ();
1625 protected abstract void Report_SymbolRelatedToPreviousError ();
1627 public static bool CheckConstraints (EmitContext ec, MethodBase definition,
1628 MethodBase instantiated, Location loc)
1630 MethodConstraintChecker checker = new MethodConstraintChecker (
1631 definition, definition.GetGenericArguments (),
1632 instantiated.GetGenericArguments (), loc);
1634 return checker.CheckConstraints (ec);
1637 public static bool CheckConstraints (IResolveContext ec, Type gt, Type[] gen_params,
1638 Type[] atypes, Location loc)
1640 TypeConstraintChecker checker = new TypeConstraintChecker (
1641 gt, gen_params, atypes, loc);
1643 return checker.CheckConstraints (ec);
1646 protected class MethodConstraintChecker : ConstraintChecker
1648 MethodBase definition;
1650 public MethodConstraintChecker (MethodBase definition, Type[] gen_params,
1651 Type[] atypes, Location loc)
1652 : base (gen_params, atypes, loc)
1654 this.definition = definition;
1657 protected override string GetSignatureForError ()
1659 return TypeManager.CSharpSignature (definition);
1662 protected override void Report_SymbolRelatedToPreviousError ()
1664 Report.SymbolRelatedToPreviousError (definition);
1668 protected class TypeConstraintChecker : ConstraintChecker
1672 public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
1674 : base (gen_params, atypes, loc)
1679 protected override string GetSignatureForError ()
1681 return TypeManager.CSharpName (gt);
1684 protected override void Report_SymbolRelatedToPreviousError ()
1686 Report.SymbolRelatedToPreviousError (gt);
1692 /// A generic method definition.
1694 public class GenericMethod : DeclSpace
1696 FullNamedExpression return_type;
1697 ParametersCompiled parameters;
1699 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
1700 FullNamedExpression return_type, ParametersCompiled parameters)
1701 : base (ns, parent, name, null)
1703 this.return_type = return_type;
1704 this.parameters = parameters;
1707 public override TypeBuilder DefineType ()
1709 throw new Exception ();
1712 public override bool Define ()
1714 for (int i = 0; i < TypeParameters.Length; i++)
1715 if (!TypeParameters [i].Resolve (this))
1722 /// Define and resolve the type parameters.
1723 /// We're called from Method.Define().
1725 public bool Define (MethodOrOperator m)
1727 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1728 string[] snames = new string [names.Length];
1729 for (int i = 0; i < names.Length; i++) {
1730 string type_argument_name = names[i].Name;
1731 int idx = parameters.GetParameterIndexByName (type_argument_name);
1735 b = new Block (null);
1737 b.Error_AlreadyDeclaredTypeParameter (parameters [i].Location,
1738 type_argument_name, "method parameter");
1741 snames[i] = type_argument_name;
1744 GenericTypeParameterBuilder[] gen_params = m.MethodBuilder.DefineGenericParameters (snames);
1745 for (int i = 0; i < TypeParameters.Length; i++)
1746 TypeParameters [i].Define (gen_params [i]);
1751 for (int i = 0; i < TypeParameters.Length; i++) {
1752 if (!TypeParameters [i].ResolveType (this))
1760 /// We're called from MethodData.Define() after creating the MethodBuilder.
1762 public bool DefineType (EmitContext ec, MethodBuilder mb,
1763 MethodInfo implementing, bool is_override)
1765 for (int i = 0; i < TypeParameters.Length; i++)
1766 if (!TypeParameters [i].DefineType (
1767 ec, mb, implementing, is_override))
1770 bool ok = parameters.Resolve (ec);
1772 if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec, false) == null))
1778 public void EmitAttributes ()
1780 for (int i = 0; i < TypeParameters.Length; i++)
1781 TypeParameters [i].Emit ();
1783 if (OptAttributes != null)
1784 OptAttributes.Emit ();
1787 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1788 MemberFilter filter, object criteria)
1790 throw new Exception ();
1793 public override MemberCache MemberCache {
1799 public override AttributeTargets AttributeTargets {
1801 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1805 public override string DocCommentHeader {
1806 get { return "M:"; }
1809 public new void VerifyClsCompliance ()
1811 foreach (TypeParameter tp in TypeParameters) {
1812 if (tp.Constraints == null)
1815 tp.Constraints.VerifyClsCompliance ();
1820 public partial class TypeManager
1822 static public Type activator_type;
1824 public static TypeContainer LookupGenericTypeContainer (Type t)
1826 t = DropGenericTypeArguments (t);
1827 return LookupTypeContainer (t);
1831 /// Check whether `a' and `b' may become equal generic types.
1832 /// The algorithm to do that is a little bit complicated.
1834 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_inferred,
1835 Type[] method_inferred)
1837 if (a.IsGenericParameter) {
1839 // If a is an array of a's type, they may never
1843 b = GetElementType (b);
1849 // If b is a generic parameter or an actual type,
1850 // they may become equal:
1852 // class X<T,U> : I<T>, I<U>
1853 // class X<T> : I<T>, I<float>
1855 if (b.IsGenericParameter || !b.IsGenericType) {
1856 int pos = a.GenericParameterPosition;
1857 Type[] args = a.DeclaringMethod != null ? method_inferred : class_inferred;
1858 if (args [pos] == null) {
1863 return args [pos] == a;
1867 // We're now comparing a type parameter with a
1868 // generic instance. They may become equal unless
1869 // the type parameter appears anywhere in the
1870 // generic instance:
1872 // class X<T,U> : I<T>, I<X<U>>
1873 // -> error because you could instanciate it as
1876 // class X<T> : I<T>, I<X<T>> -> ok
1879 Type[] bargs = GetTypeArguments (b);
1880 for (int i = 0; i < bargs.Length; i++) {
1881 if (a.Equals (bargs [i]))
1888 if (b.IsGenericParameter)
1889 return MayBecomeEqualGenericTypes (b, a, class_inferred, method_inferred);
1892 // At this point, neither a nor b are a type parameter.
1894 // If one of them is a generic instance, let
1895 // MayBecomeEqualGenericInstances() compare them (if the
1896 // other one is not a generic instance, they can never
1900 if (a.IsGenericType || b.IsGenericType)
1901 return MayBecomeEqualGenericInstances (a, b, class_inferred, method_inferred);
1904 // If both of them are arrays.
1907 if (a.IsArray && b.IsArray) {
1908 if (a.GetArrayRank () != b.GetArrayRank ())
1911 a = GetElementType (a);
1912 b = GetElementType (b);
1914 return MayBecomeEqualGenericTypes (a, b, class_inferred, method_inferred);
1918 // Ok, two ordinary types.
1921 return a.Equals (b);
1925 // Checks whether two generic instances may become equal for some
1926 // particular instantiation (26.3.1).
1928 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
1929 Type[] class_inferred,
1930 Type[] method_inferred)
1932 if (!a.IsGenericType || !b.IsGenericType)
1934 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
1937 return MayBecomeEqualGenericInstances (
1938 GetTypeArguments (a), GetTypeArguments (b), class_inferred, method_inferred);
1941 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
1942 Type[] class_inferred,
1943 Type[] method_inferred)
1945 if (aargs.Length != bargs.Length)
1948 for (int i = 0; i < aargs.Length; i++) {
1949 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_inferred, method_inferred))
1957 /// Type inference. Try to infer the type arguments from `method',
1958 /// which is invoked with the arguments `arguments'. This is used
1959 /// when resolving an Invocation or a DelegateInvocation and the user
1960 /// did not explicitly specify type arguments.
1962 public static int InferTypeArguments (EmitContext ec,
1963 ArrayList arguments,
1964 ref MethodBase method)
1966 ATypeInference ti = ATypeInference.CreateInstance (arguments);
1967 Type[] i_args = ti.InferMethodArguments (ec, method);
1969 return ti.InferenceScore;
1971 if (i_args.Length == 0)
1974 method = ((MethodInfo) method).MakeGenericMethod (i_args);
1981 public static bool InferTypeArguments (AParametersCollection apd,
1982 ref MethodBase method)
1984 if (!TypeManager.IsGenericMethod (method))
1987 ATypeInference ti = ATypeInference.CreateInstance (ArrayList.Adapter (apd.Types));
1988 Type[] i_args = ti.InferDelegateArguments (method);
1992 method = ((MethodInfo) method).MakeGenericMethod (i_args);
1997 abstract class ATypeInference
1999 protected readonly ArrayList arguments;
2000 protected readonly int arg_count;
2002 protected ATypeInference (ArrayList arguments)
2004 this.arguments = arguments;
2005 if (arguments != null)
2006 arg_count = arguments.Count;
2009 public static ATypeInference CreateInstance (ArrayList arguments)
2011 if (RootContext.Version == LanguageVersion.ISO_2)
2012 return new TypeInferenceV2 (arguments);
2014 return new TypeInferenceV3 (arguments);
2017 public virtual int InferenceScore {
2019 return int.MaxValue;
2023 public abstract Type[] InferMethodArguments (EmitContext ec, MethodBase method);
2024 public abstract Type[] InferDelegateArguments (MethodBase method);
2028 // Implements C# 2.0 type inference
2030 class TypeInferenceV2 : ATypeInference
2032 public TypeInferenceV2 (ArrayList arguments)
2037 public override Type[] InferDelegateArguments (MethodBase method)
2039 AParametersCollection pd = TypeManager.GetParameterData (method);
2040 if (arg_count != pd.Count)
2043 Type[] method_args = method.GetGenericArguments ();
2044 Type[] inferred_types = new Type[method_args.Length];
2046 Type[] param_types = new Type[pd.Count];
2047 Type[] arg_types = (Type[])arguments.ToArray (typeof (Type));
2049 for (int i = 0; i < arg_count; i++) {
2050 param_types[i] = pd.Types [i];
2053 if (!InferTypeArguments (param_types, arg_types, inferred_types))
2056 return inferred_types;
2059 public override Type[] InferMethodArguments (EmitContext ec, MethodBase method)
2061 AParametersCollection pd = TypeManager.GetParameterData (method);
2062 Type[] method_generic_args = method.GetGenericArguments ();
2063 Type [] inferred_types = new Type [method_generic_args.Length];
2064 Type[] arg_types = new Type [pd.Count];
2066 int a_count = arg_types.Length;
2070 for (int i = 0; i < a_count; i++) {
2071 Argument a = (Argument) arguments[i];
2072 if (a.Expr is NullLiteral || a.Expr is MethodGroupExpr || a.Expr is AnonymousMethodExpression)
2075 if (!TypeInferenceV2.UnifyType (pd.Types [i], a.Type, inferred_types))
2080 Type element_type = TypeManager.GetElementType (pd.Types [a_count]);
2081 for (int i = a_count; i < arg_count; i++) {
2082 Argument a = (Argument) arguments [i];
2083 if (a.Expr is NullLiteral || a.Expr is MethodGroupExpr || a.Expr is AnonymousMethodExpression)
2086 if (!TypeInferenceV2.UnifyType (element_type, a.Type, inferred_types))
2091 for (int i = 0; i < inferred_types.Length; i++)
2092 if (inferred_types [i] == null)
2095 return inferred_types;
2098 static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
2099 Type[] inferred_types)
2101 for (int i = 0; i < arg_types.Length; i++) {
2102 if (arg_types[i] == null)
2105 if (!UnifyType (param_types[i], arg_types[i], inferred_types))
2109 for (int i = 0; i < inferred_types.Length; ++i)
2110 if (inferred_types[i] == null)
2116 public static bool UnifyType (Type pt, Type at, Type[] inferred)
2118 if (pt.IsGenericParameter) {
2119 if (pt.DeclaringMethod == null)
2122 int pos = pt.GenericParameterPosition;
2124 if (inferred [pos] == null)
2125 inferred [pos] = at;
2127 return inferred [pos] == at;
2130 if (!pt.ContainsGenericParameters) {
2131 if (at.ContainsGenericParameters)
2132 return UnifyType (at, pt, inferred);
2139 if (at.GetArrayRank () != pt.GetArrayRank ())
2142 return UnifyType (TypeManager.GetElementType (pt), TypeManager.GetElementType (at), inferred);
2145 if (!pt.IsGenericType)
2148 Type gt = pt.GetGenericTypeDefinition ();
2149 if ((gt != TypeManager.generic_ilist_type) && (gt != TypeManager.generic_icollection_type) &&
2150 (gt != TypeManager.generic_ienumerable_type))
2153 Type[] args = TypeManager.GetTypeArguments (pt);
2154 return UnifyType (args[0], at.GetElementType (), inferred);
2159 (pt.GetArrayRank () != at.GetArrayRank ()))
2162 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2165 if (pt.IsByRef && at.IsByRef)
2166 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2167 ArrayList list = new ArrayList ();
2168 if (at.IsGenericType)
2170 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
2173 list.AddRange (TypeManager.GetInterfaces (at));
2175 foreach (Type type in list) {
2176 if (!type.IsGenericType)
2179 if (TypeManager.DropGenericTypeArguments (pt) != TypeManager.DropGenericTypeArguments (type))
2182 if (!UnifyTypes (pt.GetGenericArguments (), type.GetGenericArguments (), inferred))
2189 static bool UnifyTypes (Type[] pts, Type[] ats, Type[] inferred)
2191 for (int i = 0; i < ats.Length; i++) {
2192 if (!UnifyType (pts [i], ats [i], inferred))
2200 // Implements C# 3.0 type inference
2202 class TypeInferenceV3 : ATypeInference
2205 // Tracks successful rate of type inference
2207 int score = int.MaxValue;
2209 public TypeInferenceV3 (ArrayList arguments)
2214 public override int InferenceScore {
2220 public override Type[] InferDelegateArguments (MethodBase method)
2222 AParametersCollection pd = TypeManager.GetParameterData (method);
2223 if (arg_count != pd.Count)
2226 Type[] d_gargs = method.GetGenericArguments ();
2227 TypeInferenceContext context = new TypeInferenceContext (d_gargs);
2229 // A lower-bound inference is made from each argument type Uj of D
2230 // to the corresponding parameter type Tj of M
2231 for (int i = 0; i < arg_count; ++i) {
2232 Type t = pd.Types [i];
2233 if (!t.IsGenericParameter)
2236 context.LowerBoundInference ((Type)arguments[i], t);
2239 if (!context.FixAllTypes ())
2242 return context.InferredTypeArguments;
2245 public override Type[] InferMethodArguments (EmitContext ec, MethodBase method)
2247 Type[] method_generic_args = method.GetGenericArguments ();
2248 TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2249 if (!context.UnfixedVariableExists)
2250 return Type.EmptyTypes;
2252 AParametersCollection pd = TypeManager.GetParameterData (method);
2253 if (!InferInPhases (ec, context, pd))
2256 return context.InferredTypeArguments;
2260 // Implements method type arguments inference
2262 bool InferInPhases (EmitContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
2264 int params_arguments_start;
2265 if (methodParameters.HasParams) {
2266 params_arguments_start = methodParameters.Count - 1;
2268 params_arguments_start = arg_count;
2271 Type [] ptypes = methodParameters.Types;
2274 // The first inference phase
2276 Type method_parameter = null;
2277 for (int i = 0; i < arg_count; i++) {
2278 Argument a = (Argument) arguments [i];
2280 if (i < params_arguments_start) {
2281 method_parameter = methodParameters.Types [i];
2282 } else if (i == params_arguments_start) {
2283 if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2284 method_parameter = methodParameters.Types [params_arguments_start];
2286 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2288 ptypes = (Type[]) ptypes.Clone ();
2289 ptypes [i] = method_parameter;
2293 // When a lambda expression, an anonymous method
2294 // is used an explicit argument type inference takes a place
2296 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2298 if (am.ExplicitTypeInference (tic, method_parameter))
2303 if (a.Expr.Type == TypeManager.null_type)
2307 // Otherwise an output type inference is made
2309 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2313 // Part of the second phase but because it happens only once
2314 // we don't need to call it in cycle
2316 bool fixed_any = false;
2317 if (!tic.FixIndependentTypeArguments (ptypes, ref fixed_any))
2320 return DoSecondPhase (ec, tic, ptypes, !fixed_any);
2323 bool DoSecondPhase (EmitContext ec, TypeInferenceContext tic, Type[] methodParameters, bool fixDependent)
2325 bool fixed_any = false;
2326 if (fixDependent && !tic.FixDependentTypes (ref fixed_any))
2329 // If no further unfixed type variables exist, type inference succeeds
2330 if (!tic.UnfixedVariableExists)
2333 if (!fixed_any && fixDependent)
2336 // For all arguments where the corresponding argument output types
2337 // contain unfixed type variables but the input types do not,
2338 // an output type inference is made
2339 for (int i = 0; i < arg_count; i++) {
2341 // Align params arguments
2342 Type t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
2344 if (!TypeManager.IsDelegateType (t_i)) {
2345 if (TypeManager.DropGenericTypeArguments (t_i) != TypeManager.expression_type)
2348 t_i = t_i.GetGenericArguments () [0];
2351 MethodInfo mi = Delegate.GetInvokeMethod (t_i, t_i);
2352 Type rtype = mi.ReturnType;
2355 // Blablabla, because reflection does not work with dynamic types
2356 Type[] g_args = t_i.GetGenericArguments ();
2357 rtype = g_args[rtype.GenericParameterPosition];
2360 if (tic.IsReturnTypeNonDependent (mi, rtype))
2361 score -= tic.OutputTypeInference (ec, ((Argument) arguments [i]).Expr, t_i);
2365 return DoSecondPhase (ec, tic, methodParameters, true);
2369 public class TypeInferenceContext
2371 readonly Type[] unfixed_types;
2372 readonly Type[] fixed_types;
2373 readonly ArrayList[] bounds;
2376 public TypeInferenceContext (Type[] typeArguments)
2378 if (typeArguments.Length == 0)
2379 throw new ArgumentException ("Empty generic arguments");
2381 fixed_types = new Type [typeArguments.Length];
2382 for (int i = 0; i < typeArguments.Length; ++i) {
2383 if (typeArguments [i].IsGenericParameter) {
2384 if (bounds == null) {
2385 bounds = new ArrayList [typeArguments.Length];
2386 unfixed_types = new Type [typeArguments.Length];
2388 unfixed_types [i] = typeArguments [i];
2390 fixed_types [i] = typeArguments [i];
2395 public Type[] InferredTypeArguments {
2401 void AddToBounds (Type t, int index)
2404 // Some types cannot be used as type arguments
2406 if (t == TypeManager.void_type || t.IsPointer)
2409 ArrayList a = bounds [index];
2411 a = new ArrayList ();
2419 // SPEC: does not cover type inference using constraints
2421 //if (TypeManager.IsGenericParameter (t)) {
2422 // GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
2423 // if (constraints != null) {
2424 // //if (constraints.EffectiveBaseClass != null)
2425 // // t = constraints.EffectiveBaseClass;
2431 bool AllTypesAreFixed (Type[] types)
2433 foreach (Type t in types) {
2434 if (t.IsGenericParameter) {
2440 if (t.IsGenericType)
2441 return AllTypesAreFixed (t.GetGenericArguments ());
2448 // 26.3.3.8 Exact Inference
2450 public int ExactInference (Type u, Type v)
2452 // If V is an array type
2457 if (u.GetArrayRank () != v.GetArrayRank ())
2460 return ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
2463 // If V is constructed type and U is constructed type
2464 if (v.IsGenericType && !v.IsGenericTypeDefinition) {
2465 if (!u.IsGenericType)
2468 Type [] ga_u = u.GetGenericArguments ();
2469 Type [] ga_v = v.GetGenericArguments ();
2470 if (ga_u.Length != ga_v.Length)
2474 for (int i = 0; i < ga_u.Length; ++i)
2475 score += ExactInference (ga_u [i], ga_v [i]);
2477 return score > 0 ? 1 : 0;
2480 // If V is one of the unfixed type arguments
2481 int pos = IsUnfixed (v);
2485 AddToBounds (u, pos);
2489 public bool FixAllTypes ()
2491 for (int i = 0; i < unfixed_types.Length; ++i) {
2499 // All unfixed type variables Xi are fixed for which all of the following hold:
2500 // a, There is at least one type variable Xj that depends on Xi
2501 // b, Xi has a non-empty set of bounds
2503 public bool FixDependentTypes (ref bool fixed_any)
2505 for (int i = 0; i < unfixed_types.Length; ++i) {
2506 if (unfixed_types[i] == null)
2509 if (bounds[i] == null)
2522 // All unfixed type variables Xi which depend on no Xj are fixed
2524 public bool FixIndependentTypeArguments (Type[] methodParameters, ref bool fixed_any)
2526 ArrayList types_to_fix = new ArrayList (unfixed_types);
2527 for (int i = 0; i < methodParameters.Length; ++i) {
2528 Type t = methodParameters[i];
2530 if (!TypeManager.IsDelegateType (t)) {
2531 if (TypeManager.DropGenericTypeArguments (t) != TypeManager.expression_type)
2534 t = t.GetGenericArguments () [0];
2537 if (t.IsGenericParameter)
2540 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
2541 Type rtype = invoke.ReturnType;
2542 if (!rtype.IsGenericParameter && !rtype.IsGenericType)
2546 // Blablabla, because reflection does not work with dynamic types
2547 if (rtype.IsGenericParameter) {
2548 Type [] g_args = t.GetGenericArguments ();
2549 rtype = g_args [rtype.GenericParameterPosition];
2552 // Remove dependent types, they cannot be fixed yet
2553 RemoveDependentTypes (types_to_fix, rtype);
2556 foreach (Type t in types_to_fix) {
2560 int idx = IsUnfixed (t);
2561 if (idx >= 0 && !FixType (idx)) {
2566 fixed_any = types_to_fix.Count > 0;
2573 public bool FixType (int i)
2575 // It's already fixed
2576 if (unfixed_types[i] == null)
2577 throw new InternalErrorException ("Type argument has been already fixed");
2582 ArrayList candidates = (ArrayList)bounds [i];
2583 if (candidates == null)
2586 if (candidates.Count == 1) {
2587 unfixed_types[i] = null;
2588 fixed_types[i] = (Type)candidates[0];
2593 // Determines a unique type from which there is
2594 // a standard implicit conversion to all the other
2597 Type best_candidate = null;
2599 int candidates_count = candidates.Count;
2600 for (int ci = 0; ci < candidates_count; ++ci) {
2601 Type candidate = (Type)candidates [ci];
2602 for (cii = 0; cii < candidates_count; ++cii) {
2606 if (!Convert.ImplicitConversionExists (null,
2607 new TypeExpression ((Type)candidates [cii], Location.Null), candidate)) {
2612 if (cii != candidates_count)
2615 if (best_candidate != null)
2618 best_candidate = candidate;
2621 if (best_candidate == null)
2624 unfixed_types[i] = null;
2625 fixed_types[i] = best_candidate;
2630 // Uses inferred types to inflate delegate type argument
2632 public Type InflateGenericArgument (Type parameter)
2634 if (parameter.IsGenericParameter) {
2636 // Inflate method generic argument (MVAR) only
2638 if (parameter.DeclaringMethod == null)
2641 return fixed_types [parameter.GenericParameterPosition];
2644 if (parameter.IsGenericType) {
2645 Type [] parameter_targs = parameter.GetGenericArguments ();
2646 for (int ii = 0; ii < parameter_targs.Length; ++ii) {
2647 parameter_targs [ii] = InflateGenericArgument (parameter_targs [ii]);
2649 return parameter.GetGenericTypeDefinition ().MakeGenericType (parameter_targs);
2656 // Tests whether all delegate input arguments are fixed and generic output type
2657 // requires output type inference
2659 public bool IsReturnTypeNonDependent (MethodInfo invoke, Type returnType)
2661 if (returnType.IsGenericParameter) {
2662 if (IsFixed (returnType))
2664 } else if (returnType.IsGenericType) {
2665 if (TypeManager.IsDelegateType (returnType)) {
2666 invoke = Delegate.GetInvokeMethod (returnType, returnType);
2667 return IsReturnTypeNonDependent (invoke, invoke.ReturnType);
2670 Type[] g_args = returnType.GetGenericArguments ();
2672 // At least one unfixed return type has to exist
2673 if (AllTypesAreFixed (g_args))
2679 // All generic input arguments have to be fixed
2680 AParametersCollection d_parameters = TypeManager.GetParameterData (invoke);
2681 return AllTypesAreFixed (d_parameters.Types);
2684 bool IsFixed (Type type)
2686 return IsUnfixed (type) == -1;
2689 int IsUnfixed (Type type)
2691 if (!type.IsGenericParameter)
2694 //return unfixed_types[type.GenericParameterPosition] != null;
2695 for (int i = 0; i < unfixed_types.Length; ++i) {
2696 if (unfixed_types [i] == type)
2704 // 26.3.3.9 Lower-bound Inference
2706 public int LowerBoundInference (Type u, Type v)
2708 // If V is one of the unfixed type arguments
2709 int pos = IsUnfixed (v);
2711 AddToBounds (u, pos);
2715 // If U is an array type
2717 int u_dim = u.GetArrayRank ();
2719 Type u_e = TypeManager.GetElementType (u);
2722 if (u_dim != v.GetArrayRank ())
2725 v_e = TypeManager.GetElementType (v);
2728 return LowerBoundInference (u_e, v_e);
2731 return ExactInference (u_e, v_e);
2737 if (v.IsGenericType) {
2738 Type g_v = v.GetGenericTypeDefinition ();
2739 if ((g_v != TypeManager.generic_ilist_type) && (g_v != TypeManager.generic_icollection_type) &&
2740 (g_v != TypeManager.generic_ienumerable_type))
2743 v_e = TypeManager.GetTypeArguments (v)[0];
2746 return LowerBoundInference (u_e, v_e);
2749 return ExactInference (u_e, v_e);
2751 } else if (v.IsGenericType && !v.IsGenericTypeDefinition) {
2753 // if V is a constructed type C<V1..Vk> and there is a unique set of types U1..Uk
2754 // such that a standard implicit conversion exists from U to C<U1..Uk> then an exact
2755 // inference is made from each Ui for the corresponding Vi
2757 ArrayList u_candidates = new ArrayList ();
2758 if (u.IsGenericType)
2759 u_candidates.Add (u);
2761 for (Type t = u.BaseType; t != null; t = t.BaseType) {
2762 if (t.IsGenericType && !t.IsGenericTypeDefinition)
2763 u_candidates.Add (t);
2766 // TODO: Implement GetGenericInterfaces only and remove
2767 // the if from foreach
2768 u_candidates.AddRange (TypeManager.GetInterfaces (u));
2770 Type open_v = v.GetGenericTypeDefinition ();
2771 Type [] unique_candidate_targs = null;
2772 Type [] ga_v = v.GetGenericArguments ();
2773 foreach (Type u_candidate in u_candidates) {
2774 if (!u_candidate.IsGenericType || u_candidate.IsGenericTypeDefinition)
2777 if (TypeManager.DropGenericTypeArguments (u_candidate) != open_v)
2781 // The unique set of types U1..Uk means that if we have an interface C<T>,
2782 // class U: C<int>, C<long> then no type inference is made when inferring
2783 // from U to C<T> because T could be int or long
2785 if (unique_candidate_targs != null) {
2786 Type[] second_unique_candidate_targs = u_candidate.GetGenericArguments ();
2787 if (TypeManager.IsEqual (unique_candidate_targs, second_unique_candidate_targs)) {
2788 unique_candidate_targs = second_unique_candidate_targs;
2793 // This should always cause type inference failure
2799 unique_candidate_targs = u_candidate.GetGenericArguments ();
2802 if (unique_candidate_targs != null) {
2804 for (int i = 0; i < unique_candidate_targs.Length; ++i)
2805 if (ExactInference (unique_candidate_targs [i], ga_v [i]) == 0)
2815 // 26.3.3.6 Output Type Inference
2817 public int OutputTypeInference (EmitContext ec, Expression e, Type t)
2819 // If e is a lambda or anonymous method with inferred return type
2820 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
2822 Type rt = ame.InferReturnType (ec, this, t);
2823 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
2826 AParametersCollection pd = TypeManager.GetParameterData (invoke);
2827 return ame.Parameters.Count == pd.Count ? 1 : 0;
2830 Type rtype = invoke.ReturnType;
2832 // Blablabla, because reflection does not work with dynamic types
2833 Type [] g_args = t.GetGenericArguments ();
2834 rtype = g_args [rtype.GenericParameterPosition];
2836 return LowerBoundInference (rt, rtype) + 1;
2840 // if E is a method group and T is a delegate type or expression tree type
2841 // return type Tb with parameter types T1..Tk and return type Tb, and overload
2842 // resolution of E with the types T1..Tk yields a single method with return type U,
2843 // then a lower-bound inference is made from U for Tb.
2845 if (e is MethodGroupExpr) {
2846 // TODO: Or expression tree
2847 if (!TypeManager.IsDelegateType (t))
2850 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
2851 Type rtype = invoke.ReturnType;
2853 // Blablabla, because reflection does not work with dynamic types
2854 Type [] g_args = t.GetGenericArguments ();
2855 rtype = g_args [rtype.GenericParameterPosition];
2858 if (!TypeManager.IsGenericType (rtype))
2861 MethodGroupExpr mg = (MethodGroupExpr) e;
2862 ArrayList args = DelegateCreation.CreateDelegateMethodArguments (invoke, e.Location);
2863 mg = mg.OverloadResolve (ec, ref args, true, e.Location);
2867 // TODO: What should happen when return type is of generic type ?
2868 throw new NotImplementedException ();
2869 // return LowerBoundInference (null, rtype) + 1;
2873 // if e is an expression with type U, then
2874 // a lower-bound inference is made from U for T
2876 return LowerBoundInference (e.Type, t) * 2;
2879 void RemoveDependentTypes (ArrayList types, Type returnType)
2881 int idx = IsUnfixed (returnType);
2887 if (returnType.IsGenericType) {
2888 foreach (Type t in returnType.GetGenericArguments ()) {
2889 RemoveDependentTypes (types, t);
2894 public bool UnfixedVariableExists {
2896 if (unfixed_types == null)
2899 foreach (Type ut in unfixed_types)