2010-03-05 Rodrigo Kumpera <rkumpera@novell.com>
[mcs.git] / mcs / generic.cs
blob2c468dd7ca7ff54f0db30b6c95200e0d9197404a
1 //
2 // generic.cs: Generics support
3 //
4 // Authors: Martin Baulig (martin@ximian.com)
5 // Miguel de Icaza (miguel@ximian.com)
6 // Marek Safar (marek.safar@gmail.com)
7 //
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 //
10 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004-2008 Novell, Inc
13 using System;
14 using System.Reflection;
15 using System.Reflection.Emit;
16 using System.Globalization;
17 using System.Collections.Generic;
18 using System.Text;
20 namespace Mono.CSharp {
22 /// <summary>
23 /// Abstract base class for type parameter constraints.
24 /// The type parameter can come from a generic type definition or from reflection.
25 /// </summary>
26 public abstract class GenericConstraints {
27 public abstract GenericParameterAttributes Attributes {
28 get;
31 public bool HasConstructorConstraint {
32 get { return (Attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0; }
35 public bool HasReferenceTypeConstraint {
36 get { return (Attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0; }
39 public bool HasValueTypeConstraint {
40 get { return (Attributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0; }
43 public virtual bool HasClassConstraint {
44 get { return ClassConstraint != null; }
47 public abstract Type ClassConstraint {
48 get;
51 public abstract Type[] InterfaceConstraints {
52 get;
55 public abstract Type EffectiveBaseClass {
56 get;
59 // <summary>
60 // Returns whether the type parameter is "known to be a reference type".
61 // </summary>
62 public virtual bool IsReferenceType {
63 get {
64 if (HasReferenceTypeConstraint)
65 return true;
66 if (HasValueTypeConstraint)
67 return false;
69 if (ClassConstraint != null) {
70 if (ClassConstraint.IsValueType)
71 return false;
73 if (ClassConstraint != TypeManager.object_type)
74 return true;
77 foreach (Type t in InterfaceConstraints) {
78 if (!t.IsGenericParameter)
79 continue;
81 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
82 if ((gc != null) && gc.IsReferenceType)
83 return true;
86 return false;
90 // <summary>
91 // Returns whether the type parameter is "known to be a value type".
92 // </summary>
93 public virtual bool IsValueType {
94 get {
95 if (HasValueTypeConstraint)
96 return true;
97 if (HasReferenceTypeConstraint)
98 return false;
100 if (ClassConstraint != null) {
101 if (!TypeManager.IsValueType (ClassConstraint))
102 return false;
104 if (ClassConstraint != TypeManager.value_type)
105 return true;
108 foreach (Type t in InterfaceConstraints) {
109 if (!t.IsGenericParameter)
110 continue;
112 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
113 if ((gc != null) && gc.IsValueType)
114 return true;
117 return false;
122 public class ReflectionConstraints : GenericConstraints
124 GenericParameterAttributes attrs;
125 Type base_type;
126 Type class_constraint;
127 Type[] iface_constraints;
129 public static GenericConstraints GetConstraints (Type t)
131 Type[] constraints = t.GetGenericParameterConstraints ();
132 GenericParameterAttributes attrs = t.GenericParameterAttributes;
133 if (constraints.Length == 0 && attrs == GenericParameterAttributes.None)
134 return null;
135 return new ReflectionConstraints (t.Name, constraints, attrs);
138 private ReflectionConstraints (string name, Type[] constraints, GenericParameterAttributes attrs)
140 this.attrs = attrs;
142 int interface_constraints_pos = 0;
143 if ((attrs & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
144 base_type = TypeManager.value_type;
145 interface_constraints_pos = 1;
146 } else if ((attrs & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
147 if (constraints.Length > 0 && constraints[0].IsClass) {
148 class_constraint = base_type = constraints[0];
149 interface_constraints_pos = 1;
150 } else {
151 base_type = TypeManager.object_type;
153 } else {
154 base_type = TypeManager.object_type;
157 if (constraints.Length > interface_constraints_pos) {
158 if (interface_constraints_pos == 0) {
159 iface_constraints = constraints;
160 } else {
161 iface_constraints = new Type[constraints.Length - interface_constraints_pos];
162 Array.Copy (constraints, interface_constraints_pos, iface_constraints, 0, iface_constraints.Length);
164 } else {
165 iface_constraints = Type.EmptyTypes;
169 public override GenericParameterAttributes Attributes
171 get { return attrs; }
174 public override Type ClassConstraint
176 get { return class_constraint; }
179 public override Type EffectiveBaseClass
181 get { return base_type; }
184 public override Type[] InterfaceConstraints
186 get { return iface_constraints; }
190 public enum Variance
193 // Don't add or modify internal values, they are used as -/+ calculation signs
195 None = 0,
196 Covariant = 1,
197 Contravariant = -1
200 [Flags]
201 public enum SpecialConstraint
203 None = 0,
204 Constructor = 1 << 2,
205 Class = 1 << 3,
206 Struct = 1 << 4
209 public class SpecialContraintExpr : FullNamedExpression
211 public SpecialContraintExpr (SpecialConstraint constraint, Location loc)
213 this.loc = loc;
214 this.Constraint = constraint;
217 public SpecialConstraint Constraint { get; private set; }
219 protected override Expression DoResolve (ResolveContext rc)
221 throw new NotImplementedException ();
226 // A set of parsed constraints for a type parameter
228 public class Constraints : GenericConstraints
230 SimpleMemberName tparam;
231 List<FullNamedExpression> constraints;
232 Location loc;
233 GenericParameterAttributes attrs;
234 TypeExpr class_constraint;
235 List<TypeExpr> iface_constraints;
236 List<TypeExpr> type_param_constraints;
237 int num_constraints;
238 Type class_constraint_type;
239 Type[] iface_constraint_types;
240 Type effective_base_type;
241 bool resolved;
242 bool resolved_types;
245 // name is the identifier, constraints is an arraylist of
246 // Expressions (with types) or `true' for the constructor constraint.
248 public Constraints (SimpleMemberName tparam, List<FullNamedExpression> constraints, Location loc)
250 this.tparam = tparam;
251 this.constraints = constraints;
252 this.loc = loc;
255 #region Properties
257 public SimpleMemberName TypeParameter {
258 get {
259 return tparam;
263 #endregion
265 public Constraints Clone ()
267 return new Constraints (tparam, constraints, loc);
270 /// <summary>
271 /// Resolve the constraints - but only resolve things into Expression's, not
272 /// into actual types.
273 /// </summary>
274 public bool Resolve (MemberCore ec, TypeParameter tp, Report Report)
276 if (resolved)
277 return true;
279 if (ec == null)
280 return false;
282 iface_constraints = new List<TypeExpr> (2); // TODO: Too expensive allocation
283 type_param_constraints = new List<TypeExpr> ();
285 foreach (var obj in constraints) {
287 if (obj is SpecialContraintExpr) {
288 SpecialConstraint sc = ((SpecialContraintExpr) obj).Constraint;
290 if (sc == SpecialConstraint.Constructor) {
291 if (!HasValueTypeConstraint) {
292 attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
293 continue;
297 if (sc == SpecialConstraint.Class)
298 attrs |= GenericParameterAttributes.ReferenceTypeConstraint;
299 else
300 attrs |= GenericParameterAttributes.NotNullableValueTypeConstraint;
301 continue;
304 int errors = Report.Errors;
305 FullNamedExpression fn = obj.ResolveAsTypeStep (ec, false);
307 if (fn == null) {
308 if (errors != Report.Errors)
309 return false;
311 NamespaceEntry.Error_NamespaceNotFound (loc, obj.GetSignatureForError (), Report);
312 return false;
315 TypeExpr expr;
316 GenericTypeExpr cexpr = fn as GenericTypeExpr;
317 if (cexpr != null) {
318 expr = cexpr.ResolveAsBaseTerminal (ec, false);
319 if (expr != null && cexpr.HasDynamicArguments ()) {
320 Report.Error (1968, cexpr.Location,
321 "A constraint cannot be the dynamic type `{0}'",
322 cexpr.GetSignatureForError ());
323 expr = null;
325 } else
326 expr = ((Expression) obj).ResolveAsTypeTerminal (ec, false);
328 if ((expr == null) || (expr.Type == null))
329 return false;
331 if (TypeManager.IsGenericParameter (expr.Type))
332 type_param_constraints.Add (expr);
333 else if (expr.IsInterface)
334 iface_constraints.Add (expr);
335 else if (class_constraint != null || iface_constraints.Count != 0) {
336 Report.Error (406, loc,
337 "The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
338 expr.GetSignatureForError ());
339 return false;
340 } else if (HasReferenceTypeConstraint || HasValueTypeConstraint) {
341 Report.Error (450, loc, "`{0}': cannot specify both " +
342 "a constraint class and the `class' " +
343 "or `struct' constraint", expr.GetSignatureForError ());
344 return false;
345 } else
346 class_constraint = expr;
350 // Checks whether each generic method parameter constraint type
351 // is valid with respect to T
353 if (tp != null && tp.Type.DeclaringMethod != null) {
354 TypeManager.CheckTypeVariance (expr.Type, Variance.Contravariant, ec as MemberCore);
357 if (!ec.IsAccessibleAs (fn.Type)) {
358 Report.SymbolRelatedToPreviousError (fn.Type);
359 Report.Error (703, loc,
360 "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
361 fn.GetSignatureForError (), ec.GetSignatureForError ());
364 num_constraints++;
367 var list = new List<Type> ();
368 foreach (TypeExpr iface_constraint in iface_constraints) {
369 foreach (Type type in list) {
370 if (!type.Equals (iface_constraint.Type))
371 continue;
373 Report.Error (405, loc,
374 "Duplicate constraint `{0}' for type " +
375 "parameter `{1}'.", iface_constraint.GetSignatureForError (),
376 tparam.Value);
377 return false;
380 list.Add (iface_constraint.Type);
383 foreach (TypeExpr expr in type_param_constraints) {
384 foreach (Type type in list) {
385 if (!type.Equals (expr.Type))
386 continue;
388 Report.Error (405, loc,
389 "Duplicate constraint `{0}' for type " +
390 "parameter `{1}'.", expr.GetSignatureForError (), tparam.Value);
391 return false;
394 list.Add (expr.Type);
397 iface_constraint_types = new Type [list.Count];
398 list.CopyTo (iface_constraint_types, 0);
400 if (class_constraint != null) {
401 class_constraint_type = class_constraint.Type;
402 if (class_constraint_type == null)
403 return false;
405 if (class_constraint_type.IsSealed) {
406 if (class_constraint_type.IsAbstract)
408 Report.Error (717, loc, "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
409 TypeManager.CSharpName (class_constraint_type));
411 else
413 Report.Error (701, loc, "`{0}' is not a valid constraint. A constraint must be an interface, " +
414 "a non-sealed class or a type parameter", TypeManager.CSharpName(class_constraint_type));
416 return false;
419 if ((class_constraint_type == TypeManager.array_type) ||
420 (class_constraint_type == TypeManager.delegate_type) ||
421 (class_constraint_type == TypeManager.enum_type) ||
422 (class_constraint_type == TypeManager.value_type) ||
423 (class_constraint_type == TypeManager.object_type) ||
424 class_constraint_type == TypeManager.multicast_delegate_type) {
425 Report.Error (702, loc,
426 "A constraint cannot be special class `{0}'",
427 TypeManager.CSharpName (class_constraint_type));
428 return false;
431 if (TypeManager.IsDynamicType (class_constraint_type)) {
432 Report.Error (1967, loc, "A constraint cannot be the dynamic type");
433 return false;
437 if (class_constraint_type != null)
438 effective_base_type = class_constraint_type;
439 else if (HasValueTypeConstraint)
440 effective_base_type = TypeManager.value_type;
441 else
442 effective_base_type = TypeManager.object_type;
444 if ((attrs & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0)
445 attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
447 resolved = true;
448 return true;
451 bool CheckTypeParameterConstraints (Type tparam, ref TypeExpr prevConstraint, List<Type> seen, Report Report)
453 seen.Add (tparam);
455 Constraints constraints = TypeManager.LookupTypeParameter (tparam).Constraints;
456 if (constraints == null)
457 return true;
459 if (constraints.HasValueTypeConstraint) {
460 Report.Error (456, loc,
461 "Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
462 tparam.Name, this.tparam.Value);
463 return false;
467 // Checks whether there are no conflicts between type parameter constraints
469 // class Foo<T, U>
470 // where T : A
471 // where U : A, B // A and B are not convertible
473 if (constraints.HasClassConstraint) {
474 if (prevConstraint != null) {
475 Type t2 = constraints.ClassConstraint;
476 TypeExpr e2 = constraints.class_constraint;
478 if (!Convert.ImplicitReferenceConversionExists (prevConstraint, t2) &&
479 !Convert.ImplicitReferenceConversionExists (e2, prevConstraint.Type)) {
480 Report.Error (455, loc,
481 "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
482 this.tparam.Value, TypeManager.CSharpName (prevConstraint.Type), TypeManager.CSharpName (t2));
483 return false;
487 prevConstraint = constraints.class_constraint;
490 if (constraints.type_param_constraints == null)
491 return true;
493 foreach (TypeExpr expr in constraints.type_param_constraints) {
494 if (seen.Contains (expr.Type)) {
495 Report.Error (454, loc, "Circular constraint " +
496 "dependency involving `{0}' and `{1}'",
497 tparam.Name, expr.GetSignatureForError ());
498 return false;
501 if (!CheckTypeParameterConstraints (expr.Type, ref prevConstraint, seen, Report))
502 return false;
505 return true;
508 /// <summary>
509 /// Resolve the constraints into actual types.
510 /// </summary>
511 public bool ResolveTypes (IMemberContext ec, Report r)
513 if (resolved_types)
514 return true;
516 resolved_types = true;
518 foreach (object obj in constraints) {
519 GenericTypeExpr cexpr = obj as GenericTypeExpr;
520 if (cexpr == null)
521 continue;
523 if (!cexpr.CheckConstraints (ec))
524 return false;
527 if (type_param_constraints.Count != 0) {
528 var seen = new List<Type> ();
529 TypeExpr prev_constraint = class_constraint;
530 foreach (TypeExpr expr in type_param_constraints) {
531 if (!CheckTypeParameterConstraints (expr.Type, ref prev_constraint, seen, r))
532 return false;
533 seen.Clear ();
537 for (int i = 0; i < iface_constraints.Count; ++i) {
538 TypeExpr iface_constraint = (TypeExpr) iface_constraints [i];
539 iface_constraint = iface_constraint.ResolveAsTypeTerminal (ec, false);
540 if (iface_constraint == null)
541 return false;
542 iface_constraints [i] = iface_constraint;
545 if (class_constraint != null) {
546 class_constraint = class_constraint.ResolveAsTypeTerminal (ec, false);
547 if (class_constraint == null)
548 return false;
551 return true;
554 public override GenericParameterAttributes Attributes {
555 get { return attrs; }
558 public override bool HasClassConstraint {
559 get { return class_constraint != null; }
562 public override Type ClassConstraint {
563 get { return class_constraint_type; }
566 public override Type[] InterfaceConstraints {
567 get { return iface_constraint_types; }
570 public override Type EffectiveBaseClass {
571 get { return effective_base_type; }
574 public bool IsSubclassOf (Type t)
576 if ((class_constraint_type != null) &&
577 class_constraint_type.IsSubclassOf (t))
578 return true;
580 if (iface_constraint_types == null)
581 return false;
583 foreach (Type iface in iface_constraint_types) {
584 if (TypeManager.IsSubclassOf (iface, t))
585 return true;
588 return false;
591 public Location Location {
592 get {
593 return loc;
597 /// <summary>
598 /// This is used when we're implementing a generic interface method.
599 /// Each method type parameter in implementing method must have the same
600 /// constraints than the corresponding type parameter in the interface
601 /// method. To do that, we're called on each of the implementing method's
602 /// type parameters.
603 /// </summary>
604 public bool AreEqual (GenericConstraints gc)
606 if (gc.Attributes != attrs)
607 return false;
609 if (HasClassConstraint != gc.HasClassConstraint)
610 return false;
611 if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
612 return false;
614 int gc_icount = gc.InterfaceConstraints != null ?
615 gc.InterfaceConstraints.Length : 0;
616 int icount = InterfaceConstraints != null ?
617 InterfaceConstraints.Length : 0;
619 if (gc_icount != icount)
620 return false;
622 for (int i = 0; i < gc.InterfaceConstraints.Length; ++i) {
623 Type iface = gc.InterfaceConstraints [i];
624 if (iface.IsGenericType)
625 iface = iface.GetGenericTypeDefinition ();
627 bool ok = false;
628 for (int ii = 0; ii < InterfaceConstraints.Length; ii++) {
629 Type check = InterfaceConstraints [ii];
630 if (check.IsGenericType)
631 check = check.GetGenericTypeDefinition ();
633 if (TypeManager.IsEqual (iface, check)) {
634 ok = true;
635 break;
639 if (!ok)
640 return false;
643 return true;
646 public void VerifyClsCompliance (Report r)
648 if (class_constraint_type != null && !AttributeTester.IsClsCompliant (class_constraint_type))
649 Warning_ConstrainIsNotClsCompliant (class_constraint_type, class_constraint.Location, r);
651 if (iface_constraint_types != null) {
652 for (int i = 0; i < iface_constraint_types.Length; ++i) {
653 if (!AttributeTester.IsClsCompliant (iface_constraint_types [i]))
654 Warning_ConstrainIsNotClsCompliant (iface_constraint_types [i],
655 ((TypeExpr)iface_constraints [i]).Location, r);
660 void Warning_ConstrainIsNotClsCompliant (Type t, Location loc, Report Report)
662 Report.SymbolRelatedToPreviousError (t);
663 Report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
664 TypeManager.CSharpName (t));
668 /// <summary>
669 /// A type parameter from a generic type definition.
670 /// </summary>
671 public class TypeParameter : MemberCore, IMemberContainer
673 static readonly string[] attribute_target = new string [] { "type parameter" };
675 DeclSpace decl;
676 GenericConstraints gc;
677 Constraints constraints;
678 GenericTypeParameterBuilder type;
679 MemberCache member_cache;
680 Variance variance;
682 public TypeParameter (DeclSpace parent, DeclSpace decl, string name,
683 Constraints constraints, Attributes attrs, Variance variance, Location loc)
684 : base (parent, new MemberName (name, loc), attrs)
686 this.decl = decl;
687 this.constraints = constraints;
688 this.variance = variance;
691 public GenericConstraints GenericConstraints {
692 get { return gc != null ? gc : constraints; }
695 public Constraints Constraints {
696 get { return constraints; }
699 public DeclSpace DeclSpace {
700 get { return decl; }
703 public Variance Variance {
704 get { return variance; }
707 public Type Type {
708 get { return type; }
711 /// <summary>
712 /// This is the first method which is called during the resolving
713 /// process; we're called immediately after creating the type parameters
714 /// with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
715 /// MethodBuilder).
717 /// We're either called from TypeContainer.DefineType() or from
718 /// GenericMethod.Define() (called from Method.Define()).
719 /// </summary>
720 public void Define (GenericTypeParameterBuilder type)
722 if (this.type != null)
723 throw new InvalidOperationException ();
725 this.type = type;
726 TypeManager.AddTypeParameter (type, this);
729 public void ErrorInvalidVariance (IMemberContext mc, Variance expected)
731 // TODO: Report.SymbolRelatedToPreviousError (mc);
732 string input_variance = Variance == Variance.Contravariant ? "contravariant" : "covariant";
733 string gtype_variance;
734 switch (expected) {
735 case Variance.Contravariant: gtype_variance = "contravariantly"; break;
736 case Variance.Covariant: gtype_variance = "covariantly"; break;
737 default: gtype_variance = "invariantly"; break;
740 Delegate d = mc as Delegate;
741 string parameters = d != null ? d.Parameters.GetSignatureForError () : "";
743 Report.Error (1961, Location,
744 "The {2} type parameter `{0}' must be {3} valid on `{1}{4}'",
745 GetSignatureForError (), mc.GetSignatureForError (), input_variance, gtype_variance, parameters);
748 /// <summary>
749 /// This is the second method which is called during the resolving
750 /// process - in case of class type parameters, we're called from
751 /// TypeContainer.ResolveType() - after it resolved the class'es
752 /// base class and interfaces. For method type parameters, we're
753 /// called immediately after Define().
755 /// We're just resolving the constraints into expressions here, we
756 /// don't resolve them into actual types.
758 /// Note that in the special case of partial generic classes, we may be
759 /// called _before_ Define() and we may also be called multiple types.
760 /// </summary>
761 public bool Resolve (DeclSpace ds)
763 if (constraints != null) {
764 if (!constraints.Resolve (ds, this, Report)) {
765 constraints = null;
766 return false;
770 return true;
773 /// <summary>
774 /// This is the third method which is called during the resolving
775 /// process. We're called immediately after calling DefineConstraints()
776 /// on all of the current class'es type parameters.
778 /// Our job is to resolve the constraints to actual types.
780 /// Note that we may have circular dependencies on type parameters - this
781 /// is why Resolve() and ResolveType() are separate.
782 /// </summary>
783 public bool ResolveType (IMemberContext ec)
785 if (constraints != null) {
786 if (!constraints.ResolveTypes (ec, Report)) {
787 constraints = null;
788 return false;
792 return true;
795 /// <summary>
796 /// This is the fourth and last method which is called during the resolving
797 /// process. We're called after everything is fully resolved and actually
798 /// register the constraints with SRE and the TypeManager.
799 /// </summary>
800 public bool DefineType (IMemberContext ec)
802 return DefineType (ec, null, null, false);
805 /// <summary>
806 /// This is the fith and last method which is called during the resolving
807 /// process. We're called after everything is fully resolved and actually
808 /// register the constraints with SRE and the TypeManager.
810 /// The `builder', `implementing' and `is_override' arguments are only
811 /// applicable to method type parameters.
812 /// </summary>
813 public bool DefineType (IMemberContext ec, MethodBuilder builder,
814 MethodInfo implementing, bool is_override)
816 if (!ResolveType (ec))
817 return false;
819 if (implementing != null) {
820 if (is_override && (constraints != null)) {
821 Report.Error (460, Location,
822 "`{0}': Cannot specify constraints for overrides or explicit interface implementation methods",
823 TypeManager.CSharpSignature (builder));
824 return false;
827 MethodBase mb = TypeManager.DropGenericMethodArguments (implementing);
829 int pos = type.GenericParameterPosition;
830 Type mparam = mb.GetGenericArguments () [pos];
831 GenericConstraints temp_gc = ReflectionConstraints.GetConstraints (mparam);
833 if (temp_gc != null)
834 gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
835 else if (constraints != null)
836 gc = new InflatedConstraints (constraints, implementing.DeclaringType);
838 bool ok = true;
839 if (constraints != null) {
840 if (temp_gc == null)
841 ok = false;
842 else if (!constraints.AreEqual (gc))
843 ok = false;
844 } else {
845 if (!is_override && (temp_gc != null))
846 ok = false;
849 if (!ok) {
850 Report.SymbolRelatedToPreviousError (implementing);
852 Report.Error (
853 425, Location, "The constraints for type " +
854 "parameter `{0}' of method `{1}' must match " +
855 "the constraints for type parameter `{2}' " +
856 "of interface method `{3}'. Consider using " +
857 "an explicit interface implementation instead",
858 Name, TypeManager.CSharpSignature (builder),
859 TypeManager.CSharpName (mparam), TypeManager.CSharpSignature (mb));
860 return false;
862 } else if (DeclSpace is CompilerGeneratedClass) {
863 TypeParameter[] tparams = DeclSpace.TypeParameters;
864 Type[] types = new Type [tparams.Length];
865 for (int i = 0; i < tparams.Length; i++)
866 types [i] = tparams [i].Type;
868 if (constraints != null)
869 gc = new InflatedConstraints (constraints, types);
870 } else {
871 gc = (GenericConstraints) constraints;
874 SetConstraints (type);
875 return true;
878 public static TypeParameter FindTypeParameter (TypeParameter[] tparams, string name)
880 foreach (var tp in tparams) {
881 if (tp.Name == name)
882 return tp;
885 return null;
888 public void SetConstraints (GenericTypeParameterBuilder type)
890 GenericParameterAttributes attr = GenericParameterAttributes.None;
891 if (variance == Variance.Contravariant)
892 attr |= GenericParameterAttributes.Contravariant;
893 else if (variance == Variance.Covariant)
894 attr |= GenericParameterAttributes.Covariant;
896 if (gc != null) {
897 if (gc.HasClassConstraint || gc.HasValueTypeConstraint)
898 type.SetBaseTypeConstraint (gc.EffectiveBaseClass);
900 attr |= gc.Attributes;
901 type.SetInterfaceConstraints (gc.InterfaceConstraints);
902 TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
905 type.SetGenericParameterAttributes (attr);
908 /// <summary>
909 /// This is called for each part of a partial generic type definition.
911 /// If `new_constraints' is not null and we don't already have constraints,
912 /// they become our constraints. If we already have constraints, we must
913 /// check that they're the same.
914 /// con
915 /// </summary>
916 public bool UpdateConstraints (MemberCore ec, Constraints new_constraints)
918 if (type == null)
919 throw new InvalidOperationException ();
921 if (new_constraints == null)
922 return true;
924 if (!new_constraints.Resolve (ec, this, Report))
925 return false;
926 if (!new_constraints.ResolveTypes (ec, Report))
927 return false;
929 if (constraints != null)
930 return constraints.AreEqual (new_constraints);
932 constraints = new_constraints;
933 return true;
936 public override void Emit ()
938 if (OptAttributes != null)
939 OptAttributes.Emit ();
941 base.Emit ();
944 public override string DocCommentHeader {
945 get {
946 throw new InvalidOperationException (
947 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
952 // MemberContainer
955 public override bool Define ()
957 return true;
960 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
962 type.SetCustomAttribute (cb);
965 public override AttributeTargets AttributeTargets {
966 get {
967 return AttributeTargets.GenericParameter;
971 public override string[] ValidAttributeTargets {
972 get {
973 return attribute_target;
978 // IMemberContainer
981 string IMemberContainer.Name {
982 get { return Name; }
985 MemberCache IMemberContainer.BaseCache {
986 get {
987 if (gc == null)
988 return null;
990 if (gc.EffectiveBaseClass.BaseType == null)
991 return null;
993 return TypeManager.LookupMemberCache (gc.EffectiveBaseClass.BaseType);
997 bool IMemberContainer.IsInterface {
998 get { return false; }
1001 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
1003 throw new NotSupportedException ();
1006 public MemberCache MemberCache {
1007 get {
1008 if (member_cache != null)
1009 return member_cache;
1011 if (gc == null)
1012 return null;
1014 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
1015 member_cache = new MemberCache (this, gc.EffectiveBaseClass, ifaces);
1017 return member_cache;
1021 public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1022 MemberFilter filter, object criteria)
1024 if (gc == null)
1025 return MemberList.Empty;
1027 var members = new List<MemberInfo> ();
1029 if (gc.HasClassConstraint) {
1030 MemberList list = TypeManager.FindMembers (
1031 gc.ClassConstraint, mt, bf, filter, criteria);
1033 members.AddRange (list);
1036 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
1037 foreach (Type t in ifaces) {
1038 MemberList list = TypeManager.FindMembers (
1039 t, mt, bf, filter, criteria);
1041 members.AddRange (list);
1044 return new MemberList (members);
1047 public bool IsSubclassOf (Type t)
1049 if (type.Equals (t))
1050 return true;
1052 if (constraints != null)
1053 return constraints.IsSubclassOf (t);
1055 return false;
1058 public void InflateConstraints (Type declaring)
1060 if (constraints != null)
1061 gc = new InflatedConstraints (constraints, declaring);
1064 public override bool IsClsComplianceRequired ()
1066 return false;
1069 protected class InflatedConstraints : GenericConstraints
1071 GenericConstraints gc;
1072 Type base_type;
1073 Type class_constraint;
1074 Type[] iface_constraints;
1075 Type[] dargs;
1077 public InflatedConstraints (GenericConstraints gc, Type declaring)
1078 : this (gc, TypeManager.GetTypeArguments (declaring))
1081 public InflatedConstraints (GenericConstraints gc, Type[] dargs)
1083 this.gc = gc;
1084 this.dargs = dargs;
1086 var list = new List<Type> ();
1087 if (gc.HasClassConstraint)
1088 list.Add (inflate (gc.ClassConstraint));
1089 foreach (Type iface in gc.InterfaceConstraints)
1090 list.Add (inflate (iface));
1092 bool has_class_constr = false;
1093 if (list.Count > 0) {
1094 Type first = (Type) list [0];
1095 has_class_constr = !first.IsGenericParameter && !first.IsInterface;
1098 if ((list.Count > 0) && has_class_constr) {
1099 class_constraint = (Type) list [0];
1100 iface_constraints = new Type [list.Count - 1];
1101 list.CopyTo (1, iface_constraints, 0, list.Count - 1);
1102 } else {
1103 iface_constraints = new Type [list.Count];
1104 list.CopyTo (iface_constraints, 0);
1107 if (HasValueTypeConstraint)
1108 base_type = TypeManager.value_type;
1109 else if (class_constraint != null)
1110 base_type = class_constraint;
1111 else
1112 base_type = TypeManager.object_type;
1115 Type inflate (Type t)
1117 if (t == null)
1118 return null;
1119 if (t.IsGenericParameter)
1120 return t.GenericParameterPosition < dargs.Length ? dargs [t.GenericParameterPosition] : t;
1121 if (t.IsGenericType) {
1122 Type[] args = t.GetGenericArguments ();
1123 Type[] inflated = new Type [args.Length];
1125 for (int i = 0; i < args.Length; i++)
1126 inflated [i] = inflate (args [i]);
1128 t = t.GetGenericTypeDefinition ();
1129 t = t.MakeGenericType (inflated);
1132 return t;
1135 public override GenericParameterAttributes Attributes {
1136 get { return gc.Attributes; }
1139 public override Type ClassConstraint {
1140 get { return class_constraint; }
1143 public override Type EffectiveBaseClass {
1144 get { return base_type; }
1147 public override Type[] InterfaceConstraints {
1148 get { return iface_constraints; }
1153 /// <summary>
1154 /// A TypeExpr which already resolved to a type parameter.
1155 /// </summary>
1156 public class TypeParameterExpr : TypeExpr {
1158 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1160 this.type = type_parameter.Type;
1161 this.eclass = ExprClass.TypeParameter;
1162 this.loc = loc;
1165 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
1167 throw new NotSupportedException ();
1170 public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
1172 return this;
1175 public override bool IsInterface {
1176 get { return false; }
1179 public override bool CheckAccessLevel (IMemberContext ds)
1181 return true;
1186 // Tracks the type arguments when instantiating a generic type. It's used
1187 // by both type arguments and type parameters
1189 public class TypeArguments {
1190 List<FullNamedExpression> args;
1191 Type[] atypes;
1193 public TypeArguments ()
1195 args = new List<FullNamedExpression> ();
1198 public TypeArguments (params FullNamedExpression[] types)
1200 this.args = new List<FullNamedExpression> (types);
1203 public void Add (FullNamedExpression type)
1205 args.Add (type);
1208 public void Add (TypeArguments new_args)
1210 args.AddRange (new_args.args);
1213 // TODO: Kill this monster
1214 public TypeParameterName[] GetDeclarations ()
1216 return args.ConvertAll (i => (TypeParameterName) i).ToArray ();
1219 /// <summary>
1220 /// We may only be used after Resolve() is called and return the fully
1221 /// resolved types.
1222 /// </summary>
1223 public Type[] Arguments {
1224 get {
1225 return atypes;
1229 public int Count {
1230 get {
1231 return args.Count;
1235 public string GetSignatureForError()
1237 StringBuilder sb = new StringBuilder();
1238 for (int i = 0; i < Count; ++i)
1240 Expression expr = (Expression)args [i];
1241 sb.Append(expr.GetSignatureForError());
1242 if (i + 1 < Count)
1243 sb.Append(',');
1245 return sb.ToString();
1248 /// <summary>
1249 /// Resolve the type arguments.
1250 /// </summary>
1251 public bool Resolve (IMemberContext ec)
1253 if (atypes != null)
1254 return atypes.Length != 0;
1256 int count = args.Count;
1257 bool ok = true;
1259 atypes = new Type [count];
1261 for (int i = 0; i < count; i++){
1262 TypeExpr te = ((FullNamedExpression) args[i]).ResolveAsTypeTerminal (ec, false);
1263 if (te == null) {
1264 ok = false;
1265 continue;
1268 atypes[i] = te.Type;
1270 if (te.Type.IsSealed && te.Type.IsAbstract) {
1271 ec.Compiler.Report.Error (718, te.Location, "`{0}': static classes cannot be used as generic arguments",
1272 te.GetSignatureForError ());
1273 ok = false;
1276 if (te.Type.IsPointer || TypeManager.IsSpecialType (te.Type)) {
1277 ec.Compiler.Report.Error (306, te.Location,
1278 "The type `{0}' may not be used as a type argument",
1279 te.GetSignatureForError ());
1280 ok = false;
1284 if (!ok)
1285 atypes = Type.EmptyTypes;
1287 return ok;
1290 public TypeArguments Clone ()
1292 TypeArguments copy = new TypeArguments ();
1293 foreach (var ta in args)
1294 copy.args.Add (ta);
1296 return copy;
1300 public class TypeParameterName : SimpleName
1302 Attributes attributes;
1303 Variance variance;
1305 public TypeParameterName (string name, Attributes attrs, Location loc)
1306 : this (name, attrs, Variance.None, loc)
1310 public TypeParameterName (string name, Attributes attrs, Variance variance, Location loc)
1311 : base (name, loc)
1313 attributes = attrs;
1314 this.variance = variance;
1317 public Attributes OptAttributes {
1318 get {
1319 return attributes;
1323 public Variance Variance {
1324 get {
1325 return variance;
1330 /// <summary>
1331 /// A reference expression to generic type
1332 /// </summary>
1333 class GenericTypeExpr : TypeExpr
1335 TypeArguments args;
1336 Type[] gen_params; // TODO: Waiting for constrains check cleanup
1337 Type open_type;
1340 // Should be carefully used only with defined generic containers. Type parameters
1341 // can be used as type arguments in this case.
1343 // TODO: This could be GenericTypeExpr specialization
1345 public GenericTypeExpr (DeclSpace gType, Location l)
1347 open_type = gType.TypeBuilder.GetGenericTypeDefinition ();
1349 args = new TypeArguments ();
1350 foreach (TypeParameter type_param in gType.TypeParameters)
1351 args.Add (new TypeParameterExpr (type_param, l));
1353 this.loc = l;
1356 /// <summary>
1357 /// Instantiate the generic type `t' with the type arguments `args'.
1358 /// Use this constructor if you already know the fully resolved
1359 /// generic type.
1360 /// </summary>
1361 public GenericTypeExpr (Type t, TypeArguments args, Location l)
1363 open_type = t.GetGenericTypeDefinition ();
1365 loc = l;
1366 this.args = args;
1369 public TypeArguments TypeArguments {
1370 get { return args; }
1373 public override string GetSignatureForError ()
1375 return TypeManager.CSharpName (type);
1378 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
1380 eclass = ExprClass.Type;
1382 if (!args.Resolve (ec))
1383 return null;
1385 gen_params = open_type.GetGenericArguments ();
1386 Type[] atypes = args.Arguments;
1388 if (atypes.Length != gen_params.Length) {
1389 Namespace.Error_InvalidNumberOfTypeArguments (ec.Compiler.Report, open_type, loc);
1390 return null;
1394 // Now bind the parameters
1396 type = open_type.MakeGenericType (atypes);
1397 return this;
1400 /// <summary>
1401 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1402 /// after fully resolving the constructed type.
1403 /// </summary>
1404 public bool CheckConstraints (IMemberContext ec)
1406 return ConstraintChecker.CheckConstraints (ec, open_type, gen_params, args.Arguments, loc);
1409 public override bool CheckAccessLevel (IMemberContext mc)
1411 return mc.CurrentTypeDefinition.CheckAccessLevel (open_type);
1414 public bool HasDynamicArguments ()
1416 return HasDynamicArguments (args.Arguments);
1419 static bool HasDynamicArguments (Type[] args)
1421 foreach (var item in args)
1423 if (TypeManager.IsGenericType (item))
1424 return HasDynamicArguments (TypeManager.GetTypeArguments (item));
1426 if (TypeManager.IsDynamicType (item))
1427 return true;
1430 return false;
1433 public override bool IsClass {
1434 get { return open_type.IsClass; }
1437 public override bool IsValueType {
1438 get { return TypeManager.IsStruct (open_type); }
1441 public override bool IsInterface {
1442 get { return open_type.IsInterface; }
1445 public override bool IsSealed {
1446 get { return open_type.IsSealed; }
1449 public override bool Equals (object obj)
1451 GenericTypeExpr cobj = obj as GenericTypeExpr;
1452 if (cobj == null)
1453 return false;
1455 if ((type == null) || (cobj.type == null))
1456 return false;
1458 return type == cobj.type;
1461 public override int GetHashCode ()
1463 return base.GetHashCode ();
1467 public abstract class ConstraintChecker
1469 protected readonly Type[] gen_params;
1470 protected readonly Type[] atypes;
1471 protected readonly Location loc;
1472 protected Report Report;
1474 protected ConstraintChecker (Type[] gen_params, Type[] atypes, Location loc, Report r)
1476 this.gen_params = gen_params;
1477 this.atypes = atypes;
1478 this.loc = loc;
1479 this.Report = r;
1482 /// <summary>
1483 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1484 /// after fully resolving the constructed type.
1485 /// </summary>
1486 public bool CheckConstraints (IMemberContext ec)
1488 for (int i = 0; i < gen_params.Length; i++) {
1489 if (!CheckConstraints (ec, i))
1490 return false;
1493 return true;
1496 protected bool CheckConstraints (IMemberContext ec, int index)
1498 Type atype = TypeManager.TypeToCoreType (atypes [index]);
1499 Type ptype = gen_params [index];
1501 if (atype == ptype)
1502 return true;
1504 Expression aexpr = new EmptyExpression (atype);
1506 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1507 if (gc == null)
1508 return true;
1510 bool is_class, is_struct;
1511 if (atype.IsGenericParameter) {
1512 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1513 if (agc != null) {
1514 if (agc is Constraints) {
1515 // FIXME: No constraints can be resolved here, we are in
1516 // completely wrong/different context. This path is hit
1517 // when resolving base type of unresolved generic type
1518 // with constraints. We are waiting with CheckConsttraints
1519 // after type-definition but not in this case
1520 if (!((Constraints) agc).Resolve (null, null, Report))
1521 return true;
1523 is_class = agc.IsReferenceType;
1524 is_struct = agc.IsValueType;
1525 } else {
1526 is_class = is_struct = false;
1528 } else {
1529 is_class = TypeManager.IsReferenceType (atype);
1530 is_struct = TypeManager.IsValueType (atype) && !TypeManager.IsNullableType (atype);
1534 // First, check the `class' and `struct' constraints.
1536 if (gc.HasReferenceTypeConstraint && !is_class) {
1537 Report.Error (452, loc, "The type `{0}' must be " +
1538 "a reference type in order to use it " +
1539 "as type parameter `{1}' in the " +
1540 "generic type or method `{2}'.",
1541 TypeManager.CSharpName (atype),
1542 TypeManager.CSharpName (ptype),
1543 GetSignatureForError ());
1544 return false;
1545 } else if (gc.HasValueTypeConstraint && !is_struct) {
1546 Report.Error (453, loc, "The type `{0}' must be a " +
1547 "non-nullable value type in order to use it " +
1548 "as type parameter `{1}' in the " +
1549 "generic type or method `{2}'.",
1550 TypeManager.CSharpName (atype),
1551 TypeManager.CSharpName (ptype),
1552 GetSignatureForError ());
1553 return false;
1557 // The class constraint comes next.
1559 if (gc.HasClassConstraint) {
1560 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint))
1561 return false;
1565 // Now, check the interface constraints.
1567 if (gc.InterfaceConstraints != null) {
1568 foreach (Type it in gc.InterfaceConstraints) {
1569 if (!CheckConstraint (ec, ptype, aexpr, it))
1570 return false;
1575 // Finally, check the constructor constraint.
1578 if (!gc.HasConstructorConstraint)
1579 return true;
1581 if (TypeManager.IsValueType (atype))
1582 return true;
1584 if (HasDefaultConstructor (atype))
1585 return true;
1587 Report_SymbolRelatedToPreviousError ();
1588 Report.SymbolRelatedToPreviousError (atype);
1589 Report.Error (310, loc, "The type `{0}' must have a public " +
1590 "parameterless constructor in order to use it " +
1591 "as parameter `{1}' in the generic type or " +
1592 "method `{2}'",
1593 TypeManager.CSharpName (atype),
1594 TypeManager.CSharpName (ptype),
1595 GetSignatureForError ());
1596 return false;
1599 Type InflateType(IMemberContext ec, Type ctype)
1601 Type[] types = TypeManager.GetTypeArguments (ctype);
1603 TypeArguments new_args = new TypeArguments ();
1605 for (int i = 0; i < types.Length; i++) {
1606 Type t = TypeManager.TypeToCoreType (types [i]);
1608 if (t.IsGenericParameter) {
1609 int pos = t.GenericParameterPosition;
1610 if (t.DeclaringMethod == null && this is MethodConstraintChecker) {
1611 Type parent = ((MethodConstraintChecker) this).declaring_type;
1612 t = parent.GetGenericArguments ()[pos];
1613 } else {
1614 t = atypes [pos];
1616 } else if(TypeManager.HasGenericArguments(t)) {
1617 t = InflateType (ec, t);
1618 if (t == null) {
1619 return null;
1622 new_args.Add (new TypeExpression (t, loc));
1625 TypeExpr ct = new GenericTypeExpr (ctype, new_args, loc);
1626 if (ct.ResolveAsTypeStep (ec, false) == null)
1627 return null;
1629 return ct.Type;
1632 protected bool CheckConstraint (IMemberContext ec, Type ptype, Expression expr,
1633 Type ctype)
1636 // All this is needed because we don't have
1637 // real inflated type hierarchy
1639 if (TypeManager.HasGenericArguments (ctype)) {
1640 ctype = InflateType (ec, ctype);
1641 if(ctype == null) {
1642 return false;
1644 } else if (ctype.IsGenericParameter) {
1645 int pos = ctype.GenericParameterPosition;
1646 if (ctype.DeclaringMethod == null) {
1647 // FIXME: Implement
1648 return true;
1649 } else {
1650 ctype = atypes [pos];
1654 if (Convert.ImplicitStandardConversionExists (expr, ctype))
1655 return true;
1657 Report_SymbolRelatedToPreviousError ();
1658 Report.SymbolRelatedToPreviousError (expr.Type);
1660 if (TypeManager.IsNullableType (expr.Type) && ctype.IsInterface) {
1661 Report.Error (313, loc,
1662 "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. " +
1663 "The nullable type `{0}' never satisfies interface constraint of type `{3}'",
1664 TypeManager.CSharpName (expr.Type), TypeManager.CSharpName (ptype),
1665 GetSignatureForError (), TypeManager.CSharpName (ctype));
1666 } else {
1667 Report.Error (309, loc,
1668 "The type `{0}' must be convertible to `{1}' in order to " +
1669 "use it as parameter `{2}' in the generic type or method `{3}'",
1670 TypeManager.CSharpName (expr.Type), TypeManager.CSharpName (ctype),
1671 TypeManager.CSharpName (ptype), GetSignatureForError ());
1673 return false;
1676 static bool HasDefaultConstructor (Type atype)
1678 TypeParameter tparam = TypeManager.LookupTypeParameter (atype);
1679 if (tparam != null) {
1680 if (tparam.GenericConstraints == null)
1681 return false;
1683 return tparam.GenericConstraints.HasConstructorConstraint ||
1684 tparam.GenericConstraints.HasValueTypeConstraint;
1687 if (atype.IsAbstract)
1688 return false;
1690 again:
1691 atype = TypeManager.DropGenericTypeArguments (atype);
1692 if (atype is TypeBuilder) {
1693 TypeContainer tc = TypeManager.LookupTypeContainer (atype);
1694 if (tc.InstanceConstructors == null) {
1695 atype = atype.BaseType;
1696 goto again;
1699 foreach (Constructor c in tc.InstanceConstructors) {
1700 if ((c.ModFlags & Modifiers.PUBLIC) == 0)
1701 continue;
1702 if ((c.Parameters.FixedParameters != null) &&
1703 (c.Parameters.FixedParameters.Length != 0))
1704 continue;
1705 if (c.Parameters.HasArglist || c.Parameters.HasParams)
1706 continue;
1708 return true;
1712 MemberInfo [] list = TypeManager.MemberLookup (null, null, atype, MemberTypes.Constructor,
1713 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
1714 ConstructorInfo.ConstructorName, null);
1716 if (list == null)
1717 return false;
1719 foreach (MethodBase mb in list) {
1720 AParametersCollection pd = TypeManager.GetParameterData (mb);
1721 if (pd.Count == 0)
1722 return true;
1725 return false;
1728 protected abstract string GetSignatureForError ();
1729 protected abstract void Report_SymbolRelatedToPreviousError ();
1731 public static bool CheckConstraints (IMemberContext ec, MethodBase definition,
1732 MethodBase instantiated, Location loc)
1734 MethodConstraintChecker checker = new MethodConstraintChecker (
1735 definition, instantiated.DeclaringType, definition.GetGenericArguments (),
1736 instantiated.GetGenericArguments (), loc, ec.Compiler.Report);
1738 return checker.CheckConstraints (ec);
1741 public static bool CheckConstraints (IMemberContext ec, Type gt, Type[] gen_params,
1742 Type[] atypes, Location loc)
1744 TypeConstraintChecker checker = new TypeConstraintChecker (
1745 gt, gen_params, atypes, loc, ec.Compiler.Report);
1747 return checker.CheckConstraints (ec);
1750 protected class MethodConstraintChecker : ConstraintChecker
1752 MethodBase definition;
1753 public Type declaring_type;
1755 public MethodConstraintChecker (MethodBase definition, Type declaringType, Type[] gen_params,
1756 Type[] atypes, Location loc, Report r)
1757 : base (gen_params, atypes, loc, r)
1759 this.declaring_type = declaringType;
1760 this.definition = definition;
1763 protected override string GetSignatureForError ()
1765 return TypeManager.CSharpSignature (definition);
1768 protected override void Report_SymbolRelatedToPreviousError ()
1770 Report.SymbolRelatedToPreviousError (definition);
1774 protected class TypeConstraintChecker : ConstraintChecker
1776 Type gt;
1778 public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
1779 Location loc, Report r)
1780 : base (gen_params, atypes, loc, r)
1782 this.gt = gt;
1785 protected override string GetSignatureForError ()
1787 return TypeManager.CSharpName (gt);
1790 protected override void Report_SymbolRelatedToPreviousError ()
1792 Report.SymbolRelatedToPreviousError (gt);
1797 /// <summary>
1798 /// A generic method definition.
1799 /// </summary>
1800 public class GenericMethod : DeclSpace
1802 FullNamedExpression return_type;
1803 ParametersCompiled parameters;
1805 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
1806 FullNamedExpression return_type, ParametersCompiled parameters)
1807 : base (ns, parent, name, null)
1809 this.return_type = return_type;
1810 this.parameters = parameters;
1813 public override TypeContainer CurrentTypeDefinition {
1814 get {
1815 return Parent.CurrentTypeDefinition;
1819 public override TypeParameter[] CurrentTypeParameters {
1820 get {
1821 return base.type_params;
1825 public override TypeBuilder DefineType ()
1827 throw new Exception ();
1830 public override bool Define ()
1832 for (int i = 0; i < TypeParameters.Length; i++)
1833 if (!TypeParameters [i].Resolve (this))
1834 return false;
1836 return true;
1839 /// <summary>
1840 /// Define and resolve the type parameters.
1841 /// We're called from Method.Define().
1842 /// </summary>
1843 public bool Define (MethodOrOperator m)
1845 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1846 string[] snames = new string [names.Length];
1847 for (int i = 0; i < names.Length; i++) {
1848 string type_argument_name = names[i].Name;
1849 int idx = parameters.GetParameterIndexByName (type_argument_name);
1850 if (idx >= 0) {
1851 Block b = m.Block;
1852 if (b == null)
1853 b = new Block (null);
1855 b.Error_AlreadyDeclaredTypeParameter (Report, parameters [i].Location,
1856 type_argument_name, "method parameter");
1859 snames[i] = type_argument_name;
1862 GenericTypeParameterBuilder[] gen_params = m.MethodBuilder.DefineGenericParameters (snames);
1863 for (int i = 0; i < TypeParameters.Length; i++)
1864 TypeParameters [i].Define (gen_params [i]);
1866 if (!Define ())
1867 return false;
1869 for (int i = 0; i < TypeParameters.Length; i++) {
1870 if (!TypeParameters [i].ResolveType (this))
1871 return false;
1874 return true;
1877 /// <summary>
1878 /// We're called from MethodData.Define() after creating the MethodBuilder.
1879 /// </summary>
1880 public bool DefineType (IMemberContext ec, MethodBuilder mb,
1881 MethodInfo implementing, bool is_override)
1883 for (int i = 0; i < TypeParameters.Length; i++)
1884 if (!TypeParameters [i].DefineType (
1885 ec, mb, implementing, is_override))
1886 return false;
1888 bool ok = parameters.Resolve (ec);
1890 if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec, false) == null))
1891 ok = false;
1893 return ok;
1896 public void EmitAttributes ()
1898 for (int i = 0; i < TypeParameters.Length; i++)
1899 TypeParameters [i].Emit ();
1901 if (OptAttributes != null)
1902 OptAttributes.Emit ();
1905 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1906 MemberFilter filter, object criteria)
1908 throw new Exception ();
1911 public override string GetSignatureForError ()
1913 return base.GetSignatureForError () + parameters.GetSignatureForError ();
1916 public override MemberCache MemberCache {
1917 get {
1918 return null;
1922 public override AttributeTargets AttributeTargets {
1923 get {
1924 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1928 public override string DocCommentHeader {
1929 get { return "M:"; }
1932 public new void VerifyClsCompliance ()
1934 foreach (TypeParameter tp in TypeParameters) {
1935 if (tp.Constraints == null)
1936 continue;
1938 tp.Constraints.VerifyClsCompliance (Report);
1943 partial class TypeManager
1945 public static TypeContainer LookupGenericTypeContainer (Type t)
1947 t = DropGenericTypeArguments (t);
1948 return LookupTypeContainer (t);
1951 public static Variance GetTypeParameterVariance (Type type)
1953 TypeParameter tparam = LookupTypeParameter (type);
1954 if (tparam != null)
1955 return tparam.Variance;
1957 switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
1958 case GenericParameterAttributes.Covariant:
1959 return Variance.Covariant;
1960 case GenericParameterAttributes.Contravariant:
1961 return Variance.Contravariant;
1962 default:
1963 return Variance.None;
1967 public static Variance CheckTypeVariance (Type t, Variance expected, IMemberContext member)
1969 TypeParameter tp = LookupTypeParameter (t);
1970 if (tp != null) {
1971 Variance v = tp.Variance;
1972 if (expected == Variance.None && v != expected ||
1973 expected == Variance.Covariant && v == Variance.Contravariant ||
1974 expected == Variance.Contravariant && v == Variance.Covariant)
1975 tp.ErrorInvalidVariance (member, expected);
1977 return expected;
1980 if (t.IsGenericType) {
1981 Type[] targs_definition = GetTypeArguments (DropGenericTypeArguments (t));
1982 Type[] targs = GetTypeArguments (t);
1983 for (int i = 0; i < targs_definition.Length; ++i) {
1984 Variance v = GetTypeParameterVariance (targs_definition[i]);
1985 CheckTypeVariance (targs[i], (Variance) ((int)v * (int)expected), member);
1988 return expected;
1991 if (t.IsArray)
1992 return CheckTypeVariance (GetElementType (t), expected, member);
1994 return Variance.None;
1997 public static bool IsVariantOf (Type type1, Type type2)
1999 if (!type1.IsGenericType || !type2.IsGenericType)
2000 return false;
2002 Type generic_target_type = DropGenericTypeArguments (type2);
2003 if (DropGenericTypeArguments (type1) != generic_target_type)
2004 return false;
2006 Type[] t1 = GetTypeArguments (type1);
2007 Type[] t2 = GetTypeArguments (type2);
2008 Type[] targs_definition = GetTypeArguments (generic_target_type);
2009 for (int i = 0; i < targs_definition.Length; ++i) {
2010 Variance v = GetTypeParameterVariance (targs_definition [i]);
2011 if (v == Variance.None) {
2012 if (t1[i] == t2[i])
2013 continue;
2014 return false;
2017 if (v == Variance.Covariant) {
2018 if (!Convert.ImplicitReferenceConversionExists (new EmptyExpression (t1 [i]), t2 [i]))
2019 return false;
2020 } else if (!Convert.ImplicitReferenceConversionExists (new EmptyExpression (t2[i]), t1[i])) {
2021 return false;
2025 return true;
2028 /// <summary>
2029 /// Check whether `a' and `b' may become equal generic types.
2030 /// The algorithm to do that is a little bit complicated.
2031 /// </summary>
2032 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_inferred,
2033 Type[] method_inferred)
2035 if (a.IsGenericParameter) {
2037 // If a is an array of a's type, they may never
2038 // become equal.
2040 while (b.IsArray) {
2041 b = GetElementType (b);
2042 if (a.Equals (b))
2043 return false;
2047 // If b is a generic parameter or an actual type,
2048 // they may become equal:
2050 // class X<T,U> : I<T>, I<U>
2051 // class X<T> : I<T>, I<float>
2053 if (b.IsGenericParameter || !b.IsGenericType) {
2054 int pos = a.GenericParameterPosition;
2055 Type[] args = a.DeclaringMethod != null ? method_inferred : class_inferred;
2056 if (args [pos] == null) {
2057 args [pos] = b;
2058 return true;
2061 return args [pos] == a;
2065 // We're now comparing a type parameter with a
2066 // generic instance. They may become equal unless
2067 // the type parameter appears anywhere in the
2068 // generic instance:
2070 // class X<T,U> : I<T>, I<X<U>>
2071 // -> error because you could instanciate it as
2072 // X<X<int>,int>
2074 // class X<T> : I<T>, I<X<T>> -> ok
2077 Type[] bargs = GetTypeArguments (b);
2078 for (int i = 0; i < bargs.Length; i++) {
2079 if (a.Equals (bargs [i]))
2080 return false;
2083 return true;
2086 if (b.IsGenericParameter)
2087 return MayBecomeEqualGenericTypes (b, a, class_inferred, method_inferred);
2090 // At this point, neither a nor b are a type parameter.
2092 // If one of them is a generic instance, let
2093 // MayBecomeEqualGenericInstances() compare them (if the
2094 // other one is not a generic instance, they can never
2095 // become equal).
2098 if (a.IsGenericType || b.IsGenericType)
2099 return MayBecomeEqualGenericInstances (a, b, class_inferred, method_inferred);
2102 // If both of them are arrays.
2105 if (a.IsArray && b.IsArray) {
2106 if (a.GetArrayRank () != b.GetArrayRank ())
2107 return false;
2109 a = GetElementType (a);
2110 b = GetElementType (b);
2112 return MayBecomeEqualGenericTypes (a, b, class_inferred, method_inferred);
2116 // Ok, two ordinary types.
2119 return a.Equals (b);
2123 // Checks whether two generic instances may become equal for some
2124 // particular instantiation (26.3.1).
2126 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
2127 Type[] class_inferred,
2128 Type[] method_inferred)
2130 if (!a.IsGenericType || !b.IsGenericType)
2131 return false;
2132 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2133 return false;
2135 return MayBecomeEqualGenericInstances (
2136 GetTypeArguments (a), GetTypeArguments (b), class_inferred, method_inferred);
2139 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
2140 Type[] class_inferred,
2141 Type[] method_inferred)
2143 if (aargs.Length != bargs.Length)
2144 return false;
2146 for (int i = 0; i < aargs.Length; i++) {
2147 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_inferred, method_inferred))
2148 return false;
2151 return true;
2154 /// <summary>
2155 /// Type inference. Try to infer the type arguments from `method',
2156 /// which is invoked with the arguments `arguments'. This is used
2157 /// when resolving an Invocation or a DelegateInvocation and the user
2158 /// did not explicitly specify type arguments.
2159 /// </summary>
2160 public static int InferTypeArguments (ResolveContext ec, Arguments arguments, ref MethodSpec method)
2162 ATypeInference ti = ATypeInference.CreateInstance (arguments);
2163 Type[] i_args = ti.InferMethodArguments (ec, method);
2164 if (i_args == null)
2165 return ti.InferenceScore;
2167 if (i_args.Length == 0)
2168 return 0;
2170 method = method.Inflate (i_args);
2171 return 0;
2175 public static bool InferTypeArguments (ResolveContext ec, AParametersCollection param, ref MethodBase method)
2177 if (!TypeManager.IsGenericMethod (method))
2178 return true;
2180 ATypeInference ti = ATypeInference.CreateInstance (DelegateCreation.CreateDelegateMethodArguments (param, Location.Null));
2181 Type[] i_args = ti.InferDelegateArguments (ec, method);
2182 if (i_args == null)
2183 return false;
2185 method = ((MethodInfo) method).MakeGenericMethod (i_args);
2186 return true;
2191 abstract class ATypeInference
2193 protected readonly Arguments arguments;
2194 protected readonly int arg_count;
2196 protected ATypeInference (Arguments arguments)
2198 this.arguments = arguments;
2199 if (arguments != null)
2200 arg_count = arguments.Count;
2203 public static ATypeInference CreateInstance (Arguments arguments)
2205 return new TypeInference (arguments);
2208 public virtual int InferenceScore {
2209 get {
2210 return int.MaxValue;
2214 public abstract Type[] InferMethodArguments (ResolveContext ec, MethodSpec method);
2215 // public abstract Type[] InferDelegateArguments (ResolveContext ec, MethodBase method);
2219 // Implements C# type inference
2221 class TypeInference : ATypeInference
2224 // Tracks successful rate of type inference
2226 int score = int.MaxValue;
2228 public TypeInference (Arguments arguments)
2229 : base (arguments)
2233 public override int InferenceScore {
2234 get {
2235 return score;
2240 public override Type[] InferDelegateArguments (ResolveContext ec, MethodBase method)
2242 AParametersCollection pd = TypeManager.GetParameterData (method);
2243 if (arg_count != pd.Count)
2244 return null;
2246 Type[] d_gargs = method.GetGenericArguments ();
2247 TypeInferenceContext context = new TypeInferenceContext (d_gargs);
2249 // A lower-bound inference is made from each argument type Uj of D
2250 // to the corresponding parameter type Tj of M
2251 for (int i = 0; i < arg_count; ++i) {
2252 Type t = pd.Types [i];
2253 if (!t.IsGenericParameter)
2254 continue;
2256 context.LowerBoundInference (arguments [i].Expr.Type, t);
2259 if (!context.FixAllTypes (ec))
2260 return null;
2262 return context.InferredTypeArguments;
2265 public override Type[] InferMethodArguments (ResolveContext ec, MethodSpec method)
2267 var method_generic_args = method.GetGenericArguments ();
2268 TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2269 if (!context.UnfixedVariableExists)
2270 return Type.EmptyTypes;
2272 AParametersCollection pd = method.Parameters;
2273 if (!InferInPhases (ec, context, pd))
2274 return null;
2276 return context.InferredTypeArguments;
2280 // Implements method type arguments inference
2282 bool InferInPhases (ResolveContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
2284 int params_arguments_start;
2285 if (methodParameters.HasParams) {
2286 params_arguments_start = methodParameters.Count - 1;
2287 } else {
2288 params_arguments_start = arg_count;
2291 Type [] ptypes = methodParameters.Types;
2294 // The first inference phase
2296 Type method_parameter = null;
2297 for (int i = 0; i < arg_count; i++) {
2298 Argument a = arguments [i];
2299 if (a == null)
2300 continue;
2302 if (i < params_arguments_start) {
2303 method_parameter = methodParameters.Types [i];
2304 } else if (i == params_arguments_start) {
2305 if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2306 method_parameter = methodParameters.Types [params_arguments_start];
2307 else
2308 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2310 ptypes = (Type[]) ptypes.Clone ();
2311 ptypes [i] = method_parameter;
2315 // When a lambda expression, an anonymous method
2316 // is used an explicit argument type inference takes a place
2318 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2319 if (am != null) {
2320 if (am.ExplicitTypeInference (ec, tic, method_parameter))
2321 --score;
2322 continue;
2325 if (a.IsByRef) {
2326 score -= tic.ExactInference (a.Type, method_parameter);
2327 continue;
2330 if (a.Expr.Type == TypeManager.null_type)
2331 continue;
2333 if (TypeManager.IsValueType (method_parameter)) {
2334 score -= tic.LowerBoundInference (a.Type, method_parameter);
2335 continue;
2339 // Otherwise an output type inference is made
2341 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2345 // Part of the second phase but because it happens only once
2346 // we don't need to call it in cycle
2348 bool fixed_any = false;
2349 if (!tic.FixIndependentTypeArguments (ec, ptypes, ref fixed_any))
2350 return false;
2352 return DoSecondPhase (ec, tic, ptypes, !fixed_any);
2355 bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, Type[] methodParameters, bool fixDependent)
2357 bool fixed_any = false;
2358 if (fixDependent && !tic.FixDependentTypes (ec, ref fixed_any))
2359 return false;
2361 // If no further unfixed type variables exist, type inference succeeds
2362 if (!tic.UnfixedVariableExists)
2363 return true;
2365 if (!fixed_any && fixDependent)
2366 return false;
2368 // For all arguments where the corresponding argument output types
2369 // contain unfixed type variables but the input types do not,
2370 // an output type inference is made
2371 for (int i = 0; i < arg_count; i++) {
2373 // Align params arguments
2374 Type t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
2376 if (!TypeManager.IsDelegateType (t_i)) {
2377 if (TypeManager.DropGenericTypeArguments (t_i) != TypeManager.expression_type)
2378 continue;
2380 t_i = t_i.GetGenericArguments () [0];
2383 var mi = Delegate.GetInvokeMethod (ec.Compiler, t_i, t_i);
2384 Type rtype = mi.ReturnType;
2386 #if MS_COMPATIBLE
2387 // Blablabla, because reflection does not work with dynamic types
2388 // Type[] g_args = t_i.GetGenericArguments ();
2389 // rtype = g_args[rtype.GenericParameterPosition];
2390 #endif
2392 if (tic.IsReturnTypeNonDependent (ec, mi, rtype))
2393 score -= tic.OutputTypeInference (ec, arguments [i].Expr, t_i);
2397 return DoSecondPhase (ec, tic, methodParameters, true);
2401 public class TypeInferenceContext
2403 enum BoundKind
2405 Exact = 0,
2406 Lower = 1,
2407 Upper = 2
2410 class BoundInfo
2412 public readonly Type Type;
2413 public readonly BoundKind Kind;
2415 public BoundInfo (Type type, BoundKind kind)
2417 this.Type = type;
2418 this.Kind = kind;
2421 public override int GetHashCode ()
2423 return Type.GetHashCode ();
2426 public override bool Equals (object obj)
2428 BoundInfo a = (BoundInfo) obj;
2429 return Type == a.Type && Kind == a.Kind;
2433 readonly Type[] unfixed_types;
2434 readonly Type[] fixed_types;
2435 readonly List<BoundInfo>[] bounds;
2436 bool failed;
2438 public TypeInferenceContext (Type[] typeArguments)
2440 if (typeArguments.Length == 0)
2441 throw new ArgumentException ("Empty generic arguments");
2443 fixed_types = new Type [typeArguments.Length];
2444 for (int i = 0; i < typeArguments.Length; ++i) {
2445 if (typeArguments [i].IsGenericParameter) {
2446 if (bounds == null) {
2447 bounds = new List<BoundInfo> [typeArguments.Length];
2448 unfixed_types = new Type [typeArguments.Length];
2450 unfixed_types [i] = typeArguments [i];
2451 } else {
2452 fixed_types [i] = typeArguments [i];
2458 // Used together with AddCommonTypeBound fo implement
2459 // 7.4.2.13 Finding the best common type of a set of expressions
2461 public TypeInferenceContext ()
2463 fixed_types = new Type [1];
2464 unfixed_types = new Type [1];
2465 unfixed_types[0] = InternalType.Arglist; // it can be any internal type
2466 bounds = new List<BoundInfo> [1];
2469 public Type[] InferredTypeArguments {
2470 get {
2471 return fixed_types;
2475 public void AddCommonTypeBound (Type type)
2477 AddToBounds (new BoundInfo (type, BoundKind.Lower), 0);
2480 void AddToBounds (BoundInfo bound, int index)
2483 // Some types cannot be used as type arguments
2485 if (bound.Type == TypeManager.void_type || bound.Type.IsPointer)
2486 return;
2488 var a = bounds [index];
2489 if (a == null) {
2490 a = new List<BoundInfo> ();
2491 bounds [index] = a;
2492 } else {
2493 if (a.Contains (bound))
2494 return;
2498 // SPEC: does not cover type inference using constraints
2500 //if (TypeManager.IsGenericParameter (t)) {
2501 // GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
2502 // if (constraints != null) {
2503 // //if (constraints.EffectiveBaseClass != null)
2504 // // t = constraints.EffectiveBaseClass;
2505 // }
2507 a.Add (bound);
2510 bool AllTypesAreFixed (Type[] types)
2512 foreach (Type t in types) {
2513 if (t.IsGenericParameter) {
2514 if (!IsFixed (t))
2515 return false;
2516 continue;
2519 if (t.IsGenericType)
2520 return AllTypesAreFixed (t.GetGenericArguments ());
2523 return true;
2527 // 26.3.3.8 Exact Inference
2529 public int ExactInference (Type u, Type v)
2531 // If V is an array type
2532 if (v.IsArray) {
2533 if (!u.IsArray)
2534 return 0;
2536 if (u.GetArrayRank () != v.GetArrayRank ())
2537 return 0;
2539 return ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
2542 // If V is constructed type and U is constructed type
2543 if (v.IsGenericType && !v.IsGenericTypeDefinition) {
2544 if (!u.IsGenericType)
2545 return 0;
2547 Type [] ga_u = u.GetGenericArguments ();
2548 Type [] ga_v = v.GetGenericArguments ();
2549 if (ga_u.Length != ga_v.Length)
2550 return 0;
2552 int score = 0;
2553 for (int i = 0; i < ga_u.Length; ++i)
2554 score += ExactInference (ga_u [i], ga_v [i]);
2556 return score > 0 ? 1 : 0;
2559 // If V is one of the unfixed type arguments
2560 int pos = IsUnfixed (v);
2561 if (pos == -1)
2562 return 0;
2564 AddToBounds (new BoundInfo (u, BoundKind.Exact), pos);
2565 return 1;
2568 public bool FixAllTypes (ResolveContext ec)
2570 for (int i = 0; i < unfixed_types.Length; ++i) {
2571 if (!FixType (ec, i))
2572 return false;
2574 return true;
2578 // All unfixed type variables Xi are fixed for which all of the following hold:
2579 // a, There is at least one type variable Xj that depends on Xi
2580 // b, Xi has a non-empty set of bounds
2582 public bool FixDependentTypes (ResolveContext ec, ref bool fixed_any)
2584 for (int i = 0; i < unfixed_types.Length; ++i) {
2585 if (unfixed_types[i] == null)
2586 continue;
2588 if (bounds[i] == null)
2589 continue;
2591 if (!FixType (ec, i))
2592 return false;
2594 fixed_any = true;
2597 return true;
2601 // All unfixed type variables Xi which depend on no Xj are fixed
2603 public bool FixIndependentTypeArguments (ResolveContext ec, Type[] methodParameters, ref bool fixed_any)
2605 var types_to_fix = new List<Type> (unfixed_types);
2606 for (int i = 0; i < methodParameters.Length; ++i) {
2607 Type t = methodParameters[i];
2609 if (!TypeManager.IsDelegateType (t)) {
2610 if (TypeManager.DropGenericTypeArguments (t) != TypeManager.expression_type)
2611 continue;
2613 t = t.GetGenericArguments () [0];
2616 if (t.IsGenericParameter)
2617 continue;
2619 var invoke = Delegate.GetInvokeMethod (ec.Compiler, t, t);
2620 Type rtype = invoke.ReturnType;
2621 if (!rtype.IsGenericParameter && !rtype.IsGenericType)
2622 continue;
2624 #if MS_COMPATIBLE
2625 // Blablabla, because reflection does not work with dynamic types
2626 // if (rtype.IsGenericParameter) {
2627 // Type [] g_args = t.GetGenericArguments ();
2628 // rtype = g_args [rtype.GenericParameterPosition];
2629 // }
2630 #endif
2631 // Remove dependent types, they cannot be fixed yet
2632 RemoveDependentTypes (types_to_fix, rtype);
2635 foreach (Type t in types_to_fix) {
2636 if (t == null)
2637 continue;
2639 int idx = IsUnfixed (t);
2640 if (idx >= 0 && !FixType (ec, idx)) {
2641 return false;
2645 fixed_any = types_to_fix.Count > 0;
2646 return true;
2650 // 26.3.3.10 Fixing
2652 public bool FixType (ResolveContext ec, int i)
2654 // It's already fixed
2655 if (unfixed_types[i] == null)
2656 throw new InternalErrorException ("Type argument has been already fixed");
2658 if (failed)
2659 return false;
2661 var candidates = bounds [i];
2662 if (candidates == null)
2663 return false;
2665 if (candidates.Count == 1) {
2666 unfixed_types[i] = null;
2667 Type t = candidates[0].Type;
2668 if (t == TypeManager.null_type)
2669 return false;
2671 fixed_types [i] = t;
2672 return true;
2676 // Determines a unique type from which there is
2677 // a standard implicit conversion to all the other
2678 // candidate types.
2680 Type best_candidate = null;
2681 int cii;
2682 int candidates_count = candidates.Count;
2683 for (int ci = 0; ci < candidates_count; ++ci) {
2684 BoundInfo bound = (BoundInfo)candidates [ci];
2685 for (cii = 0; cii < candidates_count; ++cii) {
2686 if (cii == ci)
2687 continue;
2689 BoundInfo cbound = (BoundInfo) candidates[cii];
2691 // Same type parameters with different bounds
2692 if (cbound.Type == bound.Type) {
2693 if (bound.Kind != BoundKind.Exact)
2694 bound = cbound;
2696 continue;
2699 if (bound.Kind == BoundKind.Exact || cbound.Kind == BoundKind.Exact) {
2700 if (cbound.Kind != BoundKind.Exact) {
2701 if (!Convert.ImplicitConversionExists (ec, new TypeExpression (cbound.Type, Location.Null), bound.Type)) {
2702 break;
2705 continue;
2708 if (bound.Kind != BoundKind.Exact) {
2709 if (!Convert.ImplicitConversionExists (ec, new TypeExpression (bound.Type, Location.Null), cbound.Type)) {
2710 break;
2713 bound = cbound;
2714 continue;
2717 break;
2720 if (bound.Kind == BoundKind.Lower) {
2721 if (!Convert.ImplicitConversionExists (ec, new TypeExpression (cbound.Type, Location.Null), bound.Type)) {
2722 break;
2724 } else {
2725 if (!Convert.ImplicitConversionExists (ec, new TypeExpression (bound.Type, Location.Null), cbound.Type)) {
2726 break;
2731 if (cii != candidates_count)
2732 continue;
2734 if (best_candidate != null && best_candidate != bound.Type)
2735 return false;
2737 best_candidate = bound.Type;
2740 if (best_candidate == null)
2741 return false;
2743 unfixed_types[i] = null;
2744 fixed_types[i] = best_candidate;
2745 return true;
2749 // Uses inferred types to inflate delegate type argument
2751 public Type InflateGenericArgument (Type parameter)
2753 if (parameter.IsGenericParameter) {
2755 // Inflate method generic argument (MVAR) only
2757 if (parameter.DeclaringMethod == null)
2758 return parameter;
2760 return fixed_types [parameter.GenericParameterPosition];
2763 if (parameter.IsGenericType) {
2764 Type [] parameter_targs = parameter.GetGenericArguments ();
2765 for (int ii = 0; ii < parameter_targs.Length; ++ii) {
2766 parameter_targs [ii] = InflateGenericArgument (parameter_targs [ii]);
2768 return parameter.GetGenericTypeDefinition ().MakeGenericType (parameter_targs);
2771 return parameter;
2775 // Tests whether all delegate input arguments are fixed and generic output type
2776 // requires output type inference
2778 public bool IsReturnTypeNonDependent (ResolveContext ec, MethodSpec invoke, Type returnType)
2780 if (returnType.IsGenericParameter) {
2781 if (IsFixed (returnType))
2782 return false;
2783 } else if (returnType.IsGenericType) {
2784 if (TypeManager.IsDelegateType (returnType)) {
2785 invoke = Delegate.GetInvokeMethod (ec.Compiler, returnType, returnType);
2786 return IsReturnTypeNonDependent (ec, invoke, invoke.ReturnType);
2789 Type[] g_args = returnType.GetGenericArguments ();
2791 // At least one unfixed return type has to exist
2792 if (AllTypesAreFixed (g_args))
2793 return false;
2794 } else {
2795 return false;
2798 // All generic input arguments have to be fixed
2799 AParametersCollection d_parameters = invoke.Parameters;
2800 return AllTypesAreFixed (d_parameters.Types);
2803 bool IsFixed (Type type)
2805 return IsUnfixed (type) == -1;
2808 int IsUnfixed (Type type)
2810 if (!type.IsGenericParameter)
2811 return -1;
2813 //return unfixed_types[type.GenericParameterPosition] != null;
2814 for (int i = 0; i < unfixed_types.Length; ++i) {
2815 if (unfixed_types [i] == type)
2816 return i;
2819 return -1;
2823 // 26.3.3.9 Lower-bound Inference
2825 public int LowerBoundInference (Type u, Type v)
2827 return LowerBoundInference (u, v, false);
2831 // Lower-bound (false) or Upper-bound (true) inference based on inversed argument
2833 int LowerBoundInference (Type u, Type v, bool inversed)
2835 // If V is one of the unfixed type arguments
2836 int pos = IsUnfixed (v);
2837 if (pos != -1) {
2838 AddToBounds (new BoundInfo (u, inversed ? BoundKind.Upper : BoundKind.Lower), pos);
2839 return 1;
2842 // If U is an array type
2843 if (u.IsArray) {
2844 int u_dim = u.GetArrayRank ();
2845 Type v_i;
2846 Type u_i = TypeManager.GetElementType (u);
2848 if (v.IsArray) {
2849 if (u_dim != v.GetArrayRank ())
2850 return 0;
2852 v_i = TypeManager.GetElementType (v);
2854 if (TypeManager.IsValueType (u_i))
2855 return ExactInference (u_i, v_i);
2857 return LowerBoundInference (u_i, v_i, inversed);
2860 if (u_dim != 1)
2861 return 0;
2863 if (v.IsGenericType) {
2864 Type g_v = v.GetGenericTypeDefinition ();
2865 if ((g_v != TypeManager.generic_ilist_type) && (g_v != TypeManager.generic_icollection_type) &&
2866 (g_v != TypeManager.generic_ienumerable_type))
2867 return 0;
2869 v_i = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (v) [0]);
2870 if (TypeManager.IsValueType (u_i))
2871 return ExactInference (u_i, v_i);
2873 return LowerBoundInference (u_i, v_i);
2875 } else if (v.IsGenericType && !v.IsGenericTypeDefinition) {
2877 // if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
2878 // such that U is identical to, inherits from (directly or indirectly),
2879 // or implements (directly or indirectly) C<U1..Uk>
2881 var u_candidates = new List<Type> ();
2882 if (u.IsGenericType)
2883 u_candidates.Add (u);
2885 for (Type t = u.BaseType; t != null; t = t.BaseType) {
2886 if (t.IsGenericType && !t.IsGenericTypeDefinition)
2887 u_candidates.Add (t);
2890 // TODO: Implement GetGenericInterfaces only and remove
2891 // the if from foreach
2892 u_candidates.AddRange (TypeManager.GetInterfaces (u));
2894 Type open_v = v.GetGenericTypeDefinition ();
2895 Type [] unique_candidate_targs = null;
2896 Type [] ga_v = v.GetGenericArguments ();
2897 foreach (Type u_candidate in u_candidates) {
2898 if (!u_candidate.IsGenericType || u_candidate.IsGenericTypeDefinition)
2899 continue;
2901 if (TypeManager.DropGenericTypeArguments (u_candidate) != open_v)
2902 continue;
2905 // The unique set of types U1..Uk means that if we have an interface I<T>,
2906 // class U : I<int>, I<long> then no type inference is made when inferring
2907 // type I<T> by applying type U because T could be int or long
2909 if (unique_candidate_targs != null) {
2910 Type[] second_unique_candidate_targs = u_candidate.GetGenericArguments ();
2911 if (TypeManager.IsEqual (unique_candidate_targs, second_unique_candidate_targs)) {
2912 unique_candidate_targs = second_unique_candidate_targs;
2913 continue;
2917 // This should always cause type inference failure
2919 failed = true;
2920 return 1;
2923 unique_candidate_targs = u_candidate.GetGenericArguments ();
2926 if (unique_candidate_targs != null) {
2927 Type[] ga_open_v = open_v.GetGenericArguments ();
2928 int score = 0;
2929 for (int i = 0; i < unique_candidate_targs.Length; ++i) {
2930 Variance variance = TypeManager.GetTypeParameterVariance (ga_open_v [i]);
2932 Type u_i = unique_candidate_targs [i];
2933 if (variance == Variance.None || TypeManager.IsValueType (u_i)) {
2934 if (ExactInference (u_i, ga_v [i]) == 0)
2935 ++score;
2936 } else {
2937 bool upper_bound = (variance == Variance.Contravariant && !inversed) ||
2938 (variance == Variance.Covariant && inversed);
2940 if (LowerBoundInference (u_i, ga_v [i], upper_bound) == 0)
2941 ++score;
2944 return score;
2948 return 0;
2952 // 26.3.3.6 Output Type Inference
2954 public int OutputTypeInference (ResolveContext ec, Expression e, Type t)
2956 // If e is a lambda or anonymous method with inferred return type
2957 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
2958 if (ame != null) {
2959 Type rt = ame.InferReturnType (ec, this, t);
2960 var invoke = Delegate.GetInvokeMethod (ec.Compiler, t, t);
2962 if (rt == null) {
2963 AParametersCollection pd = invoke.Parameters;
2964 return ame.Parameters.Count == pd.Count ? 1 : 0;
2967 Type rtype = invoke.ReturnType;
2968 #if MS_COMPATIBLE
2969 // Blablabla, because reflection does not work with dynamic types
2970 // Type [] g_args = t.GetGenericArguments ();
2971 // rtype = g_args [rtype.GenericParameterPosition];
2972 #endif
2973 return LowerBoundInference (rt, rtype) + 1;
2977 // if E is a method group and T is a delegate type or expression tree type
2978 // return type Tb with parameter types T1..Tk and return type Tb, and overload
2979 // resolution of E with the types T1..Tk yields a single method with return type U,
2980 // then a lower-bound inference is made from U for Tb.
2982 if (e is MethodGroupExpr) {
2983 // TODO: Or expression tree
2984 if (!TypeManager.IsDelegateType (t))
2985 return 0;
2987 var invoke = Delegate.GetInvokeMethod (ec.Compiler, t, t);
2988 Type rtype = invoke.ReturnType;
2989 #if MS_COMPATIBLE
2990 // Blablabla, because reflection does not work with dynamic types
2991 // Type [] g_args = t.GetGenericArguments ();
2992 // rtype = g_args [rtype.GenericParameterPosition];
2993 #endif
2995 if (!TypeManager.IsGenericType (rtype))
2996 return 0;
2998 MethodGroupExpr mg = (MethodGroupExpr) e;
2999 Arguments args = DelegateCreation.CreateDelegateMethodArguments (invoke.Parameters, e.Location);
3000 mg = mg.OverloadResolve (ec, ref args, true, e.Location);
3001 if (mg == null)
3002 return 0;
3004 // TODO: What should happen when return type is of generic type ?
3005 throw new NotImplementedException ();
3006 // return LowerBoundInference (null, rtype) + 1;
3010 // if e is an expression with type U, then
3011 // a lower-bound inference is made from U for T
3013 return LowerBoundInference (e.Type, t) * 2;
3016 void RemoveDependentTypes (List<Type> types, Type returnType)
3018 int idx = IsUnfixed (returnType);
3019 if (idx >= 0) {
3020 types [idx] = null;
3021 return;
3024 if (returnType.IsGenericType) {
3025 foreach (Type t in returnType.GetGenericArguments ()) {
3026 RemoveDependentTypes (types, t);
3031 public bool UnfixedVariableExists {
3032 get {
3033 if (unfixed_types == null)
3034 return false;
3036 foreach (Type ut in unfixed_types)
3037 if (ut != null)
3038 return true;
3039 return false;