2009-12-09 Jb Evain <jbevain@novell.com>
[mcs.git] / mcs / generic.cs
blobddf34fbd5be22d94593e4b0bf782ec1f478049f4
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;
19 using System.Text.RegularExpressions;
21 namespace Mono.CSharp {
23 /// <summary>
24 /// Abstract base class for type parameter constraints.
25 /// The type parameter can come from a generic type definition or from reflection.
26 /// </summary>
27 public abstract class GenericConstraints {
28 public abstract string TypeParameter {
29 get;
32 public abstract GenericParameterAttributes Attributes {
33 get;
36 public bool HasConstructorConstraint {
37 get { return (Attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0; }
40 public bool HasReferenceTypeConstraint {
41 get { return (Attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0; }
44 public bool HasValueTypeConstraint {
45 get { return (Attributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0; }
48 public virtual bool HasClassConstraint {
49 get { return ClassConstraint != null; }
52 public abstract Type ClassConstraint {
53 get;
56 public abstract Type[] InterfaceConstraints {
57 get;
60 public abstract Type EffectiveBaseClass {
61 get;
64 // <summary>
65 // Returns whether the type parameter is "known to be a reference type".
66 // </summary>
67 public virtual bool IsReferenceType {
68 get {
69 if (HasReferenceTypeConstraint)
70 return true;
71 if (HasValueTypeConstraint)
72 return false;
74 if (ClassConstraint != null) {
75 if (ClassConstraint.IsValueType)
76 return false;
78 if (ClassConstraint != TypeManager.object_type)
79 return true;
82 foreach (Type t in InterfaceConstraints) {
83 if (!t.IsGenericParameter)
84 continue;
86 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
87 if ((gc != null) && gc.IsReferenceType)
88 return true;
91 return false;
95 // <summary>
96 // Returns whether the type parameter is "known to be a value type".
97 // </summary>
98 public virtual bool IsValueType {
99 get {
100 if (HasValueTypeConstraint)
101 return true;
102 if (HasReferenceTypeConstraint)
103 return false;
105 if (ClassConstraint != null) {
106 if (!TypeManager.IsValueType (ClassConstraint))
107 return false;
109 if (ClassConstraint != TypeManager.value_type)
110 return true;
113 foreach (Type t in InterfaceConstraints) {
114 if (!t.IsGenericParameter)
115 continue;
117 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
118 if ((gc != null) && gc.IsValueType)
119 return true;
122 return false;
127 public class ReflectionConstraints : GenericConstraints
129 GenericParameterAttributes attrs;
130 Type base_type;
131 Type class_constraint;
132 Type[] iface_constraints;
133 string name;
135 public static GenericConstraints GetConstraints (Type t)
137 Type[] constraints = t.GetGenericParameterConstraints ();
138 GenericParameterAttributes attrs = t.GenericParameterAttributes;
139 if (constraints.Length == 0 && attrs == GenericParameterAttributes.None)
140 return null;
141 return new ReflectionConstraints (t.Name, constraints, attrs);
144 private ReflectionConstraints (string name, Type[] constraints, GenericParameterAttributes attrs)
146 this.name = name;
147 this.attrs = attrs;
149 int interface_constraints_pos = 0;
150 if ((attrs & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
151 base_type = TypeManager.value_type;
152 interface_constraints_pos = 1;
153 } else if ((attrs & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
154 if (constraints.Length > 0 && constraints[0].IsClass) {
155 class_constraint = base_type = constraints[0];
156 interface_constraints_pos = 1;
157 } else {
158 base_type = TypeManager.object_type;
160 } else {
161 base_type = TypeManager.object_type;
164 if (constraints.Length > interface_constraints_pos) {
165 if (interface_constraints_pos == 0) {
166 iface_constraints = constraints;
167 } else {
168 iface_constraints = new Type[constraints.Length - interface_constraints_pos];
169 Array.Copy (constraints, interface_constraints_pos, iface_constraints, 0, iface_constraints.Length);
171 } else {
172 iface_constraints = Type.EmptyTypes;
176 public override string TypeParameter
178 get { return name; }
181 public override GenericParameterAttributes Attributes
183 get { return attrs; }
186 public override Type ClassConstraint
188 get { return class_constraint; }
191 public override Type EffectiveBaseClass
193 get { return base_type; }
196 public override Type[] InterfaceConstraints
198 get { return iface_constraints; }
202 public enum Variance
205 // Don't add or modify internal values, they are used as -/+ calculation signs
207 None = 0,
208 Covariant = 1,
209 Contravariant = -1
212 public enum SpecialConstraint
214 Constructor,
215 ReferenceType,
216 ValueType
219 /// <summary>
220 /// Tracks the constraints for a type parameter from a generic type definition.
221 /// </summary>
222 public class Constraints : GenericConstraints {
223 string name;
224 List<object> constraints;
225 Location loc;
228 // name is the identifier, constraints is an arraylist of
229 // Expressions (with types) or `true' for the constructor constraint.
231 public Constraints (string name, List<object> constraints, Location loc)
233 this.name = name;
234 this.constraints = constraints;
235 this.loc = loc;
238 public override string TypeParameter {
239 get {
240 return name;
244 public Constraints Clone ()
246 return new Constraints (name, constraints, loc);
249 GenericParameterAttributes attrs;
250 TypeExpr class_constraint;
251 List<TypeExpr> iface_constraints;
252 List<TypeExpr> type_param_constraints;
253 int num_constraints;
254 Type class_constraint_type;
255 Type[] iface_constraint_types;
256 Type effective_base_type;
257 bool resolved;
258 bool resolved_types;
260 /// <summary>
261 /// Resolve the constraints - but only resolve things into Expression's, not
262 /// into actual types.
263 /// </summary>
264 public bool Resolve (MemberCore ec, TypeParameter tp, Report Report)
266 if (resolved)
267 return true;
269 if (ec == null)
270 return false;
272 iface_constraints = new List<TypeExpr> (2); // TODO: Too expensive allocation
273 type_param_constraints = new List<TypeExpr> ();
275 foreach (object obj in constraints) {
276 if (HasConstructorConstraint) {
277 Report.Error (401, loc,
278 "The new() constraint must be the last constraint specified");
279 return false;
282 if (obj is SpecialConstraint) {
283 SpecialConstraint sc = (SpecialConstraint) obj;
285 if (sc == SpecialConstraint.Constructor) {
286 if (!HasValueTypeConstraint) {
287 attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
288 continue;
291 Report.Error (451, loc, "The `new()' constraint " +
292 "cannot be used with the `struct' constraint");
293 return false;
296 if ((num_constraints > 0) || HasReferenceTypeConstraint || HasValueTypeConstraint) {
297 Report.Error (449, loc, "The `class' or `struct' " +
298 "constraint must be the first constraint specified");
299 return false;
302 if (sc == SpecialConstraint.ReferenceType)
303 attrs |= GenericParameterAttributes.ReferenceTypeConstraint;
304 else
305 attrs |= GenericParameterAttributes.NotNullableValueTypeConstraint;
306 continue;
309 int errors = Report.Errors;
310 FullNamedExpression fn = ((Expression) obj).ResolveAsTypeStep (ec, false);
312 if (fn == null) {
313 if (errors != Report.Errors)
314 return false;
316 NamespaceEntry.Error_NamespaceNotFound (loc, ((Expression)obj).GetSignatureForError (), Report);
317 return false;
320 TypeExpr expr;
321 GenericTypeExpr cexpr = fn as GenericTypeExpr;
322 if (cexpr != null) {
323 expr = cexpr.ResolveAsBaseTerminal (ec, false);
324 if (expr != null && cexpr.HasDynamicArguments ()) {
325 Report.Error (1968, cexpr.Location,
326 "A constraint cannot be the dynamic type `{0}'",
327 cexpr.GetSignatureForError ());
328 expr = null;
330 } else
331 expr = ((Expression) obj).ResolveAsTypeTerminal (ec, false);
333 if ((expr == null) || (expr.Type == null))
334 return false;
336 if (TypeManager.IsGenericParameter (expr.Type))
337 type_param_constraints.Add (expr);
338 else if (expr.IsInterface)
339 iface_constraints.Add (expr);
340 else if (class_constraint != null || iface_constraints.Count != 0) {
341 Report.Error (406, loc,
342 "The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
343 expr.GetSignatureForError ());
344 return false;
345 } else if (HasReferenceTypeConstraint || HasValueTypeConstraint) {
346 Report.Error (450, loc, "`{0}': cannot specify both " +
347 "a constraint class and the `class' " +
348 "or `struct' constraint", expr.GetSignatureForError ());
349 return false;
350 } else
351 class_constraint = expr;
355 // Checks whether each generic method parameter constraint type
356 // is valid with respect to T
358 if (tp != null && tp.Type.DeclaringMethod != null) {
359 TypeManager.CheckTypeVariance (expr.Type, Variance.Contravariant, ec as MemberCore);
362 if (!ec.IsAccessibleAs (fn.Type)) {
363 Report.SymbolRelatedToPreviousError (fn.Type);
364 Report.Error (703, loc,
365 "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
366 fn.GetSignatureForError (), ec.GetSignatureForError ());
369 num_constraints++;
372 var list = new List<Type> ();
373 foreach (TypeExpr iface_constraint in iface_constraints) {
374 foreach (Type type in list) {
375 if (!type.Equals (iface_constraint.Type))
376 continue;
378 Report.Error (405, loc,
379 "Duplicate constraint `{0}' for type " +
380 "parameter `{1}'.", iface_constraint.GetSignatureForError (),
381 name);
382 return false;
385 list.Add (iface_constraint.Type);
388 foreach (TypeExpr expr in type_param_constraints) {
389 foreach (Type type in list) {
390 if (!type.Equals (expr.Type))
391 continue;
393 Report.Error (405, loc,
394 "Duplicate constraint `{0}' for type " +
395 "parameter `{1}'.", expr.GetSignatureForError (), name);
396 return false;
399 list.Add (expr.Type);
402 iface_constraint_types = new Type [list.Count];
403 list.CopyTo (iface_constraint_types, 0);
405 if (class_constraint != null) {
406 class_constraint_type = class_constraint.Type;
407 if (class_constraint_type == null)
408 return false;
410 if (class_constraint_type.IsSealed) {
411 if (class_constraint_type.IsAbstract)
413 Report.Error (717, loc, "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
414 TypeManager.CSharpName (class_constraint_type));
416 else
418 Report.Error (701, loc, "`{0}' is not a valid constraint. A constraint must be an interface, " +
419 "a non-sealed class or a type parameter", TypeManager.CSharpName(class_constraint_type));
421 return false;
424 if ((class_constraint_type == TypeManager.array_type) ||
425 (class_constraint_type == TypeManager.delegate_type) ||
426 (class_constraint_type == TypeManager.enum_type) ||
427 (class_constraint_type == TypeManager.value_type) ||
428 (class_constraint_type == TypeManager.object_type) ||
429 class_constraint_type == TypeManager.multicast_delegate_type) {
430 Report.Error (702, loc,
431 "A constraint cannot be special class `{0}'",
432 TypeManager.CSharpName (class_constraint_type));
433 return false;
436 if (TypeManager.IsDynamicType (class_constraint_type)) {
437 Report.Error (1967, loc, "A constraint cannot be the dynamic type");
438 return false;
442 if (class_constraint_type != null)
443 effective_base_type = class_constraint_type;
444 else if (HasValueTypeConstraint)
445 effective_base_type = TypeManager.value_type;
446 else
447 effective_base_type = TypeManager.object_type;
449 if ((attrs & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0)
450 attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
452 resolved = true;
453 return true;
456 bool CheckTypeParameterConstraints (Type tparam, ref TypeExpr prevConstraint, List<Type> seen, Report Report)
458 seen.Add (tparam);
460 Constraints constraints = TypeManager.LookupTypeParameter (tparam).Constraints;
461 if (constraints == null)
462 return true;
464 if (constraints.HasValueTypeConstraint) {
465 Report.Error (456, loc,
466 "Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
467 tparam.Name, name);
468 return false;
472 // Checks whether there are no conflicts between type parameter constraints
474 // class Foo<T, U>
475 // where T : A
476 // where U : A, B // A and B are not convertible
478 if (constraints.HasClassConstraint) {
479 if (prevConstraint != null) {
480 Type t2 = constraints.ClassConstraint;
481 TypeExpr e2 = constraints.class_constraint;
483 if (!Convert.ImplicitReferenceConversionExists (prevConstraint, t2) &&
484 !Convert.ImplicitReferenceConversionExists (e2, prevConstraint.Type)) {
485 Report.Error (455, loc,
486 "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
487 name, TypeManager.CSharpName (prevConstraint.Type), TypeManager.CSharpName (t2));
488 return false;
492 prevConstraint = constraints.class_constraint;
495 if (constraints.type_param_constraints == null)
496 return true;
498 foreach (TypeExpr expr in constraints.type_param_constraints) {
499 if (seen.Contains (expr.Type)) {
500 Report.Error (454, loc, "Circular constraint " +
501 "dependency involving `{0}' and `{1}'",
502 tparam.Name, expr.GetSignatureForError ());
503 return false;
506 if (!CheckTypeParameterConstraints (expr.Type, ref prevConstraint, seen, Report))
507 return false;
510 return true;
513 /// <summary>
514 /// Resolve the constraints into actual types.
515 /// </summary>
516 public bool ResolveTypes (IMemberContext ec, Report r)
518 if (resolved_types)
519 return true;
521 resolved_types = true;
523 foreach (object obj in constraints) {
524 GenericTypeExpr cexpr = obj as GenericTypeExpr;
525 if (cexpr == null)
526 continue;
528 if (!cexpr.CheckConstraints (ec))
529 return false;
532 if (type_param_constraints.Count != 0) {
533 var seen = new List<Type> ();
534 TypeExpr prev_constraint = class_constraint;
535 foreach (TypeExpr expr in type_param_constraints) {
536 if (!CheckTypeParameterConstraints (expr.Type, ref prev_constraint, seen, r))
537 return false;
538 seen.Clear ();
542 for (int i = 0; i < iface_constraints.Count; ++i) {
543 TypeExpr iface_constraint = (TypeExpr) iface_constraints [i];
544 iface_constraint = iface_constraint.ResolveAsTypeTerminal (ec, false);
545 if (iface_constraint == null)
546 return false;
547 iface_constraints [i] = iface_constraint;
550 if (class_constraint != null) {
551 class_constraint = class_constraint.ResolveAsTypeTerminal (ec, false);
552 if (class_constraint == null)
553 return false;
556 return true;
559 public override GenericParameterAttributes Attributes {
560 get { return attrs; }
563 public override bool HasClassConstraint {
564 get { return class_constraint != null; }
567 public override Type ClassConstraint {
568 get { return class_constraint_type; }
571 public override Type[] InterfaceConstraints {
572 get { return iface_constraint_types; }
575 public override Type EffectiveBaseClass {
576 get { return effective_base_type; }
579 public bool IsSubclassOf (Type t)
581 if ((class_constraint_type != null) &&
582 class_constraint_type.IsSubclassOf (t))
583 return true;
585 if (iface_constraint_types == null)
586 return false;
588 foreach (Type iface in iface_constraint_types) {
589 if (TypeManager.IsSubclassOf (iface, t))
590 return true;
593 return false;
596 public Location Location {
597 get {
598 return loc;
602 /// <summary>
603 /// This is used when we're implementing a generic interface method.
604 /// Each method type parameter in implementing method must have the same
605 /// constraints than the corresponding type parameter in the interface
606 /// method. To do that, we're called on each of the implementing method's
607 /// type parameters.
608 /// </summary>
609 public bool AreEqual (GenericConstraints gc)
611 if (gc.Attributes != attrs)
612 return false;
614 if (HasClassConstraint != gc.HasClassConstraint)
615 return false;
616 if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
617 return false;
619 int gc_icount = gc.InterfaceConstraints != null ?
620 gc.InterfaceConstraints.Length : 0;
621 int icount = InterfaceConstraints != null ?
622 InterfaceConstraints.Length : 0;
624 if (gc_icount != icount)
625 return false;
627 for (int i = 0; i < gc.InterfaceConstraints.Length; ++i) {
628 Type iface = gc.InterfaceConstraints [i];
629 if (iface.IsGenericType)
630 iface = iface.GetGenericTypeDefinition ();
632 bool ok = false;
633 for (int ii = 0; ii < InterfaceConstraints.Length; ii++) {
634 Type check = InterfaceConstraints [ii];
635 if (check.IsGenericType)
636 check = check.GetGenericTypeDefinition ();
638 if (TypeManager.IsEqual (iface, check)) {
639 ok = true;
640 break;
644 if (!ok)
645 return false;
648 return true;
651 public void VerifyClsCompliance (Report r)
653 if (class_constraint_type != null && !AttributeTester.IsClsCompliant (class_constraint_type))
654 Warning_ConstrainIsNotClsCompliant (class_constraint_type, class_constraint.Location, r);
656 if (iface_constraint_types != null) {
657 for (int i = 0; i < iface_constraint_types.Length; ++i) {
658 if (!AttributeTester.IsClsCompliant (iface_constraint_types [i]))
659 Warning_ConstrainIsNotClsCompliant (iface_constraint_types [i],
660 ((TypeExpr)iface_constraints [i]).Location, r);
665 void Warning_ConstrainIsNotClsCompliant (Type t, Location loc, Report Report)
667 Report.SymbolRelatedToPreviousError (t);
668 Report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
669 TypeManager.CSharpName (t));
673 /// <summary>
674 /// A type parameter from a generic type definition.
675 /// </summary>
676 public class TypeParameter : MemberCore, IMemberContainer
678 static readonly string[] attribute_target = new string [] { "type parameter" };
680 DeclSpace decl;
681 GenericConstraints gc;
682 Constraints constraints;
683 GenericTypeParameterBuilder type;
684 MemberCache member_cache;
685 Variance variance;
687 public TypeParameter (DeclSpace parent, DeclSpace decl, string name,
688 Constraints constraints, Attributes attrs, Variance variance, Location loc)
689 : base (parent, new MemberName (name, loc), attrs)
691 this.decl = decl;
692 this.constraints = constraints;
693 this.variance = variance;
696 public GenericConstraints GenericConstraints {
697 get { return gc != null ? gc : constraints; }
700 public Constraints Constraints {
701 get { return constraints; }
704 public DeclSpace DeclSpace {
705 get { return decl; }
708 public Variance Variance {
709 get { return variance; }
712 public Type Type {
713 get { return type; }
716 /// <summary>
717 /// This is the first method which is called during the resolving
718 /// process; we're called immediately after creating the type parameters
719 /// with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
720 /// MethodBuilder).
722 /// We're either called from TypeContainer.DefineType() or from
723 /// GenericMethod.Define() (called from Method.Define()).
724 /// </summary>
725 public void Define (GenericTypeParameterBuilder type)
727 if (this.type != null)
728 throw new InvalidOperationException ();
730 this.type = type;
731 TypeManager.AddTypeParameter (type, this);
734 public void ErrorInvalidVariance (IMemberContext mc, Variance expected)
736 // TODO: Report.SymbolRelatedToPreviousError (mc);
737 string input_variance = Variance == Variance.Contravariant ? "contravariant" : "covariant";
738 string gtype_variance;
739 switch (expected) {
740 case Variance.Contravariant: gtype_variance = "contravariantly"; break;
741 case Variance.Covariant: gtype_variance = "covariantly"; break;
742 default: gtype_variance = "invariantly"; break;
745 Delegate d = mc as Delegate;
746 string parameters = d != null ? d.Parameters.GetSignatureForError () : "";
748 Report.Error (1961, Location,
749 "The {2} type parameter `{0}' must be {3} valid on `{1}{4}'",
750 GetSignatureForError (), mc.GetSignatureForError (), input_variance, gtype_variance, parameters);
753 /// <summary>
754 /// This is the second method which is called during the resolving
755 /// process - in case of class type parameters, we're called from
756 /// TypeContainer.ResolveType() - after it resolved the class'es
757 /// base class and interfaces. For method type parameters, we're
758 /// called immediately after Define().
760 /// We're just resolving the constraints into expressions here, we
761 /// don't resolve them into actual types.
763 /// Note that in the special case of partial generic classes, we may be
764 /// called _before_ Define() and we may also be called multiple types.
765 /// </summary>
766 public bool Resolve (DeclSpace ds)
768 if (constraints != null) {
769 if (!constraints.Resolve (ds, this, Report)) {
770 constraints = null;
771 return false;
775 return true;
778 /// <summary>
779 /// This is the third method which is called during the resolving
780 /// process. We're called immediately after calling DefineConstraints()
781 /// on all of the current class'es type parameters.
783 /// Our job is to resolve the constraints to actual types.
785 /// Note that we may have circular dependencies on type parameters - this
786 /// is why Resolve() and ResolveType() are separate.
787 /// </summary>
788 public bool ResolveType (IMemberContext ec)
790 if (constraints != null) {
791 if (!constraints.ResolveTypes (ec, Report)) {
792 constraints = null;
793 return false;
797 return true;
800 /// <summary>
801 /// This is the fourth and last method which is called during the resolving
802 /// process. We're called after everything is fully resolved and actually
803 /// register the constraints with SRE and the TypeManager.
804 /// </summary>
805 public bool DefineType (IMemberContext ec)
807 return DefineType (ec, null, null, false);
810 /// <summary>
811 /// This is the fith and last method which is called during the resolving
812 /// process. We're called after everything is fully resolved and actually
813 /// register the constraints with SRE and the TypeManager.
815 /// The `builder', `implementing' and `is_override' arguments are only
816 /// applicable to method type parameters.
817 /// </summary>
818 public bool DefineType (IMemberContext ec, MethodBuilder builder,
819 MethodInfo implementing, bool is_override)
821 if (!ResolveType (ec))
822 return false;
824 if (implementing != null) {
825 if (is_override && (constraints != null)) {
826 Report.Error (460, Location,
827 "`{0}': Cannot specify constraints for overrides or explicit interface implementation methods",
828 TypeManager.CSharpSignature (builder));
829 return false;
832 MethodBase mb = TypeManager.DropGenericMethodArguments (implementing);
834 int pos = type.GenericParameterPosition;
835 Type mparam = mb.GetGenericArguments () [pos];
836 GenericConstraints temp_gc = ReflectionConstraints.GetConstraints (mparam);
838 if (temp_gc != null)
839 gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
840 else if (constraints != null)
841 gc = new InflatedConstraints (constraints, implementing.DeclaringType);
843 bool ok = true;
844 if (constraints != null) {
845 if (temp_gc == null)
846 ok = false;
847 else if (!constraints.AreEqual (gc))
848 ok = false;
849 } else {
850 if (!is_override && (temp_gc != null))
851 ok = false;
854 if (!ok) {
855 Report.SymbolRelatedToPreviousError (implementing);
857 Report.Error (
858 425, Location, "The constraints for type " +
859 "parameter `{0}' of method `{1}' must match " +
860 "the constraints for type parameter `{2}' " +
861 "of interface method `{3}'. Consider using " +
862 "an explicit interface implementation instead",
863 Name, TypeManager.CSharpSignature (builder),
864 TypeManager.CSharpName (mparam), TypeManager.CSharpSignature (mb));
865 return false;
867 } else if (DeclSpace is CompilerGeneratedClass) {
868 TypeParameter[] tparams = DeclSpace.TypeParameters;
869 Type[] types = new Type [tparams.Length];
870 for (int i = 0; i < tparams.Length; i++)
871 types [i] = tparams [i].Type;
873 if (constraints != null)
874 gc = new InflatedConstraints (constraints, types);
875 } else {
876 gc = (GenericConstraints) constraints;
879 SetConstraints (type);
880 return true;
883 public static TypeParameter FindTypeParameter (TypeParameter[] tparams, string name)
885 foreach (var tp in tparams) {
886 if (tp.Name == name)
887 return tp;
890 return null;
893 public void SetConstraints (GenericTypeParameterBuilder type)
895 GenericParameterAttributes attr = GenericParameterAttributes.None;
896 if (variance == Variance.Contravariant)
897 attr |= GenericParameterAttributes.Contravariant;
898 else if (variance == Variance.Covariant)
899 attr |= GenericParameterAttributes.Covariant;
901 if (gc != null) {
902 if (gc.HasClassConstraint || gc.HasValueTypeConstraint)
903 type.SetBaseTypeConstraint (gc.EffectiveBaseClass);
905 attr |= gc.Attributes;
906 type.SetInterfaceConstraints (gc.InterfaceConstraints);
907 TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
910 type.SetGenericParameterAttributes (attr);
913 /// <summary>
914 /// This is called for each part of a partial generic type definition.
916 /// If `new_constraints' is not null and we don't already have constraints,
917 /// they become our constraints. If we already have constraints, we must
918 /// check that they're the same.
919 /// con
920 /// </summary>
921 public bool UpdateConstraints (MemberCore ec, Constraints new_constraints)
923 if (type == null)
924 throw new InvalidOperationException ();
926 if (new_constraints == null)
927 return true;
929 if (!new_constraints.Resolve (ec, this, Report))
930 return false;
931 if (!new_constraints.ResolveTypes (ec, Report))
932 return false;
934 if (constraints != null)
935 return constraints.AreEqual (new_constraints);
937 constraints = new_constraints;
938 return true;
941 public override void Emit ()
943 if (OptAttributes != null)
944 OptAttributes.Emit ();
946 base.Emit ();
949 public override string DocCommentHeader {
950 get {
951 throw new InvalidOperationException (
952 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
957 // MemberContainer
960 public override bool Define ()
962 return true;
965 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
967 type.SetCustomAttribute (cb);
970 public override AttributeTargets AttributeTargets {
971 get {
972 return AttributeTargets.GenericParameter;
976 public override string[] ValidAttributeTargets {
977 get {
978 return attribute_target;
983 // IMemberContainer
986 string IMemberContainer.Name {
987 get { return Name; }
990 MemberCache IMemberContainer.BaseCache {
991 get {
992 if (gc == null)
993 return null;
995 if (gc.EffectiveBaseClass.BaseType == null)
996 return null;
998 return TypeManager.LookupMemberCache (gc.EffectiveBaseClass.BaseType);
1002 bool IMemberContainer.IsInterface {
1003 get { return false; }
1006 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
1008 throw new NotSupportedException ();
1011 public MemberCache MemberCache {
1012 get {
1013 if (member_cache != null)
1014 return member_cache;
1016 if (gc == null)
1017 return null;
1019 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
1020 member_cache = new MemberCache (this, gc.EffectiveBaseClass, ifaces);
1022 return member_cache;
1026 public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1027 MemberFilter filter, object criteria)
1029 if (gc == null)
1030 return MemberList.Empty;
1032 var members = new List<MemberInfo> ();
1034 if (gc.HasClassConstraint) {
1035 MemberList list = TypeManager.FindMembers (
1036 gc.ClassConstraint, mt, bf, filter, criteria);
1038 members.AddRange (list);
1041 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
1042 foreach (Type t in ifaces) {
1043 MemberList list = TypeManager.FindMembers (
1044 t, mt, bf, filter, criteria);
1046 members.AddRange (list);
1049 return new MemberList (members);
1052 public bool IsSubclassOf (Type t)
1054 if (type.Equals (t))
1055 return true;
1057 if (constraints != null)
1058 return constraints.IsSubclassOf (t);
1060 return false;
1063 public void InflateConstraints (Type declaring)
1065 if (constraints != null)
1066 gc = new InflatedConstraints (constraints, declaring);
1069 public override bool IsClsComplianceRequired ()
1071 return false;
1074 protected class InflatedConstraints : GenericConstraints
1076 GenericConstraints gc;
1077 Type base_type;
1078 Type class_constraint;
1079 Type[] iface_constraints;
1080 Type[] dargs;
1082 public InflatedConstraints (GenericConstraints gc, Type declaring)
1083 : this (gc, TypeManager.GetTypeArguments (declaring))
1086 public InflatedConstraints (GenericConstraints gc, Type[] dargs)
1088 this.gc = gc;
1089 this.dargs = dargs;
1091 var list = new List<Type> ();
1092 if (gc.HasClassConstraint)
1093 list.Add (inflate (gc.ClassConstraint));
1094 foreach (Type iface in gc.InterfaceConstraints)
1095 list.Add (inflate (iface));
1097 bool has_class_constr = false;
1098 if (list.Count > 0) {
1099 Type first = (Type) list [0];
1100 has_class_constr = !first.IsGenericParameter && !first.IsInterface;
1103 if ((list.Count > 0) && has_class_constr) {
1104 class_constraint = (Type) list [0];
1105 iface_constraints = new Type [list.Count - 1];
1106 list.CopyTo (1, iface_constraints, 0, list.Count - 1);
1107 } else {
1108 iface_constraints = new Type [list.Count];
1109 list.CopyTo (iface_constraints, 0);
1112 if (HasValueTypeConstraint)
1113 base_type = TypeManager.value_type;
1114 else if (class_constraint != null)
1115 base_type = class_constraint;
1116 else
1117 base_type = TypeManager.object_type;
1120 Type inflate (Type t)
1122 if (t == null)
1123 return null;
1124 if (t.IsGenericParameter)
1125 return t.GenericParameterPosition < dargs.Length ? dargs [t.GenericParameterPosition] : t;
1126 if (t.IsGenericType) {
1127 Type[] args = t.GetGenericArguments ();
1128 Type[] inflated = new Type [args.Length];
1130 for (int i = 0; i < args.Length; i++)
1131 inflated [i] = inflate (args [i]);
1133 t = t.GetGenericTypeDefinition ();
1134 t = t.MakeGenericType (inflated);
1137 return t;
1140 public override string TypeParameter {
1141 get { return gc.TypeParameter; }
1144 public override GenericParameterAttributes Attributes {
1145 get { return gc.Attributes; }
1148 public override Type ClassConstraint {
1149 get { return class_constraint; }
1152 public override Type EffectiveBaseClass {
1153 get { return base_type; }
1156 public override Type[] InterfaceConstraints {
1157 get { return iface_constraints; }
1162 /// <summary>
1163 /// A TypeExpr which already resolved to a type parameter.
1164 /// </summary>
1165 public class TypeParameterExpr : TypeExpr {
1167 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1169 this.type = type_parameter.Type;
1170 this.eclass = ExprClass.TypeParameter;
1171 this.loc = loc;
1174 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
1176 throw new NotSupportedException ();
1179 public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
1181 return this;
1184 public override bool IsInterface {
1185 get { return false; }
1188 public override bool CheckAccessLevel (IMemberContext ds)
1190 return true;
1195 // Tracks the type arguments when instantiating a generic type. It's used
1196 // by both type arguments and type parameters
1198 public class TypeArguments {
1199 List<FullNamedExpression> args;
1200 Type[] atypes;
1202 public TypeArguments ()
1204 args = new List<FullNamedExpression> ();
1207 public TypeArguments (params FullNamedExpression[] types)
1209 this.args = new List<FullNamedExpression> (types);
1212 public void Add (FullNamedExpression type)
1214 args.Add (type);
1217 public void Add (TypeArguments new_args)
1219 args.AddRange (new_args.args);
1222 // TODO: Kill this monster
1223 public TypeParameterName[] GetDeclarations ()
1225 return args.ConvertAll (i => (TypeParameterName) i).ToArray ();
1228 /// <summary>
1229 /// We may only be used after Resolve() is called and return the fully
1230 /// resolved types.
1231 /// </summary>
1232 public Type[] Arguments {
1233 get {
1234 return atypes;
1238 public int Count {
1239 get {
1240 return args.Count;
1244 public string GetSignatureForError()
1246 StringBuilder sb = new StringBuilder();
1247 for (int i = 0; i < Count; ++i)
1249 Expression expr = (Expression)args [i];
1250 sb.Append(expr.GetSignatureForError());
1251 if (i + 1 < Count)
1252 sb.Append(',');
1254 return sb.ToString();
1257 /// <summary>
1258 /// Resolve the type arguments.
1259 /// </summary>
1260 public bool Resolve (IMemberContext ec)
1262 if (atypes != null)
1263 return atypes.Length != 0;
1265 int count = args.Count;
1266 bool ok = true;
1268 atypes = new Type [count];
1270 for (int i = 0; i < count; i++){
1271 TypeExpr te = ((FullNamedExpression) args[i]).ResolveAsTypeTerminal (ec, false);
1272 if (te == null) {
1273 ok = false;
1274 continue;
1277 atypes[i] = te.Type;
1279 if (te.Type.IsSealed && te.Type.IsAbstract) {
1280 ec.Compiler.Report.Error (718, te.Location, "`{0}': static classes cannot be used as generic arguments",
1281 te.GetSignatureForError ());
1282 ok = false;
1285 if (te.Type.IsPointer || TypeManager.IsSpecialType (te.Type)) {
1286 ec.Compiler.Report.Error (306, te.Location,
1287 "The type `{0}' may not be used as a type argument",
1288 te.GetSignatureForError ());
1289 ok = false;
1293 if (!ok)
1294 atypes = Type.EmptyTypes;
1296 return ok;
1299 public TypeArguments Clone ()
1301 TypeArguments copy = new TypeArguments ();
1302 foreach (var ta in args)
1303 copy.args.Add (ta);
1305 return copy;
1309 public class TypeParameterName : SimpleName
1311 Attributes attributes;
1312 Variance variance;
1314 public TypeParameterName (string name, Attributes attrs, Location loc)
1315 : this (name, attrs, Variance.None, loc)
1319 public TypeParameterName (string name, Attributes attrs, Variance variance, Location loc)
1320 : base (name, loc)
1322 attributes = attrs;
1323 this.variance = variance;
1326 public Attributes OptAttributes {
1327 get {
1328 return attributes;
1332 public Variance Variance {
1333 get {
1334 return variance;
1339 /// <summary>
1340 /// A reference expression to generic type
1341 /// </summary>
1342 class GenericTypeExpr : TypeExpr
1344 TypeArguments args;
1345 Type[] gen_params; // TODO: Waiting for constrains check cleanup
1346 Type open_type;
1349 // Should be carefully used only with defined generic containers. Type parameters
1350 // can be used as type arguments in this case.
1352 // TODO: This could be GenericTypeExpr specialization
1354 public GenericTypeExpr (DeclSpace gType, Location l)
1356 open_type = gType.TypeBuilder.GetGenericTypeDefinition ();
1358 args = new TypeArguments ();
1359 foreach (TypeParameter type_param in gType.TypeParameters)
1360 args.Add (new TypeParameterExpr (type_param, l));
1362 this.loc = l;
1365 /// <summary>
1366 /// Instantiate the generic type `t' with the type arguments `args'.
1367 /// Use this constructor if you already know the fully resolved
1368 /// generic type.
1369 /// </summary>
1370 public GenericTypeExpr (Type t, TypeArguments args, Location l)
1372 open_type = t.GetGenericTypeDefinition ();
1374 loc = l;
1375 this.args = args;
1378 public TypeArguments TypeArguments {
1379 get { return args; }
1382 public override string GetSignatureForError ()
1384 return TypeManager.CSharpName (type);
1387 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
1389 eclass = ExprClass.Type;
1391 if (!args.Resolve (ec))
1392 return null;
1394 gen_params = open_type.GetGenericArguments ();
1395 Type[] atypes = args.Arguments;
1397 if (atypes.Length != gen_params.Length) {
1398 Namespace.Error_InvalidNumberOfTypeArguments (ec.Compiler.Report, open_type, loc);
1399 return null;
1403 // Now bind the parameters
1405 type = open_type.MakeGenericType (atypes);
1406 return this;
1409 /// <summary>
1410 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1411 /// after fully resolving the constructed type.
1412 /// </summary>
1413 public bool CheckConstraints (IMemberContext ec)
1415 return ConstraintChecker.CheckConstraints (ec, open_type, gen_params, args.Arguments, loc);
1418 public override bool CheckAccessLevel (IMemberContext mc)
1420 return mc.CurrentTypeDefinition.CheckAccessLevel (open_type);
1423 public bool HasDynamicArguments ()
1425 return HasDynamicArguments (args.Arguments);
1428 static bool HasDynamicArguments (Type[] args)
1430 foreach (var item in args)
1432 if (TypeManager.IsGenericType (item))
1433 return HasDynamicArguments (TypeManager.GetTypeArguments (item));
1435 if (TypeManager.IsDynamicType (item))
1436 return true;
1439 return false;
1442 public override bool IsClass {
1443 get { return open_type.IsClass; }
1446 public override bool IsValueType {
1447 get { return TypeManager.IsStruct (open_type); }
1450 public override bool IsInterface {
1451 get { return open_type.IsInterface; }
1454 public override bool IsSealed {
1455 get { return open_type.IsSealed; }
1458 public override bool Equals (object obj)
1460 GenericTypeExpr cobj = obj as GenericTypeExpr;
1461 if (cobj == null)
1462 return false;
1464 if ((type == null) || (cobj.type == null))
1465 return false;
1467 return type == cobj.type;
1470 public override int GetHashCode ()
1472 return base.GetHashCode ();
1476 public abstract class ConstraintChecker
1478 protected readonly Type[] gen_params;
1479 protected readonly Type[] atypes;
1480 protected readonly Location loc;
1481 protected Report Report;
1483 protected ConstraintChecker (Type[] gen_params, Type[] atypes, Location loc, Report r)
1485 this.gen_params = gen_params;
1486 this.atypes = atypes;
1487 this.loc = loc;
1488 this.Report = r;
1491 /// <summary>
1492 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1493 /// after fully resolving the constructed type.
1494 /// </summary>
1495 public bool CheckConstraints (IMemberContext ec)
1497 for (int i = 0; i < gen_params.Length; i++) {
1498 if (!CheckConstraints (ec, i))
1499 return false;
1502 return true;
1505 protected bool CheckConstraints (IMemberContext ec, int index)
1507 Type atype = TypeManager.TypeToCoreType (atypes [index]);
1508 Type ptype = gen_params [index];
1510 if (atype == ptype)
1511 return true;
1513 Expression aexpr = new EmptyExpression (atype);
1515 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1516 if (gc == null)
1517 return true;
1519 bool is_class, is_struct;
1520 if (atype.IsGenericParameter) {
1521 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1522 if (agc != null) {
1523 if (agc is Constraints) {
1524 // FIXME: No constraints can be resolved here, we are in
1525 // completely wrong/different context. This path is hit
1526 // when resolving base type of unresolved generic type
1527 // with constraints. We are waiting with CheckConsttraints
1528 // after type-definition but not in this case
1529 if (!((Constraints) agc).Resolve (null, null, Report))
1530 return true;
1532 is_class = agc.IsReferenceType;
1533 is_struct = agc.IsValueType;
1534 } else {
1535 is_class = is_struct = false;
1537 } else {
1538 is_class = TypeManager.IsReferenceType (atype);
1539 is_struct = TypeManager.IsValueType (atype) && !TypeManager.IsNullableType (atype);
1543 // First, check the `class' and `struct' constraints.
1545 if (gc.HasReferenceTypeConstraint && !is_class) {
1546 Report.Error (452, loc, "The type `{0}' must be " +
1547 "a reference 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;
1554 } else if (gc.HasValueTypeConstraint && !is_struct) {
1555 Report.Error (453, loc, "The type `{0}' must be a " +
1556 "non-nullable value type in order to use it " +
1557 "as type parameter `{1}' in the " +
1558 "generic type or method `{2}'.",
1559 TypeManager.CSharpName (atype),
1560 TypeManager.CSharpName (ptype),
1561 GetSignatureForError ());
1562 return false;
1566 // The class constraint comes next.
1568 if (gc.HasClassConstraint) {
1569 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint))
1570 return false;
1574 // Now, check the interface constraints.
1576 if (gc.InterfaceConstraints != null) {
1577 foreach (Type it in gc.InterfaceConstraints) {
1578 if (!CheckConstraint (ec, ptype, aexpr, it))
1579 return false;
1584 // Finally, check the constructor constraint.
1587 if (!gc.HasConstructorConstraint)
1588 return true;
1590 if (TypeManager.IsValueType (atype))
1591 return true;
1593 if (HasDefaultConstructor (atype))
1594 return true;
1596 Report_SymbolRelatedToPreviousError ();
1597 Report.SymbolRelatedToPreviousError (atype);
1598 Report.Error (310, loc, "The type `{0}' must have a public " +
1599 "parameterless constructor in order to use it " +
1600 "as parameter `{1}' in the generic type or " +
1601 "method `{2}'",
1602 TypeManager.CSharpName (atype),
1603 TypeManager.CSharpName (ptype),
1604 GetSignatureForError ());
1605 return false;
1608 Type InflateType(IMemberContext ec, Type ctype)
1610 Type[] types = TypeManager.GetTypeArguments (ctype);
1612 TypeArguments new_args = new TypeArguments ();
1614 for (int i = 0; i < types.Length; i++) {
1615 Type t = TypeManager.TypeToCoreType (types [i]);
1617 if (t.IsGenericParameter) {
1618 int pos = t.GenericParameterPosition;
1619 if (t.DeclaringMethod == null && this is MethodConstraintChecker) {
1620 Type parent = ((MethodConstraintChecker) this).declaring_type;
1621 t = parent.GetGenericArguments ()[pos];
1622 } else {
1623 t = atypes [pos];
1625 } else if(TypeManager.HasGenericArguments(t)) {
1626 t = InflateType (ec, t);
1627 if (t == null) {
1628 return null;
1631 new_args.Add (new TypeExpression (t, loc));
1634 TypeExpr ct = new GenericTypeExpr (ctype, new_args, loc);
1635 if (ct.ResolveAsTypeStep (ec, false) == null)
1636 return null;
1638 return ct.Type;
1641 protected bool CheckConstraint (IMemberContext ec, Type ptype, Expression expr,
1642 Type ctype)
1645 // All this is needed because we don't have
1646 // real inflated type hierarchy
1648 if (TypeManager.HasGenericArguments (ctype)) {
1649 ctype = InflateType (ec, ctype);
1650 if(ctype == null) {
1651 return false;
1653 } else if (ctype.IsGenericParameter) {
1654 int pos = ctype.GenericParameterPosition;
1655 if (ctype.DeclaringMethod == null) {
1656 // FIXME: Implement
1657 return true;
1658 } else {
1659 ctype = atypes [pos];
1663 if (Convert.ImplicitStandardConversionExists (expr, ctype))
1664 return true;
1666 Report_SymbolRelatedToPreviousError ();
1667 Report.SymbolRelatedToPreviousError (expr.Type);
1669 if (TypeManager.IsNullableType (expr.Type) && ctype.IsInterface) {
1670 Report.Error (313, loc,
1671 "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. " +
1672 "The nullable type `{0}' never satisfies interface constraint of type `{3}'",
1673 TypeManager.CSharpName (expr.Type), TypeManager.CSharpName (ptype),
1674 GetSignatureForError (), TypeManager.CSharpName (ctype));
1675 } else {
1676 Report.Error (309, loc,
1677 "The type `{0}' must be convertible to `{1}' in order to " +
1678 "use it as parameter `{2}' in the generic type or method `{3}'",
1679 TypeManager.CSharpName (expr.Type), TypeManager.CSharpName (ctype),
1680 TypeManager.CSharpName (ptype), GetSignatureForError ());
1682 return false;
1685 static bool HasDefaultConstructor (Type atype)
1687 TypeParameter tparam = TypeManager.LookupTypeParameter (atype);
1688 if (tparam != null) {
1689 if (tparam.GenericConstraints == null)
1690 return false;
1692 return tparam.GenericConstraints.HasConstructorConstraint ||
1693 tparam.GenericConstraints.HasValueTypeConstraint;
1696 if (atype.IsAbstract)
1697 return false;
1699 again:
1700 atype = TypeManager.DropGenericTypeArguments (atype);
1701 if (atype is TypeBuilder) {
1702 TypeContainer tc = TypeManager.LookupTypeContainer (atype);
1703 if (tc.InstanceConstructors == null) {
1704 atype = atype.BaseType;
1705 goto again;
1708 foreach (Constructor c in tc.InstanceConstructors) {
1709 if ((c.ModFlags & Modifiers.PUBLIC) == 0)
1710 continue;
1711 if ((c.Parameters.FixedParameters != null) &&
1712 (c.Parameters.FixedParameters.Length != 0))
1713 continue;
1714 if (c.Parameters.HasArglist || c.Parameters.HasParams)
1715 continue;
1717 return true;
1721 MemberInfo [] list = TypeManager.MemberLookup (null, null, atype, MemberTypes.Constructor,
1722 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
1723 ConstructorInfo.ConstructorName, null);
1725 if (list == null)
1726 return false;
1728 foreach (MethodBase mb in list) {
1729 AParametersCollection pd = TypeManager.GetParameterData (mb);
1730 if (pd.Count == 0)
1731 return true;
1734 return false;
1737 protected abstract string GetSignatureForError ();
1738 protected abstract void Report_SymbolRelatedToPreviousError ();
1740 public static bool CheckConstraints (IMemberContext ec, MethodBase definition,
1741 MethodBase instantiated, Location loc)
1743 MethodConstraintChecker checker = new MethodConstraintChecker (
1744 definition, instantiated.DeclaringType, definition.GetGenericArguments (),
1745 instantiated.GetGenericArguments (), loc, ec.Compiler.Report);
1747 return checker.CheckConstraints (ec);
1750 public static bool CheckConstraints (IMemberContext ec, Type gt, Type[] gen_params,
1751 Type[] atypes, Location loc)
1753 TypeConstraintChecker checker = new TypeConstraintChecker (
1754 gt, gen_params, atypes, loc, ec.Compiler.Report);
1756 return checker.CheckConstraints (ec);
1759 protected class MethodConstraintChecker : ConstraintChecker
1761 MethodBase definition;
1762 public Type declaring_type;
1764 public MethodConstraintChecker (MethodBase definition, Type declaringType, Type[] gen_params,
1765 Type[] atypes, Location loc, Report r)
1766 : base (gen_params, atypes, loc, r)
1768 this.declaring_type = declaringType;
1769 this.definition = definition;
1772 protected override string GetSignatureForError ()
1774 return TypeManager.CSharpSignature (definition);
1777 protected override void Report_SymbolRelatedToPreviousError ()
1779 Report.SymbolRelatedToPreviousError (definition);
1783 protected class TypeConstraintChecker : ConstraintChecker
1785 Type gt;
1787 public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
1788 Location loc, Report r)
1789 : base (gen_params, atypes, loc, r)
1791 this.gt = gt;
1794 protected override string GetSignatureForError ()
1796 return TypeManager.CSharpName (gt);
1799 protected override void Report_SymbolRelatedToPreviousError ()
1801 Report.SymbolRelatedToPreviousError (gt);
1806 /// <summary>
1807 /// A generic method definition.
1808 /// </summary>
1809 public class GenericMethod : DeclSpace
1811 FullNamedExpression return_type;
1812 ParametersCompiled parameters;
1814 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
1815 FullNamedExpression return_type, ParametersCompiled parameters)
1816 : base (ns, parent, name, null)
1818 this.return_type = return_type;
1819 this.parameters = parameters;
1822 public override TypeContainer CurrentTypeDefinition {
1823 get {
1824 return Parent.CurrentTypeDefinition;
1828 public override TypeParameter[] CurrentTypeParameters {
1829 get {
1830 return base.type_params;
1834 public override TypeBuilder DefineType ()
1836 throw new Exception ();
1839 public override bool Define ()
1841 for (int i = 0; i < TypeParameters.Length; i++)
1842 if (!TypeParameters [i].Resolve (this))
1843 return false;
1845 return true;
1848 /// <summary>
1849 /// Define and resolve the type parameters.
1850 /// We're called from Method.Define().
1851 /// </summary>
1852 public bool Define (MethodOrOperator m)
1854 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1855 string[] snames = new string [names.Length];
1856 for (int i = 0; i < names.Length; i++) {
1857 string type_argument_name = names[i].Name;
1858 int idx = parameters.GetParameterIndexByName (type_argument_name);
1859 if (idx >= 0) {
1860 Block b = m.Block;
1861 if (b == null)
1862 b = new Block (null);
1864 b.Error_AlreadyDeclaredTypeParameter (Report, parameters [i].Location,
1865 type_argument_name, "method parameter");
1868 snames[i] = type_argument_name;
1871 GenericTypeParameterBuilder[] gen_params = m.MethodBuilder.DefineGenericParameters (snames);
1872 for (int i = 0; i < TypeParameters.Length; i++)
1873 TypeParameters [i].Define (gen_params [i]);
1875 if (!Define ())
1876 return false;
1878 for (int i = 0; i < TypeParameters.Length; i++) {
1879 if (!TypeParameters [i].ResolveType (this))
1880 return false;
1883 return true;
1886 /// <summary>
1887 /// We're called from MethodData.Define() after creating the MethodBuilder.
1888 /// </summary>
1889 public bool DefineType (IMemberContext ec, MethodBuilder mb,
1890 MethodInfo implementing, bool is_override)
1892 for (int i = 0; i < TypeParameters.Length; i++)
1893 if (!TypeParameters [i].DefineType (
1894 ec, mb, implementing, is_override))
1895 return false;
1897 bool ok = parameters.Resolve (ec);
1899 if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec, false) == null))
1900 ok = false;
1902 return ok;
1905 public void EmitAttributes ()
1907 for (int i = 0; i < TypeParameters.Length; i++)
1908 TypeParameters [i].Emit ();
1910 if (OptAttributes != null)
1911 OptAttributes.Emit ();
1914 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1915 MemberFilter filter, object criteria)
1917 throw new Exception ();
1920 public override string GetSignatureForError ()
1922 return base.GetSignatureForError () + parameters.GetSignatureForError ();
1925 public override MemberCache MemberCache {
1926 get {
1927 return null;
1931 public override AttributeTargets AttributeTargets {
1932 get {
1933 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1937 public override string DocCommentHeader {
1938 get { return "M:"; }
1941 public new void VerifyClsCompliance ()
1943 foreach (TypeParameter tp in TypeParameters) {
1944 if (tp.Constraints == null)
1945 continue;
1947 tp.Constraints.VerifyClsCompliance (Report);
1952 partial class TypeManager
1954 public static TypeContainer LookupGenericTypeContainer (Type t)
1956 t = DropGenericTypeArguments (t);
1957 return LookupTypeContainer (t);
1960 public static Variance GetTypeParameterVariance (Type type)
1962 TypeParameter tparam = LookupTypeParameter (type);
1963 if (tparam != null)
1964 return tparam.Variance;
1966 switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
1967 case GenericParameterAttributes.Covariant:
1968 return Variance.Covariant;
1969 case GenericParameterAttributes.Contravariant:
1970 return Variance.Contravariant;
1971 default:
1972 return Variance.None;
1976 public static Variance CheckTypeVariance (Type t, Variance expected, IMemberContext member)
1978 TypeParameter tp = LookupTypeParameter (t);
1979 if (tp != null) {
1980 Variance v = tp.Variance;
1981 if (expected == Variance.None && v != expected ||
1982 expected == Variance.Covariant && v == Variance.Contravariant ||
1983 expected == Variance.Contravariant && v == Variance.Covariant)
1984 tp.ErrorInvalidVariance (member, expected);
1986 return expected;
1989 if (t.IsGenericType) {
1990 Type[] targs_definition = GetTypeArguments (DropGenericTypeArguments (t));
1991 Type[] targs = GetTypeArguments (t);
1992 for (int i = 0; i < targs_definition.Length; ++i) {
1993 Variance v = GetTypeParameterVariance (targs_definition[i]);
1994 CheckTypeVariance (targs[i], (Variance) ((int)v * (int)expected), member);
1997 return expected;
2000 if (t.IsArray)
2001 return CheckTypeVariance (GetElementType (t), expected, member);
2003 return Variance.None;
2006 public static bool IsVariantOf (Type type1, Type type2)
2008 if (!type1.IsGenericType || !type2.IsGenericType)
2009 return false;
2011 Type generic_target_type = DropGenericTypeArguments (type2);
2012 if (DropGenericTypeArguments (type1) != generic_target_type)
2013 return false;
2015 Type[] t1 = GetTypeArguments (type1);
2016 Type[] t2 = GetTypeArguments (type2);
2017 Type[] targs_definition = GetTypeArguments (generic_target_type);
2018 for (int i = 0; i < targs_definition.Length; ++i) {
2019 Variance v = GetTypeParameterVariance (targs_definition [i]);
2020 if (v == Variance.None) {
2021 if (t1[i] == t2[i])
2022 continue;
2023 return false;
2026 if (v == Variance.Covariant) {
2027 if (!Convert.ImplicitReferenceConversionExists (new EmptyExpression (t1 [i]), t2 [i]))
2028 return false;
2029 } else if (!Convert.ImplicitReferenceConversionExists (new EmptyExpression (t2[i]), t1[i])) {
2030 return false;
2034 return true;
2037 /// <summary>
2038 /// Check whether `a' and `b' may become equal generic types.
2039 /// The algorithm to do that is a little bit complicated.
2040 /// </summary>
2041 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_inferred,
2042 Type[] method_inferred)
2044 if (a.IsGenericParameter) {
2046 // If a is an array of a's type, they may never
2047 // become equal.
2049 while (b.IsArray) {
2050 b = GetElementType (b);
2051 if (a.Equals (b))
2052 return false;
2056 // If b is a generic parameter or an actual type,
2057 // they may become equal:
2059 // class X<T,U> : I<T>, I<U>
2060 // class X<T> : I<T>, I<float>
2062 if (b.IsGenericParameter || !b.IsGenericType) {
2063 int pos = a.GenericParameterPosition;
2064 Type[] args = a.DeclaringMethod != null ? method_inferred : class_inferred;
2065 if (args [pos] == null) {
2066 args [pos] = b;
2067 return true;
2070 return args [pos] == a;
2074 // We're now comparing a type parameter with a
2075 // generic instance. They may become equal unless
2076 // the type parameter appears anywhere in the
2077 // generic instance:
2079 // class X<T,U> : I<T>, I<X<U>>
2080 // -> error because you could instanciate it as
2081 // X<X<int>,int>
2083 // class X<T> : I<T>, I<X<T>> -> ok
2086 Type[] bargs = GetTypeArguments (b);
2087 for (int i = 0; i < bargs.Length; i++) {
2088 if (a.Equals (bargs [i]))
2089 return false;
2092 return true;
2095 if (b.IsGenericParameter)
2096 return MayBecomeEqualGenericTypes (b, a, class_inferred, method_inferred);
2099 // At this point, neither a nor b are a type parameter.
2101 // If one of them is a generic instance, let
2102 // MayBecomeEqualGenericInstances() compare them (if the
2103 // other one is not a generic instance, they can never
2104 // become equal).
2107 if (a.IsGenericType || b.IsGenericType)
2108 return MayBecomeEqualGenericInstances (a, b, class_inferred, method_inferred);
2111 // If both of them are arrays.
2114 if (a.IsArray && b.IsArray) {
2115 if (a.GetArrayRank () != b.GetArrayRank ())
2116 return false;
2118 a = GetElementType (a);
2119 b = GetElementType (b);
2121 return MayBecomeEqualGenericTypes (a, b, class_inferred, method_inferred);
2125 // Ok, two ordinary types.
2128 return a.Equals (b);
2132 // Checks whether two generic instances may become equal for some
2133 // particular instantiation (26.3.1).
2135 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
2136 Type[] class_inferred,
2137 Type[] method_inferred)
2139 if (!a.IsGenericType || !b.IsGenericType)
2140 return false;
2141 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2142 return false;
2144 return MayBecomeEqualGenericInstances (
2145 GetTypeArguments (a), GetTypeArguments (b), class_inferred, method_inferred);
2148 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
2149 Type[] class_inferred,
2150 Type[] method_inferred)
2152 if (aargs.Length != bargs.Length)
2153 return false;
2155 for (int i = 0; i < aargs.Length; i++) {
2156 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_inferred, method_inferred))
2157 return false;
2160 return true;
2163 /// <summary>
2164 /// Type inference. Try to infer the type arguments from `method',
2165 /// which is invoked with the arguments `arguments'. This is used
2166 /// when resolving an Invocation or a DelegateInvocation and the user
2167 /// did not explicitly specify type arguments.
2168 /// </summary>
2169 public static int InferTypeArguments (ResolveContext ec, Arguments arguments, ref MethodBase method)
2171 ATypeInference ti = ATypeInference.CreateInstance (arguments);
2172 Type[] i_args = ti.InferMethodArguments (ec, method);
2173 if (i_args == null)
2174 return ti.InferenceScore;
2176 if (i_args.Length == 0)
2177 return 0;
2179 method = ((MethodInfo) method).MakeGenericMethod (i_args);
2180 return 0;
2184 public static bool InferTypeArguments (ResolveContext ec, AParametersCollection param, ref MethodBase method)
2186 if (!TypeManager.IsGenericMethod (method))
2187 return true;
2189 ATypeInference ti = ATypeInference.CreateInstance (DelegateCreation.CreateDelegateMethodArguments (param, Location.Null));
2190 Type[] i_args = ti.InferDelegateArguments (ec, method);
2191 if (i_args == null)
2192 return false;
2194 method = ((MethodInfo) method).MakeGenericMethod (i_args);
2195 return true;
2200 abstract class ATypeInference
2202 protected readonly Arguments arguments;
2203 protected readonly int arg_count;
2205 protected ATypeInference (Arguments arguments)
2207 this.arguments = arguments;
2208 if (arguments != null)
2209 arg_count = arguments.Count;
2212 public static ATypeInference CreateInstance (Arguments arguments)
2214 return new TypeInference (arguments);
2217 public virtual int InferenceScore {
2218 get {
2219 return int.MaxValue;
2223 public abstract Type[] InferMethodArguments (ResolveContext ec, MethodBase method);
2224 // public abstract Type[] InferDelegateArguments (ResolveContext ec, MethodBase method);
2228 // Implements C# type inference
2230 class TypeInference : ATypeInference
2233 // Tracks successful rate of type inference
2235 int score = int.MaxValue;
2237 public TypeInference (Arguments arguments)
2238 : base (arguments)
2242 public override int InferenceScore {
2243 get {
2244 return score;
2249 public override Type[] InferDelegateArguments (ResolveContext ec, MethodBase method)
2251 AParametersCollection pd = TypeManager.GetParameterData (method);
2252 if (arg_count != pd.Count)
2253 return null;
2255 Type[] d_gargs = method.GetGenericArguments ();
2256 TypeInferenceContext context = new TypeInferenceContext (d_gargs);
2258 // A lower-bound inference is made from each argument type Uj of D
2259 // to the corresponding parameter type Tj of M
2260 for (int i = 0; i < arg_count; ++i) {
2261 Type t = pd.Types [i];
2262 if (!t.IsGenericParameter)
2263 continue;
2265 context.LowerBoundInference (arguments [i].Expr.Type, t);
2268 if (!context.FixAllTypes (ec))
2269 return null;
2271 return context.InferredTypeArguments;
2274 public override Type[] InferMethodArguments (ResolveContext ec, MethodBase method)
2276 Type[] method_generic_args = method.GetGenericArguments ();
2277 TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2278 if (!context.UnfixedVariableExists)
2279 return Type.EmptyTypes;
2281 AParametersCollection pd = TypeManager.GetParameterData (method);
2282 if (!InferInPhases (ec, context, pd))
2283 return null;
2285 return context.InferredTypeArguments;
2289 // Implements method type arguments inference
2291 bool InferInPhases (ResolveContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
2293 int params_arguments_start;
2294 if (methodParameters.HasParams) {
2295 params_arguments_start = methodParameters.Count - 1;
2296 } else {
2297 params_arguments_start = arg_count;
2300 Type [] ptypes = methodParameters.Types;
2303 // The first inference phase
2305 Type method_parameter = null;
2306 for (int i = 0; i < arg_count; i++) {
2307 Argument a = arguments [i];
2308 if (a == null)
2309 continue;
2311 if (i < params_arguments_start) {
2312 method_parameter = methodParameters.Types [i];
2313 } else if (i == params_arguments_start) {
2314 if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2315 method_parameter = methodParameters.Types [params_arguments_start];
2316 else
2317 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2319 ptypes = (Type[]) ptypes.Clone ();
2320 ptypes [i] = method_parameter;
2324 // When a lambda expression, an anonymous method
2325 // is used an explicit argument type inference takes a place
2327 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2328 if (am != null) {
2329 if (am.ExplicitTypeInference (ec, tic, method_parameter))
2330 --score;
2331 continue;
2334 if (a.IsByRef) {
2335 score -= tic.ExactInference (a.Type, method_parameter);
2336 continue;
2339 if (a.Expr.Type == TypeManager.null_type)
2340 continue;
2342 if (TypeManager.IsValueType (method_parameter)) {
2343 score -= tic.LowerBoundInference (a.Type, method_parameter);
2344 continue;
2348 // Otherwise an output type inference is made
2350 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2354 // Part of the second phase but because it happens only once
2355 // we don't need to call it in cycle
2357 bool fixed_any = false;
2358 if (!tic.FixIndependentTypeArguments (ec, ptypes, ref fixed_any))
2359 return false;
2361 return DoSecondPhase (ec, tic, ptypes, !fixed_any);
2364 bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, Type[] methodParameters, bool fixDependent)
2366 bool fixed_any = false;
2367 if (fixDependent && !tic.FixDependentTypes (ec, ref fixed_any))
2368 return false;
2370 // If no further unfixed type variables exist, type inference succeeds
2371 if (!tic.UnfixedVariableExists)
2372 return true;
2374 if (!fixed_any && fixDependent)
2375 return false;
2377 // For all arguments where the corresponding argument output types
2378 // contain unfixed type variables but the input types do not,
2379 // an output type inference is made
2380 for (int i = 0; i < arg_count; i++) {
2382 // Align params arguments
2383 Type t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
2385 if (!TypeManager.IsDelegateType (t_i)) {
2386 if (TypeManager.DropGenericTypeArguments (t_i) != TypeManager.expression_type)
2387 continue;
2389 t_i = t_i.GetGenericArguments () [0];
2392 MethodInfo mi = Delegate.GetInvokeMethod (ec.Compiler, t_i, t_i);
2393 Type rtype = mi.ReturnType;
2395 #if MS_COMPATIBLE
2396 // Blablabla, because reflection does not work with dynamic types
2397 Type[] g_args = t_i.GetGenericArguments ();
2398 rtype = g_args[rtype.GenericParameterPosition];
2399 #endif
2401 if (tic.IsReturnTypeNonDependent (ec, mi, rtype))
2402 score -= tic.OutputTypeInference (ec, arguments [i].Expr, t_i);
2406 return DoSecondPhase (ec, tic, methodParameters, true);
2410 public class TypeInferenceContext
2412 enum BoundKind
2414 Exact = 0,
2415 Lower = 1,
2416 Upper = 2
2419 class BoundInfo
2421 public readonly Type Type;
2422 public readonly BoundKind Kind;
2424 public BoundInfo (Type type, BoundKind kind)
2426 this.Type = type;
2427 this.Kind = kind;
2430 public override int GetHashCode ()
2432 return Type.GetHashCode ();
2435 public override bool Equals (object obj)
2437 BoundInfo a = (BoundInfo) obj;
2438 return Type == a.Type && Kind == a.Kind;
2442 readonly Type[] unfixed_types;
2443 readonly Type[] fixed_types;
2444 readonly List<BoundInfo>[] bounds;
2445 bool failed;
2447 public TypeInferenceContext (Type[] typeArguments)
2449 if (typeArguments.Length == 0)
2450 throw new ArgumentException ("Empty generic arguments");
2452 fixed_types = new Type [typeArguments.Length];
2453 for (int i = 0; i < typeArguments.Length; ++i) {
2454 if (typeArguments [i].IsGenericParameter) {
2455 if (bounds == null) {
2456 bounds = new List<BoundInfo> [typeArguments.Length];
2457 unfixed_types = new Type [typeArguments.Length];
2459 unfixed_types [i] = typeArguments [i];
2460 } else {
2461 fixed_types [i] = typeArguments [i];
2467 // Used together with AddCommonTypeBound fo implement
2468 // 7.4.2.13 Finding the best common type of a set of expressions
2470 public TypeInferenceContext ()
2472 fixed_types = new Type [1];
2473 unfixed_types = new Type [1];
2474 unfixed_types[0] = InternalType.Arglist; // it can be any internal type
2475 bounds = new List<BoundInfo> [1];
2478 public Type[] InferredTypeArguments {
2479 get {
2480 return fixed_types;
2484 public void AddCommonTypeBound (Type type)
2486 AddToBounds (new BoundInfo (type, BoundKind.Lower), 0);
2489 void AddToBounds (BoundInfo bound, int index)
2492 // Some types cannot be used as type arguments
2494 if (bound.Type == TypeManager.void_type || bound.Type.IsPointer)
2495 return;
2497 var a = bounds [index];
2498 if (a == null) {
2499 a = new List<BoundInfo> ();
2500 bounds [index] = a;
2501 } else {
2502 if (a.Contains (bound))
2503 return;
2507 // SPEC: does not cover type inference using constraints
2509 //if (TypeManager.IsGenericParameter (t)) {
2510 // GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
2511 // if (constraints != null) {
2512 // //if (constraints.EffectiveBaseClass != null)
2513 // // t = constraints.EffectiveBaseClass;
2514 // }
2516 a.Add (bound);
2519 bool AllTypesAreFixed (Type[] types)
2521 foreach (Type t in types) {
2522 if (t.IsGenericParameter) {
2523 if (!IsFixed (t))
2524 return false;
2525 continue;
2528 if (t.IsGenericType)
2529 return AllTypesAreFixed (t.GetGenericArguments ());
2532 return true;
2536 // 26.3.3.8 Exact Inference
2538 public int ExactInference (Type u, Type v)
2540 // If V is an array type
2541 if (v.IsArray) {
2542 if (!u.IsArray)
2543 return 0;
2545 if (u.GetArrayRank () != v.GetArrayRank ())
2546 return 0;
2548 return ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
2551 // If V is constructed type and U is constructed type
2552 if (v.IsGenericType && !v.IsGenericTypeDefinition) {
2553 if (!u.IsGenericType)
2554 return 0;
2556 Type [] ga_u = u.GetGenericArguments ();
2557 Type [] ga_v = v.GetGenericArguments ();
2558 if (ga_u.Length != ga_v.Length)
2559 return 0;
2561 int score = 0;
2562 for (int i = 0; i < ga_u.Length; ++i)
2563 score += ExactInference (ga_u [i], ga_v [i]);
2565 return score > 0 ? 1 : 0;
2568 // If V is one of the unfixed type arguments
2569 int pos = IsUnfixed (v);
2570 if (pos == -1)
2571 return 0;
2573 AddToBounds (new BoundInfo (u, BoundKind.Exact), pos);
2574 return 1;
2577 public bool FixAllTypes (ResolveContext ec)
2579 for (int i = 0; i < unfixed_types.Length; ++i) {
2580 if (!FixType (ec, i))
2581 return false;
2583 return true;
2587 // All unfixed type variables Xi are fixed for which all of the following hold:
2588 // a, There is at least one type variable Xj that depends on Xi
2589 // b, Xi has a non-empty set of bounds
2591 public bool FixDependentTypes (ResolveContext ec, ref bool fixed_any)
2593 for (int i = 0; i < unfixed_types.Length; ++i) {
2594 if (unfixed_types[i] == null)
2595 continue;
2597 if (bounds[i] == null)
2598 continue;
2600 if (!FixType (ec, i))
2601 return false;
2603 fixed_any = true;
2606 return true;
2610 // All unfixed type variables Xi which depend on no Xj are fixed
2612 public bool FixIndependentTypeArguments (ResolveContext ec, Type[] methodParameters, ref bool fixed_any)
2614 var types_to_fix = new List<Type> (unfixed_types);
2615 for (int i = 0; i < methodParameters.Length; ++i) {
2616 Type t = methodParameters[i];
2618 if (!TypeManager.IsDelegateType (t)) {
2619 if (TypeManager.DropGenericTypeArguments (t) != TypeManager.expression_type)
2620 continue;
2622 t = t.GetGenericArguments () [0];
2625 if (t.IsGenericParameter)
2626 continue;
2628 MethodInfo invoke = Delegate.GetInvokeMethod (ec.Compiler, t, t);
2629 Type rtype = invoke.ReturnType;
2630 if (!rtype.IsGenericParameter && !rtype.IsGenericType)
2631 continue;
2633 #if MS_COMPATIBLE
2634 // Blablabla, because reflection does not work with dynamic types
2635 if (rtype.IsGenericParameter) {
2636 Type [] g_args = t.GetGenericArguments ();
2637 rtype = g_args [rtype.GenericParameterPosition];
2639 #endif
2640 // Remove dependent types, they cannot be fixed yet
2641 RemoveDependentTypes (types_to_fix, rtype);
2644 foreach (Type t in types_to_fix) {
2645 if (t == null)
2646 continue;
2648 int idx = IsUnfixed (t);
2649 if (idx >= 0 && !FixType (ec, idx)) {
2650 return false;
2654 fixed_any = types_to_fix.Count > 0;
2655 return true;
2659 // 26.3.3.10 Fixing
2661 public bool FixType (ResolveContext ec, int i)
2663 // It's already fixed
2664 if (unfixed_types[i] == null)
2665 throw new InternalErrorException ("Type argument has been already fixed");
2667 if (failed)
2668 return false;
2670 var candidates = bounds [i];
2671 if (candidates == null)
2672 return false;
2674 if (candidates.Count == 1) {
2675 unfixed_types[i] = null;
2676 Type t = candidates[0].Type;
2677 if (t == TypeManager.null_type)
2678 return false;
2680 fixed_types [i] = t;
2681 return true;
2685 // Determines a unique type from which there is
2686 // a standard implicit conversion to all the other
2687 // candidate types.
2689 Type best_candidate = null;
2690 int cii;
2691 int candidates_count = candidates.Count;
2692 for (int ci = 0; ci < candidates_count; ++ci) {
2693 BoundInfo bound = (BoundInfo)candidates [ci];
2694 for (cii = 0; cii < candidates_count; ++cii) {
2695 if (cii == ci)
2696 continue;
2698 BoundInfo cbound = (BoundInfo) candidates[cii];
2700 // Same type parameters with different bounds
2701 if (cbound.Type == bound.Type) {
2702 if (bound.Kind != BoundKind.Exact)
2703 bound = cbound;
2705 continue;
2708 if (bound.Kind == BoundKind.Exact || cbound.Kind == BoundKind.Exact) {
2709 if (cbound.Kind != BoundKind.Exact) {
2710 if (!Convert.ImplicitConversionExists (ec, new TypeExpression (cbound.Type, Location.Null), bound.Type)) {
2711 break;
2714 continue;
2717 if (bound.Kind != BoundKind.Exact) {
2718 if (!Convert.ImplicitConversionExists (ec, new TypeExpression (bound.Type, Location.Null), cbound.Type)) {
2719 break;
2722 bound = cbound;
2723 continue;
2726 break;
2729 if (bound.Kind == BoundKind.Lower) {
2730 if (!Convert.ImplicitConversionExists (ec, new TypeExpression (cbound.Type, Location.Null), bound.Type)) {
2731 break;
2733 } else {
2734 if (!Convert.ImplicitConversionExists (ec, new TypeExpression (bound.Type, Location.Null), cbound.Type)) {
2735 break;
2740 if (cii != candidates_count)
2741 continue;
2743 if (best_candidate != null && best_candidate != bound.Type)
2744 return false;
2746 best_candidate = bound.Type;
2749 if (best_candidate == null)
2750 return false;
2752 unfixed_types[i] = null;
2753 fixed_types[i] = best_candidate;
2754 return true;
2758 // Uses inferred types to inflate delegate type argument
2760 public Type InflateGenericArgument (Type parameter)
2762 if (parameter.IsGenericParameter) {
2764 // Inflate method generic argument (MVAR) only
2766 if (parameter.DeclaringMethod == null)
2767 return parameter;
2769 return fixed_types [parameter.GenericParameterPosition];
2772 if (parameter.IsGenericType) {
2773 Type [] parameter_targs = parameter.GetGenericArguments ();
2774 for (int ii = 0; ii < parameter_targs.Length; ++ii) {
2775 parameter_targs [ii] = InflateGenericArgument (parameter_targs [ii]);
2777 return parameter.GetGenericTypeDefinition ().MakeGenericType (parameter_targs);
2780 return parameter;
2784 // Tests whether all delegate input arguments are fixed and generic output type
2785 // requires output type inference
2787 public bool IsReturnTypeNonDependent (ResolveContext ec, MethodInfo invoke, Type returnType)
2789 if (returnType.IsGenericParameter) {
2790 if (IsFixed (returnType))
2791 return false;
2792 } else if (returnType.IsGenericType) {
2793 if (TypeManager.IsDelegateType (returnType)) {
2794 invoke = Delegate.GetInvokeMethod (ec.Compiler, returnType, returnType);
2795 return IsReturnTypeNonDependent (ec, invoke, invoke.ReturnType);
2798 Type[] g_args = returnType.GetGenericArguments ();
2800 // At least one unfixed return type has to exist
2801 if (AllTypesAreFixed (g_args))
2802 return false;
2803 } else {
2804 return false;
2807 // All generic input arguments have to be fixed
2808 AParametersCollection d_parameters = TypeManager.GetParameterData (invoke);
2809 return AllTypesAreFixed (d_parameters.Types);
2812 bool IsFixed (Type type)
2814 return IsUnfixed (type) == -1;
2817 int IsUnfixed (Type type)
2819 if (!type.IsGenericParameter)
2820 return -1;
2822 //return unfixed_types[type.GenericParameterPosition] != null;
2823 for (int i = 0; i < unfixed_types.Length; ++i) {
2824 if (unfixed_types [i] == type)
2825 return i;
2828 return -1;
2832 // 26.3.3.9 Lower-bound Inference
2834 public int LowerBoundInference (Type u, Type v)
2836 return LowerBoundInference (u, v, false);
2840 // Lower-bound (false) or Upper-bound (true) inference based on inversed argument
2842 int LowerBoundInference (Type u, Type v, bool inversed)
2844 // If V is one of the unfixed type arguments
2845 int pos = IsUnfixed (v);
2846 if (pos != -1) {
2847 AddToBounds (new BoundInfo (u, inversed ? BoundKind.Upper : BoundKind.Lower), pos);
2848 return 1;
2851 // If U is an array type
2852 if (u.IsArray) {
2853 int u_dim = u.GetArrayRank ();
2854 Type v_i;
2855 Type u_i = TypeManager.GetElementType (u);
2857 if (v.IsArray) {
2858 if (u_dim != v.GetArrayRank ())
2859 return 0;
2861 v_i = TypeManager.GetElementType (v);
2863 if (TypeManager.IsValueType (u_i))
2864 return ExactInference (u_i, v_i);
2866 return LowerBoundInference (u_i, v_i, inversed);
2869 if (u_dim != 1)
2870 return 0;
2872 if (v.IsGenericType) {
2873 Type g_v = v.GetGenericTypeDefinition ();
2874 if ((g_v != TypeManager.generic_ilist_type) && (g_v != TypeManager.generic_icollection_type) &&
2875 (g_v != TypeManager.generic_ienumerable_type))
2876 return 0;
2878 v_i = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (v) [0]);
2879 if (TypeManager.IsValueType (u_i))
2880 return ExactInference (u_i, v_i);
2882 return LowerBoundInference (u_i, v_i);
2884 } else if (v.IsGenericType && !v.IsGenericTypeDefinition) {
2886 // if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
2887 // such that U is identical to, inherits from (directly or indirectly),
2888 // or implements (directly or indirectly) C<U1..Uk>
2890 var u_candidates = new List<Type> ();
2891 if (u.IsGenericType)
2892 u_candidates.Add (u);
2894 for (Type t = u.BaseType; t != null; t = t.BaseType) {
2895 if (t.IsGenericType && !t.IsGenericTypeDefinition)
2896 u_candidates.Add (t);
2899 // TODO: Implement GetGenericInterfaces only and remove
2900 // the if from foreach
2901 u_candidates.AddRange (TypeManager.GetInterfaces (u));
2903 Type open_v = v.GetGenericTypeDefinition ();
2904 Type [] unique_candidate_targs = null;
2905 Type [] ga_v = v.GetGenericArguments ();
2906 foreach (Type u_candidate in u_candidates) {
2907 if (!u_candidate.IsGenericType || u_candidate.IsGenericTypeDefinition)
2908 continue;
2910 if (TypeManager.DropGenericTypeArguments (u_candidate) != open_v)
2911 continue;
2914 // The unique set of types U1..Uk means that if we have an interface I<T>,
2915 // class U : I<int>, I<long> then no type inference is made when inferring
2916 // type I<T> by applying type U because T could be int or long
2918 if (unique_candidate_targs != null) {
2919 Type[] second_unique_candidate_targs = u_candidate.GetGenericArguments ();
2920 if (TypeManager.IsEqual (unique_candidate_targs, second_unique_candidate_targs)) {
2921 unique_candidate_targs = second_unique_candidate_targs;
2922 continue;
2926 // This should always cause type inference failure
2928 failed = true;
2929 return 1;
2932 unique_candidate_targs = u_candidate.GetGenericArguments ();
2935 if (unique_candidate_targs != null) {
2936 Type[] ga_open_v = open_v.GetGenericArguments ();
2937 int score = 0;
2938 for (int i = 0; i < unique_candidate_targs.Length; ++i) {
2939 Variance variance = TypeManager.GetTypeParameterVariance (ga_open_v [i]);
2941 Type u_i = unique_candidate_targs [i];
2942 if (variance == Variance.None || TypeManager.IsValueType (u_i)) {
2943 if (ExactInference (u_i, ga_v [i]) == 0)
2944 ++score;
2945 } else {
2946 bool upper_bound = (variance == Variance.Contravariant && !inversed) ||
2947 (variance == Variance.Covariant && inversed);
2949 if (LowerBoundInference (u_i, ga_v [i], upper_bound) == 0)
2950 ++score;
2953 return score;
2957 return 0;
2961 // 26.3.3.6 Output Type Inference
2963 public int OutputTypeInference (ResolveContext ec, Expression e, Type t)
2965 // If e is a lambda or anonymous method with inferred return type
2966 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
2967 if (ame != null) {
2968 Type rt = ame.InferReturnType (ec, this, t);
2969 MethodInfo invoke = Delegate.GetInvokeMethod (ec.Compiler, t, t);
2971 if (rt == null) {
2972 AParametersCollection pd = TypeManager.GetParameterData (invoke);
2973 return ame.Parameters.Count == pd.Count ? 1 : 0;
2976 Type rtype = invoke.ReturnType;
2977 #if MS_COMPATIBLE
2978 // Blablabla, because reflection does not work with dynamic types
2979 Type [] g_args = t.GetGenericArguments ();
2980 rtype = g_args [rtype.GenericParameterPosition];
2981 #endif
2982 return LowerBoundInference (rt, rtype) + 1;
2986 // if E is a method group and T is a delegate type or expression tree type
2987 // return type Tb with parameter types T1..Tk and return type Tb, and overload
2988 // resolution of E with the types T1..Tk yields a single method with return type U,
2989 // then a lower-bound inference is made from U for Tb.
2991 if (e is MethodGroupExpr) {
2992 // TODO: Or expression tree
2993 if (!TypeManager.IsDelegateType (t))
2994 return 0;
2996 MethodInfo invoke = Delegate.GetInvokeMethod (ec.Compiler, t, t);
2997 Type rtype = invoke.ReturnType;
2998 #if MS_COMPATIBLE
2999 // Blablabla, because reflection does not work with dynamic types
3000 Type [] g_args = t.GetGenericArguments ();
3001 rtype = g_args [rtype.GenericParameterPosition];
3002 #endif
3004 if (!TypeManager.IsGenericType (rtype))
3005 return 0;
3007 MethodGroupExpr mg = (MethodGroupExpr) e;
3008 Arguments args = DelegateCreation.CreateDelegateMethodArguments (TypeManager.GetParameterData (invoke), e.Location);
3009 mg = mg.OverloadResolve (ec, ref args, true, e.Location);
3010 if (mg == null)
3011 return 0;
3013 // TODO: What should happen when return type is of generic type ?
3014 throw new NotImplementedException ();
3015 // return LowerBoundInference (null, rtype) + 1;
3019 // if e is an expression with type U, then
3020 // a lower-bound inference is made from U for T
3022 return LowerBoundInference (e.Type, t) * 2;
3025 void RemoveDependentTypes (List<Type> types, Type returnType)
3027 int idx = IsUnfixed (returnType);
3028 if (idx >= 0) {
3029 types [idx] = null;
3030 return;
3033 if (returnType.IsGenericType) {
3034 foreach (Type t in returnType.GetGenericArguments ()) {
3035 RemoveDependentTypes (types, t);
3040 public bool UnfixedVariableExists {
3041 get {
3042 if (unfixed_types == null)
3043 return false;
3045 foreach (Type ut in unfixed_types)
3046 if (ut != null)
3047 return true;
3048 return false;