2010-04-06 Jb Evain <jbevain@novell.com>
[mcs.git] / mcs / generic.cs
blob9df0cb14e6ee27712c2bb47300fe5f51f727a33f
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 MethodBase mb = TypeManager.DropGenericMethodArguments (implementing);
822 int pos = type.GenericParameterPosition;
823 Type mparam = mb.GetGenericArguments () [pos];
824 GenericConstraints temp_gc = ReflectionConstraints.GetConstraints (mparam);
826 if (temp_gc != null)
827 gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
828 else if (constraints != null)
829 gc = new InflatedConstraints (constraints, implementing.DeclaringType);
831 bool ok = true;
832 if (constraints != null) {
833 if (temp_gc == null)
834 ok = false;
835 else if (!constraints.AreEqual (gc))
836 ok = false;
837 } else {
838 if (!is_override && (temp_gc != null))
839 ok = false;
842 if (!ok) {
843 Report.SymbolRelatedToPreviousError (implementing);
845 Report.Error (
846 425, Location, "The constraints for type " +
847 "parameter `{0}' of method `{1}' must match " +
848 "the constraints for type parameter `{2}' " +
849 "of interface method `{3}'. Consider using " +
850 "an explicit interface implementation instead",
851 Name, TypeManager.CSharpSignature (builder),
852 TypeManager.CSharpName (mparam), TypeManager.CSharpSignature (mb));
853 return false;
855 } else if (DeclSpace is CompilerGeneratedClass) {
856 TypeParameter[] tparams = DeclSpace.TypeParameters;
857 Type[] types = new Type [tparams.Length];
858 for (int i = 0; i < tparams.Length; i++)
859 types [i] = tparams [i].Type;
861 if (constraints != null)
862 gc = new InflatedConstraints (constraints, types);
863 } else {
864 gc = (GenericConstraints) constraints;
867 SetConstraints (type);
868 return true;
871 public static TypeParameter FindTypeParameter (TypeParameter[] tparams, string name)
873 foreach (var tp in tparams) {
874 if (tp.Name == name)
875 return tp;
878 return null;
881 public void SetConstraints (GenericTypeParameterBuilder type)
883 GenericParameterAttributes attr = GenericParameterAttributes.None;
884 if (variance == Variance.Contravariant)
885 attr |= GenericParameterAttributes.Contravariant;
886 else if (variance == Variance.Covariant)
887 attr |= GenericParameterAttributes.Covariant;
889 if (gc != null) {
890 if (gc.HasClassConstraint || gc.HasValueTypeConstraint)
891 type.SetBaseTypeConstraint (gc.EffectiveBaseClass);
893 attr |= gc.Attributes;
894 type.SetInterfaceConstraints (gc.InterfaceConstraints);
895 TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
898 type.SetGenericParameterAttributes (attr);
901 /// <summary>
902 /// This is called for each part of a partial generic type definition.
904 /// If `new_constraints' is not null and we don't already have constraints,
905 /// they become our constraints. If we already have constraints, we must
906 /// check that they're the same.
907 /// con
908 /// </summary>
909 public bool UpdateConstraints (MemberCore ec, Constraints new_constraints)
911 if (type == null)
912 throw new InvalidOperationException ();
914 if (new_constraints == null)
915 return true;
917 if (!new_constraints.Resolve (ec, this, Report))
918 return false;
919 if (!new_constraints.ResolveTypes (ec, Report))
920 return false;
922 if (constraints != null)
923 return constraints.AreEqual (new_constraints);
925 constraints = new_constraints;
926 return true;
929 public override void Emit ()
931 if (OptAttributes != null)
932 OptAttributes.Emit ();
934 base.Emit ();
937 public override string DocCommentHeader {
938 get {
939 throw new InvalidOperationException (
940 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
945 // MemberContainer
948 public override bool Define ()
950 return true;
953 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
955 type.SetCustomAttribute (cb);
958 public override AttributeTargets AttributeTargets {
959 get {
960 return AttributeTargets.GenericParameter;
964 public override string[] ValidAttributeTargets {
965 get {
966 return attribute_target;
971 // IMemberContainer
974 string IMemberContainer.Name {
975 get { return Name; }
978 MemberCache IMemberContainer.BaseCache {
979 get {
980 if (gc == null)
981 return null;
983 if (gc.EffectiveBaseClass.BaseType == null)
984 return null;
986 return TypeManager.LookupMemberCache (gc.EffectiveBaseClass.BaseType);
990 bool IMemberContainer.IsInterface {
991 get { return false; }
994 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
996 throw new NotSupportedException ();
999 public MemberCache MemberCache {
1000 get {
1001 if (member_cache != null)
1002 return member_cache;
1004 if (gc == null)
1005 return null;
1007 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
1008 member_cache = new MemberCache (this, gc.EffectiveBaseClass, ifaces);
1010 return member_cache;
1014 public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1015 MemberFilter filter, object criteria)
1017 if (gc == null)
1018 return MemberList.Empty;
1020 var members = new List<MemberInfo> ();
1022 if (gc.HasClassConstraint) {
1023 MemberList list = TypeManager.FindMembers (
1024 gc.ClassConstraint, mt, bf, filter, criteria);
1026 members.AddRange (list);
1029 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
1030 foreach (Type t in ifaces) {
1031 MemberList list = TypeManager.FindMembers (
1032 t, mt, bf, filter, criteria);
1034 members.AddRange (list);
1037 return new MemberList (members);
1040 public bool IsSubclassOf (Type t)
1042 if (type.Equals (t))
1043 return true;
1045 if (constraints != null)
1046 return constraints.IsSubclassOf (t);
1048 return false;
1051 public void InflateConstraints (Type declaring)
1053 if (constraints != null)
1054 gc = new InflatedConstraints (constraints, declaring);
1057 public override bool IsClsComplianceRequired ()
1059 return false;
1062 protected class InflatedConstraints : GenericConstraints
1064 GenericConstraints gc;
1065 Type base_type;
1066 Type class_constraint;
1067 Type[] iface_constraints;
1068 Type[] dargs;
1070 public InflatedConstraints (GenericConstraints gc, Type declaring)
1071 : this (gc, TypeManager.GetTypeArguments (declaring))
1074 public InflatedConstraints (GenericConstraints gc, Type[] dargs)
1076 this.gc = gc;
1077 this.dargs = dargs;
1079 var list = new List<Type> ();
1080 if (gc.HasClassConstraint)
1081 list.Add (inflate (gc.ClassConstraint));
1082 foreach (Type iface in gc.InterfaceConstraints)
1083 list.Add (inflate (iface));
1085 bool has_class_constr = false;
1086 if (list.Count > 0) {
1087 Type first = (Type) list [0];
1088 has_class_constr = !first.IsGenericParameter && !first.IsInterface;
1091 if ((list.Count > 0) && has_class_constr) {
1092 class_constraint = (Type) list [0];
1093 iface_constraints = new Type [list.Count - 1];
1094 list.CopyTo (1, iface_constraints, 0, list.Count - 1);
1095 } else {
1096 iface_constraints = new Type [list.Count];
1097 list.CopyTo (iface_constraints, 0);
1100 if (HasValueTypeConstraint)
1101 base_type = TypeManager.value_type;
1102 else if (class_constraint != null)
1103 base_type = class_constraint;
1104 else
1105 base_type = TypeManager.object_type;
1108 Type inflate (Type t)
1110 if (t == null)
1111 return null;
1112 if (t.IsGenericParameter)
1113 return t.GenericParameterPosition < dargs.Length ? dargs [t.GenericParameterPosition] : t;
1114 if (t.IsGenericType) {
1115 Type[] args = t.GetGenericArguments ();
1116 Type[] inflated = new Type [args.Length];
1118 for (int i = 0; i < args.Length; i++)
1119 inflated [i] = inflate (args [i]);
1121 t = t.GetGenericTypeDefinition ();
1122 t = t.MakeGenericType (inflated);
1125 return t;
1128 public override GenericParameterAttributes Attributes {
1129 get { return gc.Attributes; }
1132 public override Type ClassConstraint {
1133 get { return class_constraint; }
1136 public override Type EffectiveBaseClass {
1137 get { return base_type; }
1140 public override Type[] InterfaceConstraints {
1141 get { return iface_constraints; }
1146 /// <summary>
1147 /// A TypeExpr which already resolved to a type parameter.
1148 /// </summary>
1149 public class TypeParameterExpr : TypeExpr {
1151 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1153 this.type = type_parameter.Type;
1154 this.eclass = ExprClass.TypeParameter;
1155 this.loc = loc;
1158 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
1160 throw new NotSupportedException ();
1163 public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
1165 return this;
1168 public override bool IsInterface {
1169 get { return false; }
1172 public override bool CheckAccessLevel (IMemberContext ds)
1174 return true;
1179 // Tracks the type arguments when instantiating a generic type. It's used
1180 // by both type arguments and type parameters
1182 public class TypeArguments {
1183 List<FullNamedExpression> args;
1184 Type[] atypes;
1186 public TypeArguments ()
1188 args = new List<FullNamedExpression> ();
1191 public TypeArguments (params FullNamedExpression[] types)
1193 this.args = new List<FullNamedExpression> (types);
1196 public void Add (FullNamedExpression type)
1198 args.Add (type);
1201 public void Add (TypeArguments new_args)
1203 args.AddRange (new_args.args);
1206 // TODO: Kill this monster
1207 public TypeParameterName[] GetDeclarations ()
1209 return args.ConvertAll (i => (TypeParameterName) i).ToArray ();
1212 /// <summary>
1213 /// We may only be used after Resolve() is called and return the fully
1214 /// resolved types.
1215 /// </summary>
1216 public Type[] Arguments {
1217 get {
1218 return atypes;
1222 public int Count {
1223 get {
1224 return args.Count;
1228 public string GetSignatureForError()
1230 StringBuilder sb = new StringBuilder();
1231 for (int i = 0; i < Count; ++i)
1233 Expression expr = (Expression)args [i];
1234 sb.Append(expr.GetSignatureForError());
1235 if (i + 1 < Count)
1236 sb.Append(',');
1238 return sb.ToString();
1241 /// <summary>
1242 /// Resolve the type arguments.
1243 /// </summary>
1244 public bool Resolve (IMemberContext ec)
1246 if (atypes != null)
1247 return atypes.Length != 0;
1249 int count = args.Count;
1250 bool ok = true;
1252 atypes = new Type [count];
1254 for (int i = 0; i < count; i++){
1255 TypeExpr te = ((FullNamedExpression) args[i]).ResolveAsTypeTerminal (ec, false);
1256 if (te == null) {
1257 ok = false;
1258 continue;
1261 atypes[i] = te.Type;
1263 if (te.Type.IsSealed && te.Type.IsAbstract) {
1264 ec.Compiler.Report.Error (718, te.Location, "`{0}': static classes cannot be used as generic arguments",
1265 te.GetSignatureForError ());
1266 ok = false;
1269 if (te.Type.IsPointer || TypeManager.IsSpecialType (te.Type)) {
1270 ec.Compiler.Report.Error (306, te.Location,
1271 "The type `{0}' may not be used as a type argument",
1272 te.GetSignatureForError ());
1273 ok = false;
1277 if (!ok)
1278 atypes = Type.EmptyTypes;
1280 return ok;
1283 public TypeArguments Clone ()
1285 TypeArguments copy = new TypeArguments ();
1286 foreach (var ta in args)
1287 copy.args.Add (ta);
1289 return copy;
1293 public class TypeParameterName : SimpleName
1295 Attributes attributes;
1296 Variance variance;
1298 public TypeParameterName (string name, Attributes attrs, Location loc)
1299 : this (name, attrs, Variance.None, loc)
1303 public TypeParameterName (string name, Attributes attrs, Variance variance, Location loc)
1304 : base (name, loc)
1306 attributes = attrs;
1307 this.variance = variance;
1310 public Attributes OptAttributes {
1311 get {
1312 return attributes;
1316 public Variance Variance {
1317 get {
1318 return variance;
1323 /// <summary>
1324 /// A reference expression to generic type
1325 /// </summary>
1326 class GenericTypeExpr : TypeExpr
1328 TypeArguments args;
1329 Type[] gen_params; // TODO: Waiting for constrains check cleanup
1330 Type open_type;
1333 // Should be carefully used only with defined generic containers. Type parameters
1334 // can be used as type arguments in this case.
1336 // TODO: This could be GenericTypeExpr specialization
1338 public GenericTypeExpr (DeclSpace gType, Location l)
1340 open_type = gType.TypeBuilder.GetGenericTypeDefinition ();
1342 args = new TypeArguments ();
1343 foreach (TypeParameter type_param in gType.TypeParameters)
1344 args.Add (new TypeParameterExpr (type_param, l));
1346 this.loc = l;
1349 /// <summary>
1350 /// Instantiate the generic type `t' with the type arguments `args'.
1351 /// Use this constructor if you already know the fully resolved
1352 /// generic type.
1353 /// </summary>
1354 public GenericTypeExpr (Type t, TypeArguments args, Location l)
1356 open_type = t.GetGenericTypeDefinition ();
1358 loc = l;
1359 this.args = args;
1362 public TypeArguments TypeArguments {
1363 get { return args; }
1366 public override string GetSignatureForError ()
1368 return TypeManager.CSharpName (type);
1371 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
1373 eclass = ExprClass.Type;
1375 if (!args.Resolve (ec))
1376 return null;
1378 gen_params = open_type.GetGenericArguments ();
1379 Type[] atypes = args.Arguments;
1381 if (atypes.Length != gen_params.Length) {
1382 Namespace.Error_InvalidNumberOfTypeArguments (ec.Compiler.Report, open_type, loc);
1383 return null;
1387 // Now bind the parameters
1389 type = open_type.MakeGenericType (atypes);
1390 return this;
1393 /// <summary>
1394 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1395 /// after fully resolving the constructed type.
1396 /// </summary>
1397 public bool CheckConstraints (IMemberContext ec)
1399 return ConstraintChecker.CheckConstraints (ec, open_type, gen_params, args.Arguments, loc);
1402 public override bool CheckAccessLevel (IMemberContext mc)
1404 return mc.CurrentTypeDefinition.CheckAccessLevel (open_type);
1407 public bool HasDynamicArguments ()
1409 return HasDynamicArguments (args.Arguments);
1412 static bool HasDynamicArguments (Type[] args)
1414 foreach (var item in args)
1416 if (TypeManager.IsGenericType (item))
1417 return HasDynamicArguments (TypeManager.GetTypeArguments (item));
1419 if (TypeManager.IsDynamicType (item))
1420 return true;
1423 return false;
1426 public override bool IsClass {
1427 get { return open_type.IsClass; }
1430 public override bool IsValueType {
1431 get { return TypeManager.IsStruct (open_type); }
1434 public override bool IsInterface {
1435 get { return open_type.IsInterface; }
1438 public override bool IsSealed {
1439 get { return open_type.IsSealed; }
1442 public override bool Equals (object obj)
1444 GenericTypeExpr cobj = obj as GenericTypeExpr;
1445 if (cobj == null)
1446 return false;
1448 if ((type == null) || (cobj.type == null))
1449 return false;
1451 return type == cobj.type;
1454 public override int GetHashCode ()
1456 return base.GetHashCode ();
1460 public abstract class ConstraintChecker
1462 protected readonly Type[] gen_params;
1463 protected readonly Type[] atypes;
1464 protected readonly Location loc;
1465 protected Report Report;
1467 protected ConstraintChecker (Type[] gen_params, Type[] atypes, Location loc, Report r)
1469 this.gen_params = gen_params;
1470 this.atypes = atypes;
1471 this.loc = loc;
1472 this.Report = r;
1475 /// <summary>
1476 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1477 /// after fully resolving the constructed type.
1478 /// </summary>
1479 public bool CheckConstraints (IMemberContext ec)
1481 for (int i = 0; i < gen_params.Length; i++) {
1482 if (!CheckConstraints (ec, i))
1483 return false;
1486 return true;
1489 protected bool CheckConstraints (IMemberContext ec, int index)
1491 Type atype = TypeManager.TypeToCoreType (atypes [index]);
1492 Type ptype = gen_params [index];
1494 if (atype == ptype)
1495 return true;
1497 Expression aexpr = new EmptyExpression (atype);
1499 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1500 if (gc == null)
1501 return true;
1503 bool is_class, is_struct;
1504 if (atype.IsGenericParameter) {
1505 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1506 if (agc != null) {
1507 if (agc is Constraints) {
1508 // FIXME: No constraints can be resolved here, we are in
1509 // completely wrong/different context. This path is hit
1510 // when resolving base type of unresolved generic type
1511 // with constraints. We are waiting with CheckConsttraints
1512 // after type-definition but not in this case
1513 if (!((Constraints) agc).Resolve (null, null, Report))
1514 return true;
1516 is_class = agc.IsReferenceType;
1517 is_struct = agc.IsValueType;
1518 } else {
1519 is_class = is_struct = false;
1521 } else {
1522 is_class = TypeManager.IsReferenceType (atype);
1523 is_struct = TypeManager.IsValueType (atype) && !TypeManager.IsNullableType (atype);
1527 // First, check the `class' and `struct' constraints.
1529 if (gc.HasReferenceTypeConstraint && !is_class) {
1530 Report.Error (452, loc, "The type `{0}' must be " +
1531 "a reference type in order to use it " +
1532 "as type parameter `{1}' in the " +
1533 "generic type or method `{2}'.",
1534 TypeManager.CSharpName (atype),
1535 TypeManager.CSharpName (ptype),
1536 GetSignatureForError ());
1537 return false;
1538 } else if (gc.HasValueTypeConstraint && !is_struct) {
1539 Report.Error (453, loc, "The type `{0}' must be a " +
1540 "non-nullable value type in order to use it " +
1541 "as type parameter `{1}' in the " +
1542 "generic type or method `{2}'.",
1543 TypeManager.CSharpName (atype),
1544 TypeManager.CSharpName (ptype),
1545 GetSignatureForError ());
1546 return false;
1550 // The class constraint comes next.
1552 if (gc.HasClassConstraint) {
1553 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint))
1554 return false;
1558 // Now, check the interface constraints.
1560 if (gc.InterfaceConstraints != null) {
1561 foreach (Type it in gc.InterfaceConstraints) {
1562 if (!CheckConstraint (ec, ptype, aexpr, it))
1563 return false;
1568 // Finally, check the constructor constraint.
1571 if (!gc.HasConstructorConstraint)
1572 return true;
1574 if (TypeManager.IsValueType (atype))
1575 return true;
1577 if (HasDefaultConstructor (atype))
1578 return true;
1580 Report_SymbolRelatedToPreviousError ();
1581 Report.SymbolRelatedToPreviousError (atype);
1582 Report.Error (310, loc, "The type `{0}' must have a public " +
1583 "parameterless constructor in order to use it " +
1584 "as parameter `{1}' in the generic type or " +
1585 "method `{2}'",
1586 TypeManager.CSharpName (atype),
1587 TypeManager.CSharpName (ptype),
1588 GetSignatureForError ());
1589 return false;
1592 Type InflateType(IMemberContext ec, Type ctype)
1594 Type[] types = TypeManager.GetTypeArguments (ctype);
1596 TypeArguments new_args = new TypeArguments ();
1598 for (int i = 0; i < types.Length; i++) {
1599 Type t = TypeManager.TypeToCoreType (types [i]);
1601 if (t.IsGenericParameter) {
1602 int pos = t.GenericParameterPosition;
1603 if (t.DeclaringMethod == null && this is MethodConstraintChecker) {
1604 Type parent = ((MethodConstraintChecker) this).declaring_type;
1605 t = parent.GetGenericArguments ()[pos];
1606 } else {
1607 t = atypes [pos];
1609 } else if(TypeManager.HasGenericArguments(t)) {
1610 t = InflateType (ec, t);
1611 if (t == null) {
1612 return null;
1615 new_args.Add (new TypeExpression (t, loc));
1618 TypeExpr ct = new GenericTypeExpr (ctype, new_args, loc);
1619 if (ct.ResolveAsTypeStep (ec, false) == null)
1620 return null;
1622 return ct.Type;
1625 protected bool CheckConstraint (IMemberContext ec, Type ptype, Expression expr,
1626 Type ctype)
1629 // All this is needed because we don't have
1630 // real inflated type hierarchy
1632 if (TypeManager.HasGenericArguments (ctype)) {
1633 ctype = InflateType (ec, ctype);
1634 if(ctype == null) {
1635 return false;
1637 } else if (ctype.IsGenericParameter) {
1638 int pos = ctype.GenericParameterPosition;
1639 if (ctype.DeclaringMethod == null) {
1640 // FIXME: Implement
1641 return true;
1642 } else {
1643 ctype = atypes [pos];
1647 if (Convert.ImplicitStandardConversionExists (expr, ctype))
1648 return true;
1650 Report_SymbolRelatedToPreviousError ();
1651 Report.SymbolRelatedToPreviousError (expr.Type);
1653 if (TypeManager.IsNullableType (expr.Type) && ctype.IsInterface) {
1654 Report.Error (313, loc,
1655 "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. " +
1656 "The nullable type `{0}' never satisfies interface constraint of type `{3}'",
1657 TypeManager.CSharpName (expr.Type), TypeManager.CSharpName (ptype),
1658 GetSignatureForError (), TypeManager.CSharpName (ctype));
1659 } else {
1660 Report.Error (309, loc,
1661 "The type `{0}' must be convertible to `{1}' in order to " +
1662 "use it as parameter `{2}' in the generic type or method `{3}'",
1663 TypeManager.CSharpName (expr.Type), TypeManager.CSharpName (ctype),
1664 TypeManager.CSharpName (ptype), GetSignatureForError ());
1666 return false;
1669 static bool HasDefaultConstructor (Type atype)
1671 TypeParameter tparam = TypeManager.LookupTypeParameter (atype);
1672 if (tparam != null) {
1673 if (tparam.GenericConstraints == null)
1674 return false;
1676 return tparam.GenericConstraints.HasConstructorConstraint ||
1677 tparam.GenericConstraints.HasValueTypeConstraint;
1680 if (atype.IsAbstract)
1681 return false;
1683 again:
1684 atype = TypeManager.DropGenericTypeArguments (atype);
1685 if (atype is TypeBuilder) {
1686 TypeContainer tc = TypeManager.LookupTypeContainer (atype);
1687 if (tc.InstanceConstructors == null) {
1688 atype = atype.BaseType;
1689 goto again;
1692 foreach (Constructor c in tc.InstanceConstructors) {
1693 if ((c.ModFlags & Modifiers.PUBLIC) == 0)
1694 continue;
1695 if ((c.Parameters.FixedParameters != null) &&
1696 (c.Parameters.FixedParameters.Length != 0))
1697 continue;
1698 if (c.Parameters.HasArglist || c.Parameters.HasParams)
1699 continue;
1701 return true;
1705 MemberInfo [] list = TypeManager.MemberLookup (null, null, atype, MemberTypes.Constructor,
1706 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
1707 ConstructorInfo.ConstructorName, null);
1709 if (list == null)
1710 return false;
1712 foreach (MethodBase mb in list) {
1713 AParametersCollection pd = TypeManager.GetParameterData (mb);
1714 if (pd.Count == 0)
1715 return true;
1718 return false;
1721 protected abstract string GetSignatureForError ();
1722 protected abstract void Report_SymbolRelatedToPreviousError ();
1724 public static bool CheckConstraints (IMemberContext ec, MethodBase definition,
1725 MethodBase instantiated, Location loc)
1727 MethodConstraintChecker checker = new MethodConstraintChecker (
1728 definition, instantiated.DeclaringType, definition.GetGenericArguments (),
1729 instantiated.GetGenericArguments (), loc, ec.Compiler.Report);
1731 return checker.CheckConstraints (ec);
1734 public static bool CheckConstraints (IMemberContext ec, Type gt, Type[] gen_params,
1735 Type[] atypes, Location loc)
1737 TypeConstraintChecker checker = new TypeConstraintChecker (
1738 gt, gen_params, atypes, loc, ec.Compiler.Report);
1740 return checker.CheckConstraints (ec);
1743 protected class MethodConstraintChecker : ConstraintChecker
1745 MethodBase definition;
1746 public Type declaring_type;
1748 public MethodConstraintChecker (MethodBase definition, Type declaringType, Type[] gen_params,
1749 Type[] atypes, Location loc, Report r)
1750 : base (gen_params, atypes, loc, r)
1752 this.declaring_type = declaringType;
1753 this.definition = definition;
1756 protected override string GetSignatureForError ()
1758 return TypeManager.CSharpSignature (definition);
1761 protected override void Report_SymbolRelatedToPreviousError ()
1763 Report.SymbolRelatedToPreviousError (definition);
1767 protected class TypeConstraintChecker : ConstraintChecker
1769 Type gt;
1771 public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
1772 Location loc, Report r)
1773 : base (gen_params, atypes, loc, r)
1775 this.gt = gt;
1778 protected override string GetSignatureForError ()
1780 return TypeManager.CSharpName (gt);
1783 protected override void Report_SymbolRelatedToPreviousError ()
1785 Report.SymbolRelatedToPreviousError (gt);
1790 /// <summary>
1791 /// A generic method definition.
1792 /// </summary>
1793 public class GenericMethod : DeclSpace
1795 FullNamedExpression return_type;
1796 ParametersCompiled parameters;
1798 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
1799 FullNamedExpression return_type, ParametersCompiled parameters)
1800 : base (ns, parent, name, null)
1802 this.return_type = return_type;
1803 this.parameters = parameters;
1806 public override TypeContainer CurrentTypeDefinition {
1807 get {
1808 return Parent.CurrentTypeDefinition;
1812 public override TypeParameter[] CurrentTypeParameters {
1813 get {
1814 return base.type_params;
1818 public override TypeBuilder DefineType ()
1820 throw new Exception ();
1823 public override bool Define ()
1825 for (int i = 0; i < TypeParameters.Length; i++)
1826 if (!TypeParameters [i].Resolve (this))
1827 return false;
1829 return true;
1832 /// <summary>
1833 /// Define and resolve the type parameters.
1834 /// We're called from Method.Define().
1835 /// </summary>
1836 public bool Define (MethodOrOperator m)
1838 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1839 string[] snames = new string [names.Length];
1840 for (int i = 0; i < names.Length; i++) {
1841 string type_argument_name = names[i].Name;
1842 int idx = parameters.GetParameterIndexByName (type_argument_name);
1843 if (idx >= 0) {
1844 Block b = m.Block;
1845 if (b == null)
1846 b = new Block (null);
1848 b.Error_AlreadyDeclaredTypeParameter (Report, parameters [i].Location,
1849 type_argument_name, "method parameter");
1852 snames[i] = type_argument_name;
1855 GenericTypeParameterBuilder[] gen_params = m.MethodBuilder.DefineGenericParameters (snames);
1856 for (int i = 0; i < TypeParameters.Length; i++)
1857 TypeParameters [i].Define (gen_params [i]);
1859 if (!Define ())
1860 return false;
1862 for (int i = 0; i < TypeParameters.Length; i++) {
1863 if (!TypeParameters [i].ResolveType (this))
1864 return false;
1867 return true;
1870 /// <summary>
1871 /// We're called from MethodData.Define() after creating the MethodBuilder.
1872 /// </summary>
1873 public bool DefineType (IMemberContext ec, MethodBuilder mb,
1874 MethodInfo implementing, bool is_override)
1876 for (int i = 0; i < TypeParameters.Length; i++)
1877 if (!TypeParameters [i].DefineType (
1878 ec, mb, implementing, is_override))
1879 return false;
1881 bool ok = parameters.Resolve (ec);
1883 if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec, false) == null))
1884 ok = false;
1886 return ok;
1889 public void EmitAttributes ()
1891 for (int i = 0; i < TypeParameters.Length; i++)
1892 TypeParameters [i].Emit ();
1894 if (OptAttributes != null)
1895 OptAttributes.Emit ();
1898 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1899 MemberFilter filter, object criteria)
1901 throw new Exception ();
1904 public override string GetSignatureForError ()
1906 return base.GetSignatureForError () + parameters.GetSignatureForError ();
1909 public override MemberCache MemberCache {
1910 get {
1911 return null;
1915 public override AttributeTargets AttributeTargets {
1916 get {
1917 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1921 public override string DocCommentHeader {
1922 get { return "M:"; }
1925 public new void VerifyClsCompliance ()
1927 foreach (TypeParameter tp in TypeParameters) {
1928 if (tp.Constraints == null)
1929 continue;
1931 tp.Constraints.VerifyClsCompliance (Report);
1936 partial class TypeManager
1938 public static TypeContainer LookupGenericTypeContainer (Type t)
1940 t = DropGenericTypeArguments (t);
1941 return LookupTypeContainer (t);
1944 public static Variance GetTypeParameterVariance (Type type)
1946 TypeParameter tparam = LookupTypeParameter (type);
1947 if (tparam != null)
1948 return tparam.Variance;
1950 switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
1951 case GenericParameterAttributes.Covariant:
1952 return Variance.Covariant;
1953 case GenericParameterAttributes.Contravariant:
1954 return Variance.Contravariant;
1955 default:
1956 return Variance.None;
1960 public static Variance CheckTypeVariance (Type t, Variance expected, IMemberContext member)
1962 TypeParameter tp = LookupTypeParameter (t);
1963 if (tp != null) {
1964 Variance v = tp.Variance;
1965 if (expected == Variance.None && v != expected ||
1966 expected == Variance.Covariant && v == Variance.Contravariant ||
1967 expected == Variance.Contravariant && v == Variance.Covariant)
1968 tp.ErrorInvalidVariance (member, expected);
1970 return expected;
1973 if (t.IsGenericType) {
1974 Type[] targs_definition = GetTypeArguments (DropGenericTypeArguments (t));
1975 Type[] targs = GetTypeArguments (t);
1976 for (int i = 0; i < targs_definition.Length; ++i) {
1977 Variance v = GetTypeParameterVariance (targs_definition[i]);
1978 CheckTypeVariance (targs[i], (Variance) ((int)v * (int)expected), member);
1981 return expected;
1984 if (t.IsArray)
1985 return CheckTypeVariance (GetElementType (t), expected, member);
1987 return Variance.None;
1990 public static bool IsVariantOf (Type type1, Type type2)
1992 if (!type1.IsGenericType || !type2.IsGenericType)
1993 return false;
1995 Type generic_target_type = DropGenericTypeArguments (type2);
1996 if (DropGenericTypeArguments (type1) != generic_target_type)
1997 return false;
1999 Type[] t1 = GetTypeArguments (type1);
2000 Type[] t2 = GetTypeArguments (type2);
2001 Type[] targs_definition = GetTypeArguments (generic_target_type);
2002 for (int i = 0; i < targs_definition.Length; ++i) {
2003 Variance v = GetTypeParameterVariance (targs_definition [i]);
2004 if (v == Variance.None) {
2005 if (t1[i] == t2[i])
2006 continue;
2007 return false;
2010 if (v == Variance.Covariant) {
2011 if (!Convert.ImplicitReferenceConversionExists (new EmptyExpression (t1 [i]), t2 [i]))
2012 return false;
2013 } else if (!Convert.ImplicitReferenceConversionExists (new EmptyExpression (t2[i]), t1[i])) {
2014 return false;
2018 return true;
2021 /// <summary>
2022 /// Check whether `a' and `b' may become equal generic types.
2023 /// The algorithm to do that is a little bit complicated.
2024 /// </summary>
2025 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_inferred,
2026 Type[] method_inferred)
2028 if (a.IsGenericParameter) {
2030 // If a is an array of a's type, they may never
2031 // become equal.
2033 while (b.IsArray) {
2034 b = GetElementType (b);
2035 if (a.Equals (b))
2036 return false;
2040 // If b is a generic parameter or an actual type,
2041 // they may become equal:
2043 // class X<T,U> : I<T>, I<U>
2044 // class X<T> : I<T>, I<float>
2046 if (b.IsGenericParameter || !b.IsGenericType) {
2047 int pos = a.GenericParameterPosition;
2048 Type[] args = a.DeclaringMethod != null ? method_inferred : class_inferred;
2049 if (args [pos] == null) {
2050 args [pos] = b;
2051 return true;
2054 return args [pos] == a;
2058 // We're now comparing a type parameter with a
2059 // generic instance. They may become equal unless
2060 // the type parameter appears anywhere in the
2061 // generic instance:
2063 // class X<T,U> : I<T>, I<X<U>>
2064 // -> error because you could instanciate it as
2065 // X<X<int>,int>
2067 // class X<T> : I<T>, I<X<T>> -> ok
2070 Type[] bargs = GetTypeArguments (b);
2071 for (int i = 0; i < bargs.Length; i++) {
2072 if (a.Equals (bargs [i]))
2073 return false;
2076 return true;
2079 if (b.IsGenericParameter)
2080 return MayBecomeEqualGenericTypes (b, a, class_inferred, method_inferred);
2083 // At this point, neither a nor b are a type parameter.
2085 // If one of them is a generic instance, let
2086 // MayBecomeEqualGenericInstances() compare them (if the
2087 // other one is not a generic instance, they can never
2088 // become equal).
2091 if (a.IsGenericType || b.IsGenericType)
2092 return MayBecomeEqualGenericInstances (a, b, class_inferred, method_inferred);
2095 // If both of them are arrays.
2098 if (a.IsArray && b.IsArray) {
2099 if (a.GetArrayRank () != b.GetArrayRank ())
2100 return false;
2102 a = GetElementType (a);
2103 b = GetElementType (b);
2105 return MayBecomeEqualGenericTypes (a, b, class_inferred, method_inferred);
2109 // Ok, two ordinary types.
2112 return a.Equals (b);
2116 // Checks whether two generic instances may become equal for some
2117 // particular instantiation (26.3.1).
2119 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
2120 Type[] class_inferred,
2121 Type[] method_inferred)
2123 if (!a.IsGenericType || !b.IsGenericType)
2124 return false;
2125 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2126 return false;
2128 return MayBecomeEqualGenericInstances (
2129 GetTypeArguments (a), GetTypeArguments (b), class_inferred, method_inferred);
2132 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
2133 Type[] class_inferred,
2134 Type[] method_inferred)
2136 if (aargs.Length != bargs.Length)
2137 return false;
2139 for (int i = 0; i < aargs.Length; i++) {
2140 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_inferred, method_inferred))
2141 return false;
2144 return true;
2147 /// <summary>
2148 /// Type inference. Try to infer the type arguments from `method',
2149 /// which is invoked with the arguments `arguments'. This is used
2150 /// when resolving an Invocation or a DelegateInvocation and the user
2151 /// did not explicitly specify type arguments.
2152 /// </summary>
2153 public static int InferTypeArguments (ResolveContext ec, Arguments arguments, ref MethodSpec method)
2155 ATypeInference ti = ATypeInference.CreateInstance (arguments);
2156 Type[] i_args = ti.InferMethodArguments (ec, method);
2157 if (i_args == null)
2158 return ti.InferenceScore;
2160 if (i_args.Length == 0)
2161 return 0;
2163 method = method.Inflate (i_args);
2164 return 0;
2168 public static bool InferTypeArguments (ResolveContext ec, AParametersCollection param, ref MethodBase method)
2170 if (!TypeManager.IsGenericMethod (method))
2171 return true;
2173 ATypeInference ti = ATypeInference.CreateInstance (DelegateCreation.CreateDelegateMethodArguments (param, Location.Null));
2174 Type[] i_args = ti.InferDelegateArguments (ec, method);
2175 if (i_args == null)
2176 return false;
2178 method = ((MethodInfo) method).MakeGenericMethod (i_args);
2179 return true;
2184 abstract class ATypeInference
2186 protected readonly Arguments arguments;
2187 protected readonly int arg_count;
2189 protected ATypeInference (Arguments arguments)
2191 this.arguments = arguments;
2192 if (arguments != null)
2193 arg_count = arguments.Count;
2196 public static ATypeInference CreateInstance (Arguments arguments)
2198 return new TypeInference (arguments);
2201 public virtual int InferenceScore {
2202 get {
2203 return int.MaxValue;
2207 public abstract Type[] InferMethodArguments (ResolveContext ec, MethodSpec method);
2208 // public abstract Type[] InferDelegateArguments (ResolveContext ec, MethodBase method);
2212 // Implements C# type inference
2214 class TypeInference : ATypeInference
2217 // Tracks successful rate of type inference
2219 int score = int.MaxValue;
2221 public TypeInference (Arguments arguments)
2222 : base (arguments)
2226 public override int InferenceScore {
2227 get {
2228 return score;
2233 public override Type[] InferDelegateArguments (ResolveContext ec, MethodBase method)
2235 AParametersCollection pd = TypeManager.GetParameterData (method);
2236 if (arg_count != pd.Count)
2237 return null;
2239 Type[] d_gargs = method.GetGenericArguments ();
2240 TypeInferenceContext context = new TypeInferenceContext (d_gargs);
2242 // A lower-bound inference is made from each argument type Uj of D
2243 // to the corresponding parameter type Tj of M
2244 for (int i = 0; i < arg_count; ++i) {
2245 Type t = pd.Types [i];
2246 if (!t.IsGenericParameter)
2247 continue;
2249 context.LowerBoundInference (arguments [i].Expr.Type, t);
2252 if (!context.FixAllTypes (ec))
2253 return null;
2255 return context.InferredTypeArguments;
2258 public override Type[] InferMethodArguments (ResolveContext ec, MethodSpec method)
2260 var method_generic_args = method.GetGenericArguments ();
2261 TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2262 if (!context.UnfixedVariableExists)
2263 return Type.EmptyTypes;
2265 AParametersCollection pd = method.Parameters;
2266 if (!InferInPhases (ec, context, pd))
2267 return null;
2269 return context.InferredTypeArguments;
2273 // Implements method type arguments inference
2275 bool InferInPhases (ResolveContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
2277 int params_arguments_start;
2278 if (methodParameters.HasParams) {
2279 params_arguments_start = methodParameters.Count - 1;
2280 } else {
2281 params_arguments_start = arg_count;
2284 Type [] ptypes = methodParameters.Types;
2287 // The first inference phase
2289 Type method_parameter = null;
2290 for (int i = 0; i < arg_count; i++) {
2291 Argument a = arguments [i];
2292 if (a == null)
2293 continue;
2295 if (i < params_arguments_start) {
2296 method_parameter = methodParameters.Types [i];
2297 } else if (i == params_arguments_start) {
2298 if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2299 method_parameter = methodParameters.Types [params_arguments_start];
2300 else
2301 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2303 ptypes = (Type[]) ptypes.Clone ();
2304 ptypes [i] = method_parameter;
2308 // When a lambda expression, an anonymous method
2309 // is used an explicit argument type inference takes a place
2311 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2312 if (am != null) {
2313 if (am.ExplicitTypeInference (ec, tic, method_parameter))
2314 --score;
2315 continue;
2318 if (a.IsByRef) {
2319 score -= tic.ExactInference (a.Type, method_parameter);
2320 continue;
2323 if (a.Expr.Type == TypeManager.null_type)
2324 continue;
2326 if (TypeManager.IsValueType (method_parameter)) {
2327 score -= tic.LowerBoundInference (a.Type, method_parameter);
2328 continue;
2332 // Otherwise an output type inference is made
2334 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2338 // Part of the second phase but because it happens only once
2339 // we don't need to call it in cycle
2341 bool fixed_any = false;
2342 if (!tic.FixIndependentTypeArguments (ec, ptypes, ref fixed_any))
2343 return false;
2345 return DoSecondPhase (ec, tic, ptypes, !fixed_any);
2348 bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, Type[] methodParameters, bool fixDependent)
2350 bool fixed_any = false;
2351 if (fixDependent && !tic.FixDependentTypes (ec, ref fixed_any))
2352 return false;
2354 // If no further unfixed type variables exist, type inference succeeds
2355 if (!tic.UnfixedVariableExists)
2356 return true;
2358 if (!fixed_any && fixDependent)
2359 return false;
2361 // For all arguments where the corresponding argument output types
2362 // contain unfixed type variables but the input types do not,
2363 // an output type inference is made
2364 for (int i = 0; i < arg_count; i++) {
2366 // Align params arguments
2367 Type t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
2369 if (!TypeManager.IsDelegateType (t_i)) {
2370 if (TypeManager.DropGenericTypeArguments (t_i) != TypeManager.expression_type)
2371 continue;
2373 t_i = t_i.GetGenericArguments () [0];
2376 var mi = Delegate.GetInvokeMethod (ec.Compiler, t_i, t_i);
2377 Type rtype = mi.ReturnType;
2379 #if MS_COMPATIBLE
2380 // Blablabla, because reflection does not work with dynamic types
2381 // Type[] g_args = t_i.GetGenericArguments ();
2382 // rtype = g_args[rtype.GenericParameterPosition];
2383 #endif
2385 if (tic.IsReturnTypeNonDependent (ec, mi, rtype))
2386 score -= tic.OutputTypeInference (ec, arguments [i].Expr, t_i);
2390 return DoSecondPhase (ec, tic, methodParameters, true);
2394 public class TypeInferenceContext
2396 enum BoundKind
2398 Exact = 0,
2399 Lower = 1,
2400 Upper = 2
2403 class BoundInfo
2405 public readonly Type Type;
2406 public readonly BoundKind Kind;
2408 public BoundInfo (Type type, BoundKind kind)
2410 this.Type = type;
2411 this.Kind = kind;
2414 public override int GetHashCode ()
2416 return Type.GetHashCode ();
2419 public override bool Equals (object obj)
2421 BoundInfo a = (BoundInfo) obj;
2422 return Type == a.Type && Kind == a.Kind;
2426 readonly Type[] unfixed_types;
2427 readonly Type[] fixed_types;
2428 readonly List<BoundInfo>[] bounds;
2429 bool failed;
2431 public TypeInferenceContext (Type[] typeArguments)
2433 if (typeArguments.Length == 0)
2434 throw new ArgumentException ("Empty generic arguments");
2436 fixed_types = new Type [typeArguments.Length];
2437 for (int i = 0; i < typeArguments.Length; ++i) {
2438 if (typeArguments [i].IsGenericParameter) {
2439 if (bounds == null) {
2440 bounds = new List<BoundInfo> [typeArguments.Length];
2441 unfixed_types = new Type [typeArguments.Length];
2443 unfixed_types [i] = typeArguments [i];
2444 } else {
2445 fixed_types [i] = typeArguments [i];
2451 // Used together with AddCommonTypeBound fo implement
2452 // 7.4.2.13 Finding the best common type of a set of expressions
2454 public TypeInferenceContext ()
2456 fixed_types = new Type [1];
2457 unfixed_types = new Type [1];
2458 unfixed_types[0] = InternalType.Arglist; // it can be any internal type
2459 bounds = new List<BoundInfo> [1];
2462 public Type[] InferredTypeArguments {
2463 get {
2464 return fixed_types;
2468 public void AddCommonTypeBound (Type type)
2470 AddToBounds (new BoundInfo (type, BoundKind.Lower), 0);
2473 void AddToBounds (BoundInfo bound, int index)
2476 // Some types cannot be used as type arguments
2478 if (bound.Type == TypeManager.void_type || bound.Type.IsPointer)
2479 return;
2481 var a = bounds [index];
2482 if (a == null) {
2483 a = new List<BoundInfo> ();
2484 bounds [index] = a;
2485 } else {
2486 if (a.Contains (bound))
2487 return;
2491 // SPEC: does not cover type inference using constraints
2493 //if (TypeManager.IsGenericParameter (t)) {
2494 // GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
2495 // if (constraints != null) {
2496 // //if (constraints.EffectiveBaseClass != null)
2497 // // t = constraints.EffectiveBaseClass;
2498 // }
2500 a.Add (bound);
2503 bool AllTypesAreFixed (Type[] types)
2505 foreach (Type t in types) {
2506 if (t.IsGenericParameter) {
2507 if (!IsFixed (t))
2508 return false;
2509 continue;
2512 if (t.IsGenericType)
2513 return AllTypesAreFixed (t.GetGenericArguments ());
2516 return true;
2520 // 26.3.3.8 Exact Inference
2522 public int ExactInference (Type u, Type v)
2524 // If V is an array type
2525 if (v.IsArray) {
2526 if (!u.IsArray)
2527 return 0;
2529 if (u.GetArrayRank () != v.GetArrayRank ())
2530 return 0;
2532 return ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
2535 // If V is constructed type and U is constructed type
2536 if (v.IsGenericType && !v.IsGenericTypeDefinition) {
2537 if (!u.IsGenericType)
2538 return 0;
2540 Type [] ga_u = u.GetGenericArguments ();
2541 Type [] ga_v = v.GetGenericArguments ();
2542 if (ga_u.Length != ga_v.Length)
2543 return 0;
2545 int score = 0;
2546 for (int i = 0; i < ga_u.Length; ++i)
2547 score += ExactInference (ga_u [i], ga_v [i]);
2549 return score > 0 ? 1 : 0;
2552 // If V is one of the unfixed type arguments
2553 int pos = IsUnfixed (v);
2554 if (pos == -1)
2555 return 0;
2557 AddToBounds (new BoundInfo (u, BoundKind.Exact), pos);
2558 return 1;
2561 public bool FixAllTypes (ResolveContext ec)
2563 for (int i = 0; i < unfixed_types.Length; ++i) {
2564 if (!FixType (ec, i))
2565 return false;
2567 return true;
2571 // All unfixed type variables Xi are fixed for which all of the following hold:
2572 // a, There is at least one type variable Xj that depends on Xi
2573 // b, Xi has a non-empty set of bounds
2575 public bool FixDependentTypes (ResolveContext ec, ref bool fixed_any)
2577 for (int i = 0; i < unfixed_types.Length; ++i) {
2578 if (unfixed_types[i] == null)
2579 continue;
2581 if (bounds[i] == null)
2582 continue;
2584 if (!FixType (ec, i))
2585 return false;
2587 fixed_any = true;
2590 return true;
2594 // All unfixed type variables Xi which depend on no Xj are fixed
2596 public bool FixIndependentTypeArguments (ResolveContext ec, Type[] methodParameters, ref bool fixed_any)
2598 var types_to_fix = new List<Type> (unfixed_types);
2599 for (int i = 0; i < methodParameters.Length; ++i) {
2600 Type t = methodParameters[i];
2602 if (!TypeManager.IsDelegateType (t)) {
2603 if (TypeManager.DropGenericTypeArguments (t) != TypeManager.expression_type)
2604 continue;
2606 t = t.GetGenericArguments () [0];
2609 if (t.IsGenericParameter)
2610 continue;
2612 var invoke = Delegate.GetInvokeMethod (ec.Compiler, t, t);
2613 Type rtype = invoke.ReturnType;
2614 if (!rtype.IsGenericParameter && !rtype.IsGenericType)
2615 continue;
2617 #if MS_COMPATIBLE
2618 // Blablabla, because reflection does not work with dynamic types
2619 // if (rtype.IsGenericParameter) {
2620 // Type [] g_args = t.GetGenericArguments ();
2621 // rtype = g_args [rtype.GenericParameterPosition];
2622 // }
2623 #endif
2624 // Remove dependent types, they cannot be fixed yet
2625 RemoveDependentTypes (types_to_fix, rtype);
2628 foreach (Type t in types_to_fix) {
2629 if (t == null)
2630 continue;
2632 int idx = IsUnfixed (t);
2633 if (idx >= 0 && !FixType (ec, idx)) {
2634 return false;
2638 fixed_any = types_to_fix.Count > 0;
2639 return true;
2643 // 26.3.3.10 Fixing
2645 public bool FixType (ResolveContext ec, int i)
2647 // It's already fixed
2648 if (unfixed_types[i] == null)
2649 throw new InternalErrorException ("Type argument has been already fixed");
2651 if (failed)
2652 return false;
2654 var candidates = bounds [i];
2655 if (candidates == null)
2656 return false;
2658 if (candidates.Count == 1) {
2659 unfixed_types[i] = null;
2660 Type t = candidates[0].Type;
2661 if (t == TypeManager.null_type)
2662 return false;
2664 fixed_types [i] = t;
2665 return true;
2669 // Determines a unique type from which there is
2670 // a standard implicit conversion to all the other
2671 // candidate types.
2673 Type best_candidate = null;
2674 int cii;
2675 int candidates_count = candidates.Count;
2676 for (int ci = 0; ci < candidates_count; ++ci) {
2677 BoundInfo bound = (BoundInfo)candidates [ci];
2678 for (cii = 0; cii < candidates_count; ++cii) {
2679 if (cii == ci)
2680 continue;
2682 BoundInfo cbound = (BoundInfo) candidates[cii];
2684 // Same type parameters with different bounds
2685 if (cbound.Type == bound.Type) {
2686 if (bound.Kind != BoundKind.Exact)
2687 bound = cbound;
2689 continue;
2692 if (bound.Kind == BoundKind.Exact || cbound.Kind == BoundKind.Exact) {
2693 if (cbound.Kind != BoundKind.Exact) {
2694 if (!Convert.ImplicitConversionExists (ec, new TypeExpression (cbound.Type, Location.Null), bound.Type)) {
2695 break;
2698 continue;
2701 if (bound.Kind != BoundKind.Exact) {
2702 if (!Convert.ImplicitConversionExists (ec, new TypeExpression (bound.Type, Location.Null), cbound.Type)) {
2703 break;
2706 bound = cbound;
2707 continue;
2710 break;
2713 if (bound.Kind == BoundKind.Lower) {
2714 if (!Convert.ImplicitConversionExists (ec, new TypeExpression (cbound.Type, Location.Null), bound.Type)) {
2715 break;
2717 } else {
2718 if (!Convert.ImplicitConversionExists (ec, new TypeExpression (bound.Type, Location.Null), cbound.Type)) {
2719 break;
2724 if (cii != candidates_count)
2725 continue;
2727 if (best_candidate != null && best_candidate != bound.Type)
2728 return false;
2730 best_candidate = bound.Type;
2733 if (best_candidate == null)
2734 return false;
2736 unfixed_types[i] = null;
2737 fixed_types[i] = best_candidate;
2738 return true;
2742 // Uses inferred types to inflate delegate type argument
2744 public Type InflateGenericArgument (Type parameter)
2746 if (parameter.IsGenericParameter) {
2748 // Inflate method generic argument (MVAR) only
2750 if (parameter.DeclaringMethod == null)
2751 return parameter;
2753 return fixed_types [parameter.GenericParameterPosition];
2756 if (parameter.IsGenericType) {
2757 Type [] parameter_targs = parameter.GetGenericArguments ();
2758 for (int ii = 0; ii < parameter_targs.Length; ++ii) {
2759 parameter_targs [ii] = InflateGenericArgument (parameter_targs [ii]);
2761 return parameter.GetGenericTypeDefinition ().MakeGenericType (parameter_targs);
2764 return parameter;
2768 // Tests whether all delegate input arguments are fixed and generic output type
2769 // requires output type inference
2771 public bool IsReturnTypeNonDependent (ResolveContext ec, MethodSpec invoke, Type returnType)
2773 if (returnType.IsGenericParameter) {
2774 if (IsFixed (returnType))
2775 return false;
2776 } else if (returnType.IsGenericType) {
2777 if (TypeManager.IsDelegateType (returnType)) {
2778 invoke = Delegate.GetInvokeMethod (ec.Compiler, returnType, returnType);
2779 return IsReturnTypeNonDependent (ec, invoke, invoke.ReturnType);
2782 Type[] g_args = returnType.GetGenericArguments ();
2784 // At least one unfixed return type has to exist
2785 if (AllTypesAreFixed (g_args))
2786 return false;
2787 } else {
2788 return false;
2791 // All generic input arguments have to be fixed
2792 AParametersCollection d_parameters = invoke.Parameters;
2793 return AllTypesAreFixed (d_parameters.Types);
2796 bool IsFixed (Type type)
2798 return IsUnfixed (type) == -1;
2801 int IsUnfixed (Type type)
2803 if (!type.IsGenericParameter)
2804 return -1;
2806 //return unfixed_types[type.GenericParameterPosition] != null;
2807 for (int i = 0; i < unfixed_types.Length; ++i) {
2808 if (unfixed_types [i] == type)
2809 return i;
2812 return -1;
2816 // 26.3.3.9 Lower-bound Inference
2818 public int LowerBoundInference (Type u, Type v)
2820 return LowerBoundInference (u, v, false);
2824 // Lower-bound (false) or Upper-bound (true) inference based on inversed argument
2826 int LowerBoundInference (Type u, Type v, bool inversed)
2828 // If V is one of the unfixed type arguments
2829 int pos = IsUnfixed (v);
2830 if (pos != -1) {
2831 AddToBounds (new BoundInfo (u, inversed ? BoundKind.Upper : BoundKind.Lower), pos);
2832 return 1;
2835 // If U is an array type
2836 if (u.IsArray) {
2837 int u_dim = u.GetArrayRank ();
2838 Type v_i;
2839 Type u_i = TypeManager.GetElementType (u);
2841 if (v.IsArray) {
2842 if (u_dim != v.GetArrayRank ())
2843 return 0;
2845 v_i = TypeManager.GetElementType (v);
2847 if (TypeManager.IsValueType (u_i))
2848 return ExactInference (u_i, v_i);
2850 return LowerBoundInference (u_i, v_i, inversed);
2853 if (u_dim != 1)
2854 return 0;
2856 if (v.IsGenericType) {
2857 Type g_v = v.GetGenericTypeDefinition ();
2858 if ((g_v != TypeManager.generic_ilist_type) && (g_v != TypeManager.generic_icollection_type) &&
2859 (g_v != TypeManager.generic_ienumerable_type))
2860 return 0;
2862 v_i = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (v) [0]);
2863 if (TypeManager.IsValueType (u_i))
2864 return ExactInference (u_i, v_i);
2866 return LowerBoundInference (u_i, v_i);
2868 } else if (v.IsGenericType && !v.IsGenericTypeDefinition) {
2870 // if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
2871 // such that U is identical to, inherits from (directly or indirectly),
2872 // or implements (directly or indirectly) C<U1..Uk>
2874 var u_candidates = new List<Type> ();
2875 if (u.IsGenericType)
2876 u_candidates.Add (u);
2878 for (Type t = u.BaseType; t != null; t = t.BaseType) {
2879 if (t.IsGenericType && !t.IsGenericTypeDefinition)
2880 u_candidates.Add (t);
2883 // TODO: Implement GetGenericInterfaces only and remove
2884 // the if from foreach
2885 u_candidates.AddRange (TypeManager.GetInterfaces (u));
2887 Type open_v = v.GetGenericTypeDefinition ();
2888 Type [] unique_candidate_targs = null;
2889 Type [] ga_v = v.GetGenericArguments ();
2890 foreach (Type u_candidate in u_candidates) {
2891 if (!u_candidate.IsGenericType || u_candidate.IsGenericTypeDefinition)
2892 continue;
2894 if (TypeManager.DropGenericTypeArguments (u_candidate) != open_v)
2895 continue;
2898 // The unique set of types U1..Uk means that if we have an interface I<T>,
2899 // class U : I<int>, I<long> then no type inference is made when inferring
2900 // type I<T> by applying type U because T could be int or long
2902 if (unique_candidate_targs != null) {
2903 Type[] second_unique_candidate_targs = u_candidate.GetGenericArguments ();
2904 if (TypeManager.IsEqual (unique_candidate_targs, second_unique_candidate_targs)) {
2905 unique_candidate_targs = second_unique_candidate_targs;
2906 continue;
2910 // This should always cause type inference failure
2912 failed = true;
2913 return 1;
2916 unique_candidate_targs = u_candidate.GetGenericArguments ();
2919 if (unique_candidate_targs != null) {
2920 Type[] ga_open_v = open_v.GetGenericArguments ();
2921 int score = 0;
2922 for (int i = 0; i < unique_candidate_targs.Length; ++i) {
2923 Variance variance = TypeManager.GetTypeParameterVariance (ga_open_v [i]);
2925 Type u_i = unique_candidate_targs [i];
2926 if (variance == Variance.None || TypeManager.IsValueType (u_i)) {
2927 if (ExactInference (u_i, ga_v [i]) == 0)
2928 ++score;
2929 } else {
2930 bool upper_bound = (variance == Variance.Contravariant && !inversed) ||
2931 (variance == Variance.Covariant && inversed);
2933 if (LowerBoundInference (u_i, ga_v [i], upper_bound) == 0)
2934 ++score;
2937 return score;
2941 return 0;
2945 // 26.3.3.6 Output Type Inference
2947 public int OutputTypeInference (ResolveContext ec, Expression e, Type t)
2949 // If e is a lambda or anonymous method with inferred return type
2950 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
2951 if (ame != null) {
2952 Type rt = ame.InferReturnType (ec, this, t);
2953 var invoke = Delegate.GetInvokeMethod (ec.Compiler, t, t);
2955 if (rt == null) {
2956 AParametersCollection pd = invoke.Parameters;
2957 return ame.Parameters.Count == pd.Count ? 1 : 0;
2960 Type rtype = invoke.ReturnType;
2961 #if MS_COMPATIBLE
2962 // Blablabla, because reflection does not work with dynamic types
2963 // Type [] g_args = t.GetGenericArguments ();
2964 // rtype = g_args [rtype.GenericParameterPosition];
2965 #endif
2966 return LowerBoundInference (rt, rtype) + 1;
2970 // if E is a method group and T is a delegate type or expression tree type
2971 // return type Tb with parameter types T1..Tk and return type Tb, and overload
2972 // resolution of E with the types T1..Tk yields a single method with return type U,
2973 // then a lower-bound inference is made from U for Tb.
2975 if (e is MethodGroupExpr) {
2976 // TODO: Or expression tree
2977 if (!TypeManager.IsDelegateType (t))
2978 return 0;
2980 var invoke = Delegate.GetInvokeMethod (ec.Compiler, t, t);
2981 Type rtype = invoke.ReturnType;
2982 #if MS_COMPATIBLE
2983 // Blablabla, because reflection does not work with dynamic types
2984 // Type [] g_args = t.GetGenericArguments ();
2985 // rtype = g_args [rtype.GenericParameterPosition];
2986 #endif
2988 if (!TypeManager.IsGenericType (rtype))
2989 return 0;
2991 MethodGroupExpr mg = (MethodGroupExpr) e;
2992 Arguments args = DelegateCreation.CreateDelegateMethodArguments (invoke.Parameters, e.Location);
2993 mg = mg.OverloadResolve (ec, ref args, true, e.Location);
2994 if (mg == null)
2995 return 0;
2997 // TODO: What should happen when return type is of generic type ?
2998 throw new NotImplementedException ();
2999 // return LowerBoundInference (null, rtype) + 1;
3003 // if e is an expression with type U, then
3004 // a lower-bound inference is made from U for T
3006 return LowerBoundInference (e.Type, t) * 2;
3009 void RemoveDependentTypes (List<Type> types, Type returnType)
3011 int idx = IsUnfixed (returnType);
3012 if (idx >= 0) {
3013 types [idx] = null;
3014 return;
3017 if (returnType.IsGenericType) {
3018 foreach (Type t in returnType.GetGenericArguments ()) {
3019 RemoveDependentTypes (types, t);
3024 public bool UnfixedVariableExists {
3025 get {
3026 if (unfixed_types == null)
3027 return false;
3029 foreach (Type ut in unfixed_types)
3030 if (ut != null)
3031 return true;
3032 return false;