2009-11-24 Jb Evain <jbevain@novell.com>
[mcs.git] / mcs / generic.cs
blobc70cfda8f701e643de494ea9d010c0a599998912
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;
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 ArrayList 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, ArrayList constraints,
232 Location loc)
234 this.name = name;
235 this.constraints = constraints;
236 this.loc = loc;
239 public override string TypeParameter {
240 get {
241 return name;
245 public Constraints Clone ()
247 return new Constraints (name, constraints, loc);
250 GenericParameterAttributes attrs;
251 TypeExpr class_constraint;
252 ArrayList iface_constraints;
253 ArrayList type_param_constraints;
254 int num_constraints;
255 Type class_constraint_type;
256 Type[] iface_constraint_types;
257 Type effective_base_type;
258 bool resolved;
259 bool resolved_types;
261 /// <summary>
262 /// Resolve the constraints - but only resolve things into Expression's, not
263 /// into actual types.
264 /// </summary>
265 public bool Resolve (MemberCore ec, TypeParameter tp, Report Report)
267 if (resolved)
268 return true;
270 if (ec == null)
271 return false;
273 iface_constraints = new ArrayList (2); // TODO: Too expensive allocation
274 type_param_constraints = new ArrayList ();
276 foreach (object obj in constraints) {
277 if (HasConstructorConstraint) {
278 Report.Error (401, loc,
279 "The new() constraint must be the last constraint specified");
280 return false;
283 if (obj is SpecialConstraint) {
284 SpecialConstraint sc = (SpecialConstraint) obj;
286 if (sc == SpecialConstraint.Constructor) {
287 if (!HasValueTypeConstraint) {
288 attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
289 continue;
292 Report.Error (451, loc, "The `new()' constraint " +
293 "cannot be used with the `struct' constraint");
294 return false;
297 if ((num_constraints > 0) || HasReferenceTypeConstraint || HasValueTypeConstraint) {
298 Report.Error (449, loc, "The `class' or `struct' " +
299 "constraint must be the first constraint specified");
300 return false;
303 if (sc == SpecialConstraint.ReferenceType)
304 attrs |= GenericParameterAttributes.ReferenceTypeConstraint;
305 else
306 attrs |= GenericParameterAttributes.NotNullableValueTypeConstraint;
307 continue;
310 int errors = Report.Errors;
311 FullNamedExpression fn = ((Expression) obj).ResolveAsTypeStep (ec, false);
313 if (fn == null) {
314 if (errors != Report.Errors)
315 return false;
317 NamespaceEntry.Error_NamespaceNotFound (loc, ((Expression)obj).GetSignatureForError (), Report);
318 return false;
321 TypeExpr expr;
322 GenericTypeExpr cexpr = fn as GenericTypeExpr;
323 if (cexpr != null) {
324 expr = cexpr.ResolveAsBaseTerminal (ec, false);
325 if (expr != null && cexpr.HasDynamicArguments ()) {
326 Report.Error (1968, cexpr.Location,
327 "A constraint cannot be the dynamic type `{0}'",
328 cexpr.GetSignatureForError ());
329 expr = null;
331 } else
332 expr = ((Expression) obj).ResolveAsTypeTerminal (ec, false);
334 if ((expr == null) || (expr.Type == null))
335 return false;
337 if (TypeManager.IsGenericParameter (expr.Type))
338 type_param_constraints.Add (expr);
339 else if (expr.IsInterface)
340 iface_constraints.Add (expr);
341 else if (class_constraint != null || iface_constraints.Count != 0) {
342 Report.Error (406, loc,
343 "The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
344 expr.GetSignatureForError ());
345 return false;
346 } else if (HasReferenceTypeConstraint || HasValueTypeConstraint) {
347 Report.Error (450, loc, "`{0}': cannot specify both " +
348 "a constraint class and the `class' " +
349 "or `struct' constraint", expr.GetSignatureForError ());
350 return false;
351 } else
352 class_constraint = expr;
356 // Checks whether each generic method parameter constraint type
357 // is valid with respect to T
359 if (tp != null && tp.Type.DeclaringMethod != null) {
360 TypeManager.CheckTypeVariance (expr.Type, Variance.Contravariant, ec as MemberCore);
363 if (!ec.IsAccessibleAs (fn.Type)) {
364 Report.SymbolRelatedToPreviousError (fn.Type);
365 Report.Error (703, loc,
366 "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
367 fn.GetSignatureForError (), ec.GetSignatureForError ());
370 num_constraints++;
373 ArrayList list = new ArrayList ();
374 foreach (TypeExpr iface_constraint in iface_constraints) {
375 foreach (Type type in list) {
376 if (!type.Equals (iface_constraint.Type))
377 continue;
379 Report.Error (405, loc,
380 "Duplicate constraint `{0}' for type " +
381 "parameter `{1}'.", iface_constraint.GetSignatureForError (),
382 name);
383 return false;
386 list.Add (iface_constraint.Type);
389 foreach (TypeExpr expr in type_param_constraints) {
390 foreach (Type type in list) {
391 if (!type.Equals (expr.Type))
392 continue;
394 Report.Error (405, loc,
395 "Duplicate constraint `{0}' for type " +
396 "parameter `{1}'.", expr.GetSignatureForError (), name);
397 return false;
400 list.Add (expr.Type);
403 iface_constraint_types = new Type [list.Count];
404 list.CopyTo (iface_constraint_types, 0);
406 if (class_constraint != null) {
407 class_constraint_type = class_constraint.Type;
408 if (class_constraint_type == null)
409 return false;
411 if (class_constraint_type.IsSealed) {
412 if (class_constraint_type.IsAbstract)
414 Report.Error (717, loc, "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
415 TypeManager.CSharpName (class_constraint_type));
417 else
419 Report.Error (701, loc, "`{0}' is not a valid constraint. A constraint must be an interface, " +
420 "a non-sealed class or a type parameter", TypeManager.CSharpName(class_constraint_type));
422 return false;
425 if ((class_constraint_type == TypeManager.array_type) ||
426 (class_constraint_type == TypeManager.delegate_type) ||
427 (class_constraint_type == TypeManager.enum_type) ||
428 (class_constraint_type == TypeManager.value_type) ||
429 (class_constraint_type == TypeManager.object_type) ||
430 class_constraint_type == TypeManager.multicast_delegate_type) {
431 Report.Error (702, loc,
432 "A constraint cannot be special class `{0}'",
433 TypeManager.CSharpName (class_constraint_type));
434 return false;
437 if (TypeManager.IsDynamicType (class_constraint_type)) {
438 Report.Error (1967, loc, "A constraint cannot be the dynamic type");
439 return false;
443 if (class_constraint_type != null)
444 effective_base_type = class_constraint_type;
445 else if (HasValueTypeConstraint)
446 effective_base_type = TypeManager.value_type;
447 else
448 effective_base_type = TypeManager.object_type;
450 if ((attrs & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0)
451 attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
453 resolved = true;
454 return true;
457 bool CheckTypeParameterConstraints (Type tparam, ref TypeExpr prevConstraint, ArrayList seen, Report Report)
459 seen.Add (tparam);
461 Constraints constraints = TypeManager.LookupTypeParameter (tparam).Constraints;
462 if (constraints == null)
463 return true;
465 if (constraints.HasValueTypeConstraint) {
466 Report.Error (456, loc,
467 "Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
468 tparam.Name, name);
469 return false;
473 // Checks whether there are no conflicts between type parameter constraints
475 // class Foo<T, U>
476 // where T : A
477 // where U : A, B // A and B are not convertible
479 if (constraints.HasClassConstraint) {
480 if (prevConstraint != null) {
481 Type t2 = constraints.ClassConstraint;
482 TypeExpr e2 = constraints.class_constraint;
484 if (!Convert.ImplicitReferenceConversionExists (prevConstraint, t2) &&
485 !Convert.ImplicitReferenceConversionExists (e2, prevConstraint.Type)) {
486 Report.Error (455, loc,
487 "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
488 name, TypeManager.CSharpName (prevConstraint.Type), TypeManager.CSharpName (t2));
489 return false;
493 prevConstraint = constraints.class_constraint;
496 if (constraints.type_param_constraints == null)
497 return true;
499 foreach (TypeExpr expr in constraints.type_param_constraints) {
500 if (seen.Contains (expr.Type)) {
501 Report.Error (454, loc, "Circular constraint " +
502 "dependency involving `{0}' and `{1}'",
503 tparam.Name, expr.GetSignatureForError ());
504 return false;
507 if (!CheckTypeParameterConstraints (expr.Type, ref prevConstraint, seen, Report))
508 return false;
511 return true;
514 /// <summary>
515 /// Resolve the constraints into actual types.
516 /// </summary>
517 public bool ResolveTypes (IMemberContext ec, Report r)
519 if (resolved_types)
520 return true;
522 resolved_types = true;
524 foreach (object obj in constraints) {
525 GenericTypeExpr cexpr = obj as GenericTypeExpr;
526 if (cexpr == null)
527 continue;
529 if (!cexpr.CheckConstraints (ec))
530 return false;
533 if (type_param_constraints.Count != 0) {
534 ArrayList seen = new ArrayList ();
535 TypeExpr prev_constraint = class_constraint;
536 foreach (TypeExpr expr in type_param_constraints) {
537 if (!CheckTypeParameterConstraints (expr.Type, ref prev_constraint, seen, r))
538 return false;
539 seen.Clear ();
543 for (int i = 0; i < iface_constraints.Count; ++i) {
544 TypeExpr iface_constraint = (TypeExpr) iface_constraints [i];
545 iface_constraint = iface_constraint.ResolveAsTypeTerminal (ec, false);
546 if (iface_constraint == null)
547 return false;
548 iface_constraints [i] = iface_constraint;
551 if (class_constraint != null) {
552 class_constraint = class_constraint.ResolveAsTypeTerminal (ec, false);
553 if (class_constraint == null)
554 return false;
557 return true;
560 public override GenericParameterAttributes Attributes {
561 get { return attrs; }
564 public override bool HasClassConstraint {
565 get { return class_constraint != null; }
568 public override Type ClassConstraint {
569 get { return class_constraint_type; }
572 public override Type[] InterfaceConstraints {
573 get { return iface_constraint_types; }
576 public override Type EffectiveBaseClass {
577 get { return effective_base_type; }
580 public bool IsSubclassOf (Type t)
582 if ((class_constraint_type != null) &&
583 class_constraint_type.IsSubclassOf (t))
584 return true;
586 if (iface_constraint_types == null)
587 return false;
589 foreach (Type iface in iface_constraint_types) {
590 if (TypeManager.IsSubclassOf (iface, t))
591 return true;
594 return false;
597 public Location Location {
598 get {
599 return loc;
603 /// <summary>
604 /// This is used when we're implementing a generic interface method.
605 /// Each method type parameter in implementing method must have the same
606 /// constraints than the corresponding type parameter in the interface
607 /// method. To do that, we're called on each of the implementing method's
608 /// type parameters.
609 /// </summary>
610 public bool AreEqual (GenericConstraints gc)
612 if (gc.Attributes != attrs)
613 return false;
615 if (HasClassConstraint != gc.HasClassConstraint)
616 return false;
617 if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
618 return false;
620 int gc_icount = gc.InterfaceConstraints != null ?
621 gc.InterfaceConstraints.Length : 0;
622 int icount = InterfaceConstraints != null ?
623 InterfaceConstraints.Length : 0;
625 if (gc_icount != icount)
626 return false;
628 for (int i = 0; i < gc.InterfaceConstraints.Length; ++i) {
629 Type iface = gc.InterfaceConstraints [i];
630 if (iface.IsGenericType)
631 iface = iface.GetGenericTypeDefinition ();
633 bool ok = false;
634 for (int ii = 0; ii < InterfaceConstraints.Length; ii++) {
635 Type check = InterfaceConstraints [ii];
636 if (check.IsGenericType)
637 check = check.GetGenericTypeDefinition ();
639 if (TypeManager.IsEqual (iface, check)) {
640 ok = true;
641 break;
645 if (!ok)
646 return false;
649 return true;
652 public void VerifyClsCompliance (Report r)
654 if (class_constraint_type != null && !AttributeTester.IsClsCompliant (class_constraint_type))
655 Warning_ConstrainIsNotClsCompliant (class_constraint_type, class_constraint.Location, r);
657 if (iface_constraint_types != null) {
658 for (int i = 0; i < iface_constraint_types.Length; ++i) {
659 if (!AttributeTester.IsClsCompliant (iface_constraint_types [i]))
660 Warning_ConstrainIsNotClsCompliant (iface_constraint_types [i],
661 ((TypeExpr)iface_constraints [i]).Location, r);
666 void Warning_ConstrainIsNotClsCompliant (Type t, Location loc, Report Report)
668 Report.SymbolRelatedToPreviousError (t);
669 Report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
670 TypeManager.CSharpName (t));
674 /// <summary>
675 /// A type parameter from a generic type definition.
676 /// </summary>
677 public class TypeParameter : MemberCore, IMemberContainer
679 static readonly string[] attribute_target = new string [] { "type parameter" };
681 DeclSpace decl;
682 GenericConstraints gc;
683 Constraints constraints;
684 GenericTypeParameterBuilder type;
685 MemberCache member_cache;
686 Variance variance;
688 public TypeParameter (DeclSpace parent, DeclSpace decl, string name,
689 Constraints constraints, Attributes attrs, Variance variance, Location loc)
690 : base (parent, new MemberName (name, loc), attrs)
692 this.decl = decl;
693 this.constraints = constraints;
694 this.variance = variance;
697 public GenericConstraints GenericConstraints {
698 get { return gc != null ? gc : constraints; }
701 public Constraints Constraints {
702 get { return constraints; }
705 public DeclSpace DeclSpace {
706 get { return decl; }
709 public Variance Variance {
710 get { return variance; }
713 public Type Type {
714 get { return type; }
717 /// <summary>
718 /// This is the first method which is called during the resolving
719 /// process; we're called immediately after creating the type parameters
720 /// with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
721 /// MethodBuilder).
723 /// We're either called from TypeContainer.DefineType() or from
724 /// GenericMethod.Define() (called from Method.Define()).
725 /// </summary>
726 public void Define (GenericTypeParameterBuilder type)
728 if (this.type != null)
729 throw new InvalidOperationException ();
731 this.type = type;
732 TypeManager.AddTypeParameter (type, this);
735 public void ErrorInvalidVariance (IMemberContext mc, Variance expected)
737 // TODO: Report.SymbolRelatedToPreviousError (mc);
738 string input_variance = Variance == Variance.Contravariant ? "contravariant" : "covariant";
739 string gtype_variance;
740 switch (expected) {
741 case Variance.Contravariant: gtype_variance = "contravariantly"; break;
742 case Variance.Covariant: gtype_variance = "covariantly"; break;
743 default: gtype_variance = "invariantly"; break;
746 Delegate d = mc as Delegate;
747 string parameters = d != null ? d.Parameters.GetSignatureForError () : "";
749 Report.Error (1961, Location,
750 "The {2} type parameter `{0}' must be {3} valid on `{1}{4}'",
751 GetSignatureForError (), mc.GetSignatureForError (), input_variance, gtype_variance, parameters);
754 /// <summary>
755 /// This is the second method which is called during the resolving
756 /// process - in case of class type parameters, we're called from
757 /// TypeContainer.ResolveType() - after it resolved the class'es
758 /// base class and interfaces. For method type parameters, we're
759 /// called immediately after Define().
761 /// We're just resolving the constraints into expressions here, we
762 /// don't resolve them into actual types.
764 /// Note that in the special case of partial generic classes, we may be
765 /// called _before_ Define() and we may also be called multiple types.
766 /// </summary>
767 public bool Resolve (DeclSpace ds)
769 if (constraints != null) {
770 if (!constraints.Resolve (ds, this, Report)) {
771 constraints = null;
772 return false;
776 return true;
779 /// <summary>
780 /// This is the third method which is called during the resolving
781 /// process. We're called immediately after calling DefineConstraints()
782 /// on all of the current class'es type parameters.
784 /// Our job is to resolve the constraints to actual types.
786 /// Note that we may have circular dependencies on type parameters - this
787 /// is why Resolve() and ResolveType() are separate.
788 /// </summary>
789 public bool ResolveType (IMemberContext ec)
791 if (constraints != null) {
792 if (!constraints.ResolveTypes (ec, Report)) {
793 constraints = null;
794 return false;
798 return true;
801 /// <summary>
802 /// This is the fourth and last method which is called during the resolving
803 /// process. We're called after everything is fully resolved and actually
804 /// register the constraints with SRE and the TypeManager.
805 /// </summary>
806 public bool DefineType (IMemberContext ec)
808 return DefineType (ec, null, null, false);
811 /// <summary>
812 /// This is the fith and last method which is called during the resolving
813 /// process. We're called after everything is fully resolved and actually
814 /// register the constraints with SRE and the TypeManager.
816 /// The `builder', `implementing' and `is_override' arguments are only
817 /// applicable to method type parameters.
818 /// </summary>
819 public bool DefineType (IMemberContext ec, MethodBuilder builder,
820 MethodInfo implementing, bool is_override)
822 if (!ResolveType (ec))
823 return false;
825 if (implementing != null) {
826 if (is_override && (constraints != null)) {
827 Report.Error (460, Location,
828 "`{0}': Cannot specify constraints for overrides or explicit interface implementation methods",
829 TypeManager.CSharpSignature (builder));
830 return false;
833 MethodBase mb = TypeManager.DropGenericMethodArguments (implementing);
835 int pos = type.GenericParameterPosition;
836 Type mparam = mb.GetGenericArguments () [pos];
837 GenericConstraints temp_gc = ReflectionConstraints.GetConstraints (mparam);
839 if (temp_gc != null)
840 gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
841 else if (constraints != null)
842 gc = new InflatedConstraints (constraints, implementing.DeclaringType);
844 bool ok = true;
845 if (constraints != null) {
846 if (temp_gc == null)
847 ok = false;
848 else if (!constraints.AreEqual (gc))
849 ok = false;
850 } else {
851 if (!is_override && (temp_gc != null))
852 ok = false;
855 if (!ok) {
856 Report.SymbolRelatedToPreviousError (implementing);
858 Report.Error (
859 425, Location, "The constraints for type " +
860 "parameter `{0}' of method `{1}' must match " +
861 "the constraints for type parameter `{2}' " +
862 "of interface method `{3}'. Consider using " +
863 "an explicit interface implementation instead",
864 Name, TypeManager.CSharpSignature (builder),
865 TypeManager.CSharpName (mparam), TypeManager.CSharpSignature (mb));
866 return false;
868 } else if (DeclSpace is CompilerGeneratedClass) {
869 TypeParameter[] tparams = DeclSpace.TypeParameters;
870 Type[] types = new Type [tparams.Length];
871 for (int i = 0; i < tparams.Length; i++)
872 types [i] = tparams [i].Type;
874 if (constraints != null)
875 gc = new InflatedConstraints (constraints, types);
876 } else {
877 gc = (GenericConstraints) constraints;
880 SetConstraints (type);
881 return true;
884 public static TypeParameter FindTypeParameter (TypeParameter[] tparams, string name)
886 foreach (var tp in tparams) {
887 if (tp.Name == name)
888 return tp;
891 return null;
894 public void SetConstraints (GenericTypeParameterBuilder type)
896 GenericParameterAttributes attr = GenericParameterAttributes.None;
897 if (variance == Variance.Contravariant)
898 attr |= GenericParameterAttributes.Contravariant;
899 else if (variance == Variance.Covariant)
900 attr |= GenericParameterAttributes.Covariant;
902 if (gc != null) {
903 if (gc.HasClassConstraint || gc.HasValueTypeConstraint)
904 type.SetBaseTypeConstraint (gc.EffectiveBaseClass);
906 attr |= gc.Attributes;
907 type.SetInterfaceConstraints (gc.InterfaceConstraints);
908 TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
911 type.SetGenericParameterAttributes (attr);
914 /// <summary>
915 /// This is called for each part of a partial generic type definition.
917 /// If `new_constraints' is not null and we don't already have constraints,
918 /// they become our constraints. If we already have constraints, we must
919 /// check that they're the same.
920 /// con
921 /// </summary>
922 public bool UpdateConstraints (MemberCore ec, Constraints new_constraints)
924 if (type == null)
925 throw new InvalidOperationException ();
927 if (new_constraints == null)
928 return true;
930 if (!new_constraints.Resolve (ec, this, Report))
931 return false;
932 if (!new_constraints.ResolveTypes (ec, Report))
933 return false;
935 if (constraints != null)
936 return constraints.AreEqual (new_constraints);
938 constraints = new_constraints;
939 return true;
942 public override void Emit ()
944 if (OptAttributes != null)
945 OptAttributes.Emit ();
947 base.Emit ();
950 public override string DocCommentHeader {
951 get {
952 throw new InvalidOperationException (
953 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
958 // MemberContainer
961 public override bool Define ()
963 return true;
966 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
968 type.SetCustomAttribute (cb);
971 public override AttributeTargets AttributeTargets {
972 get {
973 return AttributeTargets.GenericParameter;
977 public override string[] ValidAttributeTargets {
978 get {
979 return attribute_target;
984 // IMemberContainer
987 string IMemberContainer.Name {
988 get { return Name; }
991 MemberCache IMemberContainer.BaseCache {
992 get {
993 if (gc == null)
994 return null;
996 if (gc.EffectiveBaseClass.BaseType == null)
997 return null;
999 return TypeManager.LookupMemberCache (gc.EffectiveBaseClass.BaseType);
1003 bool IMemberContainer.IsInterface {
1004 get { return false; }
1007 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
1009 throw new NotSupportedException ();
1012 public MemberCache MemberCache {
1013 get {
1014 if (member_cache != null)
1015 return member_cache;
1017 if (gc == null)
1018 return null;
1020 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
1021 member_cache = new MemberCache (this, gc.EffectiveBaseClass, ifaces);
1023 return member_cache;
1027 public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1028 MemberFilter filter, object criteria)
1030 if (gc == null)
1031 return MemberList.Empty;
1033 ArrayList members = new ArrayList ();
1035 if (gc.HasClassConstraint) {
1036 MemberList list = TypeManager.FindMembers (
1037 gc.ClassConstraint, mt, bf, filter, criteria);
1039 members.AddRange (list);
1042 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
1043 foreach (Type t in ifaces) {
1044 MemberList list = TypeManager.FindMembers (
1045 t, mt, bf, filter, criteria);
1047 members.AddRange (list);
1050 return new MemberList (members);
1053 public bool IsSubclassOf (Type t)
1055 if (type.Equals (t))
1056 return true;
1058 if (constraints != null)
1059 return constraints.IsSubclassOf (t);
1061 return false;
1064 public void InflateConstraints (Type declaring)
1066 if (constraints != null)
1067 gc = new InflatedConstraints (constraints, declaring);
1070 public override bool IsClsComplianceRequired ()
1072 return false;
1075 protected class InflatedConstraints : GenericConstraints
1077 GenericConstraints gc;
1078 Type base_type;
1079 Type class_constraint;
1080 Type[] iface_constraints;
1081 Type[] dargs;
1083 public InflatedConstraints (GenericConstraints gc, Type declaring)
1084 : this (gc, TypeManager.GetTypeArguments (declaring))
1087 public InflatedConstraints (GenericConstraints gc, Type[] dargs)
1089 this.gc = gc;
1090 this.dargs = dargs;
1092 ArrayList list = new ArrayList ();
1093 if (gc.HasClassConstraint)
1094 list.Add (inflate (gc.ClassConstraint));
1095 foreach (Type iface in gc.InterfaceConstraints)
1096 list.Add (inflate (iface));
1098 bool has_class_constr = false;
1099 if (list.Count > 0) {
1100 Type first = (Type) list [0];
1101 has_class_constr = !first.IsGenericParameter && !first.IsInterface;
1104 if ((list.Count > 0) && has_class_constr) {
1105 class_constraint = (Type) list [0];
1106 iface_constraints = new Type [list.Count - 1];
1107 list.CopyTo (1, iface_constraints, 0, list.Count - 1);
1108 } else {
1109 iface_constraints = new Type [list.Count];
1110 list.CopyTo (iface_constraints, 0);
1113 if (HasValueTypeConstraint)
1114 base_type = TypeManager.value_type;
1115 else if (class_constraint != null)
1116 base_type = class_constraint;
1117 else
1118 base_type = TypeManager.object_type;
1121 Type inflate (Type t)
1123 if (t == null)
1124 return null;
1125 if (t.IsGenericParameter)
1126 return t.GenericParameterPosition < dargs.Length ? dargs [t.GenericParameterPosition] : t;
1127 if (t.IsGenericType) {
1128 Type[] args = t.GetGenericArguments ();
1129 Type[] inflated = new Type [args.Length];
1131 for (int i = 0; i < args.Length; i++)
1132 inflated [i] = inflate (args [i]);
1134 t = t.GetGenericTypeDefinition ();
1135 t = t.MakeGenericType (inflated);
1138 return t;
1141 public override string TypeParameter {
1142 get { return gc.TypeParameter; }
1145 public override GenericParameterAttributes Attributes {
1146 get { return gc.Attributes; }
1149 public override Type ClassConstraint {
1150 get { return class_constraint; }
1153 public override Type EffectiveBaseClass {
1154 get { return base_type; }
1157 public override Type[] InterfaceConstraints {
1158 get { return iface_constraints; }
1163 /// <summary>
1164 /// A TypeExpr which already resolved to a type parameter.
1165 /// </summary>
1166 public class TypeParameterExpr : TypeExpr {
1168 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1170 this.type = type_parameter.Type;
1171 this.eclass = ExprClass.TypeParameter;
1172 this.loc = loc;
1175 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
1177 throw new NotSupportedException ();
1180 public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
1182 return this;
1185 public override bool IsInterface {
1186 get { return false; }
1189 public override bool CheckAccessLevel (IMemberContext ds)
1191 return true;
1196 // Tracks the type arguments when instantiating a generic type. It's used
1197 // by both type arguments and type parameters
1199 public class TypeArguments {
1200 ArrayList args;
1201 Type[] atypes;
1203 public TypeArguments ()
1205 args = new ArrayList ();
1208 public TypeArguments (params FullNamedExpression[] types)
1210 this.args = new ArrayList (types);
1213 public void Add (FullNamedExpression type)
1215 args.Add (type);
1218 public void Add (TypeArguments new_args)
1220 args.AddRange (new_args.args);
1223 // TODO: Should be deleted
1224 public TypeParameterName[] GetDeclarations ()
1226 return (TypeParameterName[]) args.ToArray (typeof (TypeParameterName));
1229 /// <summary>
1230 /// We may only be used after Resolve() is called and return the fully
1231 /// resolved types.
1232 /// </summary>
1233 public Type[] Arguments {
1234 get {
1235 return atypes;
1239 public int Count {
1240 get {
1241 return args.Count;
1245 public string GetSignatureForError()
1247 StringBuilder sb = new StringBuilder();
1248 for (int i = 0; i < Count; ++i)
1250 Expression expr = (Expression)args [i];
1251 sb.Append(expr.GetSignatureForError());
1252 if (i + 1 < Count)
1253 sb.Append(',');
1255 return sb.ToString();
1258 /// <summary>
1259 /// Resolve the type arguments.
1260 /// </summary>
1261 public bool Resolve (IMemberContext ec)
1263 if (atypes != null)
1264 return atypes.Length != 0;
1266 int count = args.Count;
1267 bool ok = true;
1269 atypes = new Type [count];
1271 for (int i = 0; i < count; i++){
1272 TypeExpr te = ((FullNamedExpression) args[i]).ResolveAsTypeTerminal (ec, false);
1273 if (te == null) {
1274 ok = false;
1275 continue;
1278 atypes[i] = te.Type;
1280 if (te.Type.IsSealed && te.Type.IsAbstract) {
1281 ec.Compiler.Report.Error (718, te.Location, "`{0}': static classes cannot be used as generic arguments",
1282 te.GetSignatureForError ());
1283 ok = false;
1286 if (te.Type.IsPointer || TypeManager.IsSpecialType (te.Type)) {
1287 ec.Compiler.Report.Error (306, te.Location,
1288 "The type `{0}' may not be used as a type argument",
1289 te.GetSignatureForError ());
1290 ok = false;
1294 if (!ok)
1295 atypes = Type.EmptyTypes;
1297 return ok;
1300 public TypeArguments Clone ()
1302 TypeArguments copy = new TypeArguments ();
1303 foreach (Expression ta in args)
1304 copy.args.Add (ta);
1306 return copy;
1310 public class TypeParameterName : SimpleName
1312 Attributes attributes;
1313 Variance variance;
1315 public TypeParameterName (string name, Attributes attrs, Location loc)
1316 : this (name, attrs, Variance.None, loc)
1320 public TypeParameterName (string name, Attributes attrs, Variance variance, Location loc)
1321 : base (name, loc)
1323 attributes = attrs;
1324 this.variance = variance;
1327 public Attributes OptAttributes {
1328 get {
1329 return attributes;
1333 public Variance Variance {
1334 get {
1335 return variance;
1340 /// <summary>
1341 /// A reference expression to generic type
1342 /// </summary>
1343 class GenericTypeExpr : TypeExpr
1345 TypeArguments args;
1346 Type[] gen_params; // TODO: Waiting for constrains check cleanup
1347 Type open_type;
1350 // Should be carefully used only with defined generic containers. Type parameters
1351 // can be used as type arguments in this case.
1353 // TODO: This could be GenericTypeExpr specialization
1355 public GenericTypeExpr (DeclSpace gType, Location l)
1357 open_type = gType.TypeBuilder.GetGenericTypeDefinition ();
1359 args = new TypeArguments ();
1360 foreach (TypeParameter type_param in gType.TypeParameters)
1361 args.Add (new TypeParameterExpr (type_param, l));
1363 this.loc = l;
1366 /// <summary>
1367 /// Instantiate the generic type `t' with the type arguments `args'.
1368 /// Use this constructor if you already know the fully resolved
1369 /// generic type.
1370 /// </summary>
1371 public GenericTypeExpr (Type t, TypeArguments args, Location l)
1373 open_type = t.GetGenericTypeDefinition ();
1375 loc = l;
1376 this.args = args;
1379 public TypeArguments TypeArguments {
1380 get { return args; }
1383 public override string GetSignatureForError ()
1385 return TypeManager.CSharpName (type);
1388 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
1390 eclass = ExprClass.Type;
1392 if (!args.Resolve (ec))
1393 return null;
1395 gen_params = open_type.GetGenericArguments ();
1396 Type[] atypes = args.Arguments;
1398 if (atypes.Length != gen_params.Length) {
1399 Namespace.Error_InvalidNumberOfTypeArguments (ec.Compiler.Report, open_type, loc);
1400 return null;
1404 // Now bind the parameters
1406 type = open_type.MakeGenericType (atypes);
1407 return this;
1410 /// <summary>
1411 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1412 /// after fully resolving the constructed type.
1413 /// </summary>
1414 public bool CheckConstraints (IMemberContext ec)
1416 return ConstraintChecker.CheckConstraints (ec, open_type, gen_params, args.Arguments, loc);
1419 public override bool CheckAccessLevel (IMemberContext mc)
1421 return mc.CurrentTypeDefinition.CheckAccessLevel (open_type);
1424 public bool HasDynamicArguments ()
1426 return HasDynamicArguments (args.Arguments);
1429 static bool HasDynamicArguments (Type[] args)
1431 foreach (var item in args)
1433 if (TypeManager.IsGenericType (item))
1434 return HasDynamicArguments (TypeManager.GetTypeArguments (item));
1436 if (TypeManager.IsDynamicType (item))
1437 return true;
1440 return false;
1443 public override bool IsClass {
1444 get { return open_type.IsClass; }
1447 public override bool IsValueType {
1448 get { return TypeManager.IsStruct (open_type); }
1451 public override bool IsInterface {
1452 get { return open_type.IsInterface; }
1455 public override bool IsSealed {
1456 get { return open_type.IsSealed; }
1459 public override bool Equals (object obj)
1461 GenericTypeExpr cobj = obj as GenericTypeExpr;
1462 if (cobj == null)
1463 return false;
1465 if ((type == null) || (cobj.type == null))
1466 return false;
1468 return type == cobj.type;
1471 public override int GetHashCode ()
1473 return base.GetHashCode ();
1477 public abstract class ConstraintChecker
1479 protected readonly Type[] gen_params;
1480 protected readonly Type[] atypes;
1481 protected readonly Location loc;
1482 protected Report Report;
1484 protected ConstraintChecker (Type[] gen_params, Type[] atypes, Location loc, Report r)
1486 this.gen_params = gen_params;
1487 this.atypes = atypes;
1488 this.loc = loc;
1489 this.Report = r;
1492 /// <summary>
1493 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1494 /// after fully resolving the constructed type.
1495 /// </summary>
1496 public bool CheckConstraints (IMemberContext ec)
1498 for (int i = 0; i < gen_params.Length; i++) {
1499 if (!CheckConstraints (ec, i))
1500 return false;
1503 return true;
1506 protected bool CheckConstraints (IMemberContext ec, int index)
1508 Type atype = TypeManager.TypeToCoreType (atypes [index]);
1509 Type ptype = gen_params [index];
1511 if (atype == ptype)
1512 return true;
1514 Expression aexpr = new EmptyExpression (atype);
1516 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1517 if (gc == null)
1518 return true;
1520 bool is_class, is_struct;
1521 if (atype.IsGenericParameter) {
1522 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1523 if (agc != null) {
1524 if (agc is Constraints) {
1525 // FIXME: No constraints can be resolved here, we are in
1526 // completely wrong/different context. This path is hit
1527 // when resolving base type of unresolved generic type
1528 // with constraints. We are waiting with CheckConsttraints
1529 // after type-definition but not in this case
1530 if (!((Constraints) agc).Resolve (null, null, Report))
1531 return true;
1533 is_class = agc.IsReferenceType;
1534 is_struct = agc.IsValueType;
1535 } else {
1536 is_class = is_struct = false;
1538 } else {
1539 is_class = TypeManager.IsReferenceType (atype);
1540 is_struct = TypeManager.IsValueType (atype) && !TypeManager.IsNullableType (atype);
1544 // First, check the `class' and `struct' constraints.
1546 if (gc.HasReferenceTypeConstraint && !is_class) {
1547 Report.Error (452, loc, "The type `{0}' must be " +
1548 "a reference type in order to use it " +
1549 "as type parameter `{1}' in the " +
1550 "generic type or method `{2}'.",
1551 TypeManager.CSharpName (atype),
1552 TypeManager.CSharpName (ptype),
1553 GetSignatureForError ());
1554 return false;
1555 } else if (gc.HasValueTypeConstraint && !is_struct) {
1556 Report.Error (453, loc, "The type `{0}' must be a " +
1557 "non-nullable value type in order to use it " +
1558 "as type parameter `{1}' in the " +
1559 "generic type or method `{2}'.",
1560 TypeManager.CSharpName (atype),
1561 TypeManager.CSharpName (ptype),
1562 GetSignatureForError ());
1563 return false;
1567 // The class constraint comes next.
1569 if (gc.HasClassConstraint) {
1570 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint))
1571 return false;
1575 // Now, check the interface constraints.
1577 if (gc.InterfaceConstraints != null) {
1578 foreach (Type it in gc.InterfaceConstraints) {
1579 if (!CheckConstraint (ec, ptype, aexpr, it))
1580 return false;
1585 // Finally, check the constructor constraint.
1588 if (!gc.HasConstructorConstraint)
1589 return true;
1591 if (TypeManager.IsValueType (atype))
1592 return true;
1594 if (HasDefaultConstructor (atype))
1595 return true;
1597 Report_SymbolRelatedToPreviousError ();
1598 Report.SymbolRelatedToPreviousError (atype);
1599 Report.Error (310, loc, "The type `{0}' must have a public " +
1600 "parameterless constructor in order to use it " +
1601 "as parameter `{1}' in the generic type or " +
1602 "method `{2}'",
1603 TypeManager.CSharpName (atype),
1604 TypeManager.CSharpName (ptype),
1605 GetSignatureForError ());
1606 return false;
1609 Type InflateType(IMemberContext ec, Type ctype)
1611 Type[] types = TypeManager.GetTypeArguments (ctype);
1613 TypeArguments new_args = new TypeArguments ();
1615 for (int i = 0; i < types.Length; i++) {
1616 Type t = TypeManager.TypeToCoreType (types [i]);
1618 if (t.IsGenericParameter) {
1619 int pos = t.GenericParameterPosition;
1620 if (t.DeclaringMethod == null && this is MethodConstraintChecker) {
1621 Type parent = ((MethodConstraintChecker) this).declaring_type;
1622 t = parent.GetGenericArguments ()[pos];
1623 } else {
1624 t = atypes [pos];
1626 } else if(TypeManager.HasGenericArguments(t)) {
1627 t = InflateType (ec, t);
1628 if (t == null) {
1629 return null;
1632 new_args.Add (new TypeExpression (t, loc));
1635 TypeExpr ct = new GenericTypeExpr (ctype, new_args, loc);
1636 if (ct.ResolveAsTypeStep (ec, false) == null)
1637 return null;
1639 return ct.Type;
1642 protected bool CheckConstraint (IMemberContext ec, Type ptype, Expression expr,
1643 Type ctype)
1646 // All this is needed because we don't have
1647 // real inflated type hierarchy
1649 if (TypeManager.HasGenericArguments (ctype)) {
1650 ctype = InflateType (ec, ctype);
1651 if(ctype == null) {
1652 return false;
1654 } else if (ctype.IsGenericParameter) {
1655 int pos = ctype.GenericParameterPosition;
1656 if (ctype.DeclaringMethod == null) {
1657 // FIXME: Implement
1658 return true;
1659 } else {
1660 ctype = atypes [pos];
1664 if (Convert.ImplicitStandardConversionExists (expr, ctype))
1665 return true;
1667 Report_SymbolRelatedToPreviousError ();
1668 Report.SymbolRelatedToPreviousError (expr.Type);
1670 if (TypeManager.IsNullableType (expr.Type) && ctype.IsInterface) {
1671 Report.Error (313, loc,
1672 "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. " +
1673 "The nullable type `{0}' never satisfies interface constraint of type `{3}'",
1674 TypeManager.CSharpName (expr.Type), TypeManager.CSharpName (ptype),
1675 GetSignatureForError (), TypeManager.CSharpName (ctype));
1676 } else {
1677 Report.Error (309, loc,
1678 "The type `{0}' must be convertible to `{1}' in order to " +
1679 "use it as parameter `{2}' in the generic type or method `{3}'",
1680 TypeManager.CSharpName (expr.Type), TypeManager.CSharpName (ctype),
1681 TypeManager.CSharpName (ptype), GetSignatureForError ());
1683 return false;
1686 static bool HasDefaultConstructor (Type atype)
1688 TypeParameter tparam = TypeManager.LookupTypeParameter (atype);
1689 if (tparam != null) {
1690 if (tparam.GenericConstraints == null)
1691 return false;
1693 return tparam.GenericConstraints.HasConstructorConstraint ||
1694 tparam.GenericConstraints.HasValueTypeConstraint;
1697 if (atype.IsAbstract)
1698 return false;
1700 again:
1701 atype = TypeManager.DropGenericTypeArguments (atype);
1702 if (atype is TypeBuilder) {
1703 TypeContainer tc = TypeManager.LookupTypeContainer (atype);
1704 if (tc.InstanceConstructors == null) {
1705 atype = atype.BaseType;
1706 goto again;
1709 foreach (Constructor c in tc.InstanceConstructors) {
1710 if ((c.ModFlags & Modifiers.PUBLIC) == 0)
1711 continue;
1712 if ((c.Parameters.FixedParameters != null) &&
1713 (c.Parameters.FixedParameters.Length != 0))
1714 continue;
1715 if (c.Parameters.HasArglist || c.Parameters.HasParams)
1716 continue;
1718 return true;
1722 MemberInfo [] list = TypeManager.MemberLookup (null, null, atype, MemberTypes.Constructor,
1723 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
1724 ConstructorInfo.ConstructorName, null);
1726 if (list == null)
1727 return false;
1729 foreach (MethodBase mb in list) {
1730 AParametersCollection pd = TypeManager.GetParameterData (mb);
1731 if (pd.Count == 0)
1732 return true;
1735 return false;
1738 protected abstract string GetSignatureForError ();
1739 protected abstract void Report_SymbolRelatedToPreviousError ();
1741 public static bool CheckConstraints (IMemberContext ec, MethodBase definition,
1742 MethodBase instantiated, Location loc)
1744 MethodConstraintChecker checker = new MethodConstraintChecker (
1745 definition, instantiated.DeclaringType, definition.GetGenericArguments (),
1746 instantiated.GetGenericArguments (), loc, ec.Compiler.Report);
1748 return checker.CheckConstraints (ec);
1751 public static bool CheckConstraints (IMemberContext ec, Type gt, Type[] gen_params,
1752 Type[] atypes, Location loc)
1754 TypeConstraintChecker checker = new TypeConstraintChecker (
1755 gt, gen_params, atypes, loc, ec.Compiler.Report);
1757 return checker.CheckConstraints (ec);
1760 protected class MethodConstraintChecker : ConstraintChecker
1762 MethodBase definition;
1763 public Type declaring_type;
1765 public MethodConstraintChecker (MethodBase definition, Type declaringType, Type[] gen_params,
1766 Type[] atypes, Location loc, Report r)
1767 : base (gen_params, atypes, loc, r)
1769 this.declaring_type = declaringType;
1770 this.definition = definition;
1773 protected override string GetSignatureForError ()
1775 return TypeManager.CSharpSignature (definition);
1778 protected override void Report_SymbolRelatedToPreviousError ()
1780 Report.SymbolRelatedToPreviousError (definition);
1784 protected class TypeConstraintChecker : ConstraintChecker
1786 Type gt;
1788 public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
1789 Location loc, Report r)
1790 : base (gen_params, atypes, loc, r)
1792 this.gt = gt;
1795 protected override string GetSignatureForError ()
1797 return TypeManager.CSharpName (gt);
1800 protected override void Report_SymbolRelatedToPreviousError ()
1802 Report.SymbolRelatedToPreviousError (gt);
1807 /// <summary>
1808 /// A generic method definition.
1809 /// </summary>
1810 public class GenericMethod : DeclSpace
1812 FullNamedExpression return_type;
1813 ParametersCompiled parameters;
1815 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
1816 FullNamedExpression return_type, ParametersCompiled parameters)
1817 : base (ns, parent, name, null)
1819 this.return_type = return_type;
1820 this.parameters = parameters;
1823 public override TypeContainer CurrentTypeDefinition {
1824 get {
1825 return Parent.CurrentTypeDefinition;
1829 public override TypeParameter[] CurrentTypeParameters {
1830 get {
1831 return base.type_params;
1835 public override TypeBuilder DefineType ()
1837 throw new Exception ();
1840 public override bool Define ()
1842 for (int i = 0; i < TypeParameters.Length; i++)
1843 if (!TypeParameters [i].Resolve (this))
1844 return false;
1846 return true;
1849 /// <summary>
1850 /// Define and resolve the type parameters.
1851 /// We're called from Method.Define().
1852 /// </summary>
1853 public bool Define (MethodOrOperator m)
1855 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1856 string[] snames = new string [names.Length];
1857 for (int i = 0; i < names.Length; i++) {
1858 string type_argument_name = names[i].Name;
1859 int idx = parameters.GetParameterIndexByName (type_argument_name);
1860 if (idx >= 0) {
1861 Block b = m.Block;
1862 if (b == null)
1863 b = new Block (null);
1865 b.Error_AlreadyDeclaredTypeParameter (Report, parameters [i].Location,
1866 type_argument_name, "method parameter");
1869 snames[i] = type_argument_name;
1872 GenericTypeParameterBuilder[] gen_params = m.MethodBuilder.DefineGenericParameters (snames);
1873 for (int i = 0; i < TypeParameters.Length; i++)
1874 TypeParameters [i].Define (gen_params [i]);
1876 if (!Define ())
1877 return false;
1879 for (int i = 0; i < TypeParameters.Length; i++) {
1880 if (!TypeParameters [i].ResolveType (this))
1881 return false;
1884 return true;
1887 /// <summary>
1888 /// We're called from MethodData.Define() after creating the MethodBuilder.
1889 /// </summary>
1890 public bool DefineType (IMemberContext ec, MethodBuilder mb,
1891 MethodInfo implementing, bool is_override)
1893 for (int i = 0; i < TypeParameters.Length; i++)
1894 if (!TypeParameters [i].DefineType (
1895 ec, mb, implementing, is_override))
1896 return false;
1898 bool ok = parameters.Resolve (ec);
1900 if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec, false) == null))
1901 ok = false;
1903 return ok;
1906 public void EmitAttributes ()
1908 for (int i = 0; i < TypeParameters.Length; i++)
1909 TypeParameters [i].Emit ();
1911 if (OptAttributes != null)
1912 OptAttributes.Emit ();
1915 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1916 MemberFilter filter, object criteria)
1918 throw new Exception ();
1921 public override string GetSignatureForError ()
1923 return base.GetSignatureForError () + parameters.GetSignatureForError ();
1926 public override MemberCache MemberCache {
1927 get {
1928 return null;
1932 public override AttributeTargets AttributeTargets {
1933 get {
1934 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1938 public override string DocCommentHeader {
1939 get { return "M:"; }
1942 public new void VerifyClsCompliance ()
1944 foreach (TypeParameter tp in TypeParameters) {
1945 if (tp.Constraints == null)
1946 continue;
1948 tp.Constraints.VerifyClsCompliance (Report);
1953 public partial class TypeManager
1955 static public Type activator_type;
1957 public static TypeContainer LookupGenericTypeContainer (Type t)
1959 t = DropGenericTypeArguments (t);
1960 return LookupTypeContainer (t);
1963 public static Variance GetTypeParameterVariance (Type type)
1965 TypeParameter tparam = LookupTypeParameter (type);
1966 if (tparam != null)
1967 return tparam.Variance;
1969 switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
1970 case GenericParameterAttributes.Covariant:
1971 return Variance.Covariant;
1972 case GenericParameterAttributes.Contravariant:
1973 return Variance.Contravariant;
1974 default:
1975 return Variance.None;
1979 public static Variance CheckTypeVariance (Type t, Variance expected, IMemberContext member)
1981 TypeParameter tp = LookupTypeParameter (t);
1982 if (tp != null) {
1983 Variance v = tp.Variance;
1984 if (expected == Variance.None && v != expected ||
1985 expected == Variance.Covariant && v == Variance.Contravariant ||
1986 expected == Variance.Contravariant && v == Variance.Covariant)
1987 tp.ErrorInvalidVariance (member, expected);
1989 return expected;
1992 if (t.IsGenericType) {
1993 Type[] targs_definition = GetTypeArguments (DropGenericTypeArguments (t));
1994 Type[] targs = GetTypeArguments (t);
1995 for (int i = 0; i < targs_definition.Length; ++i) {
1996 Variance v = GetTypeParameterVariance (targs_definition[i]);
1997 CheckTypeVariance (targs[i], (Variance) ((int)v * (int)expected), member);
2000 return expected;
2003 if (t.IsArray)
2004 return CheckTypeVariance (GetElementType (t), expected, member);
2006 return Variance.None;
2009 public static bool IsVariantOf (Type type1, Type type2)
2011 if (!type1.IsGenericType || !type2.IsGenericType)
2012 return false;
2014 Type generic_target_type = DropGenericTypeArguments (type2);
2015 if (DropGenericTypeArguments (type1) != generic_target_type)
2016 return false;
2018 Type[] t1 = GetTypeArguments (type1);
2019 Type[] t2 = GetTypeArguments (type2);
2020 Type[] targs_definition = GetTypeArguments (generic_target_type);
2021 for (int i = 0; i < targs_definition.Length; ++i) {
2022 Variance v = GetTypeParameterVariance (targs_definition [i]);
2023 if (v == Variance.None) {
2024 if (t1[i] == t2[i])
2025 continue;
2026 return false;
2029 if (v == Variance.Covariant) {
2030 if (!Convert.ImplicitReferenceConversionExists (new EmptyExpression (t1 [i]), t2 [i]))
2031 return false;
2032 } else if (!Convert.ImplicitReferenceConversionExists (new EmptyExpression (t2[i]), t1[i])) {
2033 return false;
2037 return true;
2040 /// <summary>
2041 /// Check whether `a' and `b' may become equal generic types.
2042 /// The algorithm to do that is a little bit complicated.
2043 /// </summary>
2044 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_inferred,
2045 Type[] method_inferred)
2047 if (a.IsGenericParameter) {
2049 // If a is an array of a's type, they may never
2050 // become equal.
2052 while (b.IsArray) {
2053 b = GetElementType (b);
2054 if (a.Equals (b))
2055 return false;
2059 // If b is a generic parameter or an actual type,
2060 // they may become equal:
2062 // class X<T,U> : I<T>, I<U>
2063 // class X<T> : I<T>, I<float>
2065 if (b.IsGenericParameter || !b.IsGenericType) {
2066 int pos = a.GenericParameterPosition;
2067 Type[] args = a.DeclaringMethod != null ? method_inferred : class_inferred;
2068 if (args [pos] == null) {
2069 args [pos] = b;
2070 return true;
2073 return args [pos] == a;
2077 // We're now comparing a type parameter with a
2078 // generic instance. They may become equal unless
2079 // the type parameter appears anywhere in the
2080 // generic instance:
2082 // class X<T,U> : I<T>, I<X<U>>
2083 // -> error because you could instanciate it as
2084 // X<X<int>,int>
2086 // class X<T> : I<T>, I<X<T>> -> ok
2089 Type[] bargs = GetTypeArguments (b);
2090 for (int i = 0; i < bargs.Length; i++) {
2091 if (a.Equals (bargs [i]))
2092 return false;
2095 return true;
2098 if (b.IsGenericParameter)
2099 return MayBecomeEqualGenericTypes (b, a, class_inferred, method_inferred);
2102 // At this point, neither a nor b are a type parameter.
2104 // If one of them is a generic instance, let
2105 // MayBecomeEqualGenericInstances() compare them (if the
2106 // other one is not a generic instance, they can never
2107 // become equal).
2110 if (a.IsGenericType || b.IsGenericType)
2111 return MayBecomeEqualGenericInstances (a, b, class_inferred, method_inferred);
2114 // If both of them are arrays.
2117 if (a.IsArray && b.IsArray) {
2118 if (a.GetArrayRank () != b.GetArrayRank ())
2119 return false;
2121 a = GetElementType (a);
2122 b = GetElementType (b);
2124 return MayBecomeEqualGenericTypes (a, b, class_inferred, method_inferred);
2128 // Ok, two ordinary types.
2131 return a.Equals (b);
2135 // Checks whether two generic instances may become equal for some
2136 // particular instantiation (26.3.1).
2138 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
2139 Type[] class_inferred,
2140 Type[] method_inferred)
2142 if (!a.IsGenericType || !b.IsGenericType)
2143 return false;
2144 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2145 return false;
2147 return MayBecomeEqualGenericInstances (
2148 GetTypeArguments (a), GetTypeArguments (b), class_inferred, method_inferred);
2151 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
2152 Type[] class_inferred,
2153 Type[] method_inferred)
2155 if (aargs.Length != bargs.Length)
2156 return false;
2158 for (int i = 0; i < aargs.Length; i++) {
2159 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_inferred, method_inferred))
2160 return false;
2163 return true;
2166 /// <summary>
2167 /// Type inference. Try to infer the type arguments from `method',
2168 /// which is invoked with the arguments `arguments'. This is used
2169 /// when resolving an Invocation or a DelegateInvocation and the user
2170 /// did not explicitly specify type arguments.
2171 /// </summary>
2172 public static int InferTypeArguments (ResolveContext ec, Arguments arguments, ref MethodBase method)
2174 ATypeInference ti = ATypeInference.CreateInstance (arguments);
2175 Type[] i_args = ti.InferMethodArguments (ec, method);
2176 if (i_args == null)
2177 return ti.InferenceScore;
2179 if (i_args.Length == 0)
2180 return 0;
2182 method = ((MethodInfo) method).MakeGenericMethod (i_args);
2183 return 0;
2187 public static bool InferTypeArguments (ResolveContext ec, AParametersCollection param, ref MethodBase method)
2189 if (!TypeManager.IsGenericMethod (method))
2190 return true;
2192 ATypeInference ti = ATypeInference.CreateInstance (DelegateCreation.CreateDelegateMethodArguments (param, Location.Null));
2193 Type[] i_args = ti.InferDelegateArguments (ec, method);
2194 if (i_args == null)
2195 return false;
2197 method = ((MethodInfo) method).MakeGenericMethod (i_args);
2198 return true;
2203 abstract class ATypeInference
2205 protected readonly Arguments arguments;
2206 protected readonly int arg_count;
2208 protected ATypeInference (Arguments arguments)
2210 this.arguments = arguments;
2211 if (arguments != null)
2212 arg_count = arguments.Count;
2215 public static ATypeInference CreateInstance (Arguments arguments)
2217 return new TypeInference (arguments);
2220 public virtual int InferenceScore {
2221 get {
2222 return int.MaxValue;
2226 public abstract Type[] InferMethodArguments (ResolveContext ec, MethodBase method);
2227 // public abstract Type[] InferDelegateArguments (ResolveContext ec, MethodBase method);
2231 // Implements C# type inference
2233 class TypeInference : ATypeInference
2236 // Tracks successful rate of type inference
2238 int score = int.MaxValue;
2240 public TypeInference (Arguments arguments)
2241 : base (arguments)
2245 public override int InferenceScore {
2246 get {
2247 return score;
2252 public override Type[] InferDelegateArguments (ResolveContext ec, MethodBase method)
2254 AParametersCollection pd = TypeManager.GetParameterData (method);
2255 if (arg_count != pd.Count)
2256 return null;
2258 Type[] d_gargs = method.GetGenericArguments ();
2259 TypeInferenceContext context = new TypeInferenceContext (d_gargs);
2261 // A lower-bound inference is made from each argument type Uj of D
2262 // to the corresponding parameter type Tj of M
2263 for (int i = 0; i < arg_count; ++i) {
2264 Type t = pd.Types [i];
2265 if (!t.IsGenericParameter)
2266 continue;
2268 context.LowerBoundInference (arguments [i].Expr.Type, t);
2271 if (!context.FixAllTypes (ec))
2272 return null;
2274 return context.InferredTypeArguments;
2277 public override Type[] InferMethodArguments (ResolveContext ec, MethodBase method)
2279 Type[] method_generic_args = method.GetGenericArguments ();
2280 TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2281 if (!context.UnfixedVariableExists)
2282 return Type.EmptyTypes;
2284 AParametersCollection pd = TypeManager.GetParameterData (method);
2285 if (!InferInPhases (ec, context, pd))
2286 return null;
2288 return context.InferredTypeArguments;
2292 // Implements method type arguments inference
2294 bool InferInPhases (ResolveContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
2296 int params_arguments_start;
2297 if (methodParameters.HasParams) {
2298 params_arguments_start = methodParameters.Count - 1;
2299 } else {
2300 params_arguments_start = arg_count;
2303 Type [] ptypes = methodParameters.Types;
2306 // The first inference phase
2308 Type method_parameter = null;
2309 for (int i = 0; i < arg_count; i++) {
2310 Argument a = arguments [i];
2311 if (a == null)
2312 continue;
2314 if (i < params_arguments_start) {
2315 method_parameter = methodParameters.Types [i];
2316 } else if (i == params_arguments_start) {
2317 if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2318 method_parameter = methodParameters.Types [params_arguments_start];
2319 else
2320 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2322 ptypes = (Type[]) ptypes.Clone ();
2323 ptypes [i] = method_parameter;
2327 // When a lambda expression, an anonymous method
2328 // is used an explicit argument type inference takes a place
2330 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2331 if (am != null) {
2332 if (am.ExplicitTypeInference (ec, tic, method_parameter))
2333 --score;
2334 continue;
2337 if (a.IsByRef) {
2338 score -= tic.ExactInference (a.Type, method_parameter);
2339 continue;
2342 if (a.Expr.Type == TypeManager.null_type)
2343 continue;
2345 if (TypeManager.IsValueType (method_parameter)) {
2346 score -= tic.LowerBoundInference (a.Type, method_parameter);
2347 continue;
2351 // Otherwise an output type inference is made
2353 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2357 // Part of the second phase but because it happens only once
2358 // we don't need to call it in cycle
2360 bool fixed_any = false;
2361 if (!tic.FixIndependentTypeArguments (ec, ptypes, ref fixed_any))
2362 return false;
2364 return DoSecondPhase (ec, tic, ptypes, !fixed_any);
2367 bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, Type[] methodParameters, bool fixDependent)
2369 bool fixed_any = false;
2370 if (fixDependent && !tic.FixDependentTypes (ec, ref fixed_any))
2371 return false;
2373 // If no further unfixed type variables exist, type inference succeeds
2374 if (!tic.UnfixedVariableExists)
2375 return true;
2377 if (!fixed_any && fixDependent)
2378 return false;
2380 // For all arguments where the corresponding argument output types
2381 // contain unfixed type variables but the input types do not,
2382 // an output type inference is made
2383 for (int i = 0; i < arg_count; i++) {
2385 // Align params arguments
2386 Type t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
2388 if (!TypeManager.IsDelegateType (t_i)) {
2389 if (TypeManager.DropGenericTypeArguments (t_i) != TypeManager.expression_type)
2390 continue;
2392 t_i = t_i.GetGenericArguments () [0];
2395 MethodInfo mi = Delegate.GetInvokeMethod (ec.Compiler, t_i, t_i);
2396 Type rtype = mi.ReturnType;
2398 #if MS_COMPATIBLE
2399 // Blablabla, because reflection does not work with dynamic types
2400 Type[] g_args = t_i.GetGenericArguments ();
2401 rtype = g_args[rtype.GenericParameterPosition];
2402 #endif
2404 if (tic.IsReturnTypeNonDependent (ec, mi, rtype))
2405 score -= tic.OutputTypeInference (ec, arguments [i].Expr, t_i);
2409 return DoSecondPhase (ec, tic, methodParameters, true);
2413 public class TypeInferenceContext
2415 enum BoundKind
2417 Exact = 0,
2418 Lower = 1,
2419 Upper = 2
2422 class BoundInfo
2424 public readonly Type Type;
2425 public readonly BoundKind Kind;
2427 public BoundInfo (Type type, BoundKind kind)
2429 this.Type = type;
2430 this.Kind = kind;
2433 public override int GetHashCode ()
2435 return Type.GetHashCode ();
2438 public override bool Equals (object obj)
2440 BoundInfo a = (BoundInfo) obj;
2441 return Type == a.Type && Kind == a.Kind;
2445 readonly Type[] unfixed_types;
2446 readonly Type[] fixed_types;
2447 readonly ArrayList[] bounds;
2448 bool failed;
2450 public TypeInferenceContext (Type[] typeArguments)
2452 if (typeArguments.Length == 0)
2453 throw new ArgumentException ("Empty generic arguments");
2455 fixed_types = new Type [typeArguments.Length];
2456 for (int i = 0; i < typeArguments.Length; ++i) {
2457 if (typeArguments [i].IsGenericParameter) {
2458 if (bounds == null) {
2459 bounds = new ArrayList [typeArguments.Length];
2460 unfixed_types = new Type [typeArguments.Length];
2462 unfixed_types [i] = typeArguments [i];
2463 } else {
2464 fixed_types [i] = typeArguments [i];
2470 // Used together with AddCommonTypeBound fo implement
2471 // 7.4.2.13 Finding the best common type of a set of expressions
2473 public TypeInferenceContext ()
2475 fixed_types = new Type [1];
2476 unfixed_types = new Type [1];
2477 unfixed_types[0] = InternalType.Arglist; // it can be any internal type
2478 bounds = new ArrayList [1];
2481 public Type[] InferredTypeArguments {
2482 get {
2483 return fixed_types;
2487 public void AddCommonTypeBound (Type type)
2489 AddToBounds (new BoundInfo (type, BoundKind.Lower), 0);
2492 void AddToBounds (BoundInfo bound, int index)
2495 // Some types cannot be used as type arguments
2497 if (bound.Type == TypeManager.void_type || bound.Type.IsPointer)
2498 return;
2500 ArrayList a = bounds [index];
2501 if (a == null) {
2502 a = new ArrayList ();
2503 bounds [index] = a;
2504 } else {
2505 if (a.Contains (bound))
2506 return;
2510 // SPEC: does not cover type inference using constraints
2512 //if (TypeManager.IsGenericParameter (t)) {
2513 // GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
2514 // if (constraints != null) {
2515 // //if (constraints.EffectiveBaseClass != null)
2516 // // t = constraints.EffectiveBaseClass;
2517 // }
2519 a.Add (bound);
2522 bool AllTypesAreFixed (Type[] types)
2524 foreach (Type t in types) {
2525 if (t.IsGenericParameter) {
2526 if (!IsFixed (t))
2527 return false;
2528 continue;
2531 if (t.IsGenericType)
2532 return AllTypesAreFixed (t.GetGenericArguments ());
2535 return true;
2539 // 26.3.3.8 Exact Inference
2541 public int ExactInference (Type u, Type v)
2543 // If V is an array type
2544 if (v.IsArray) {
2545 if (!u.IsArray)
2546 return 0;
2548 if (u.GetArrayRank () != v.GetArrayRank ())
2549 return 0;
2551 return ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
2554 // If V is constructed type and U is constructed type
2555 if (v.IsGenericType && !v.IsGenericTypeDefinition) {
2556 if (!u.IsGenericType)
2557 return 0;
2559 Type [] ga_u = u.GetGenericArguments ();
2560 Type [] ga_v = v.GetGenericArguments ();
2561 if (ga_u.Length != ga_v.Length)
2562 return 0;
2564 int score = 0;
2565 for (int i = 0; i < ga_u.Length; ++i)
2566 score += ExactInference (ga_u [i], ga_v [i]);
2568 return score > 0 ? 1 : 0;
2571 // If V is one of the unfixed type arguments
2572 int pos = IsUnfixed (v);
2573 if (pos == -1)
2574 return 0;
2576 AddToBounds (new BoundInfo (u, BoundKind.Exact), pos);
2577 return 1;
2580 public bool FixAllTypes (ResolveContext ec)
2582 for (int i = 0; i < unfixed_types.Length; ++i) {
2583 if (!FixType (ec, i))
2584 return false;
2586 return true;
2590 // All unfixed type variables Xi are fixed for which all of the following hold:
2591 // a, There is at least one type variable Xj that depends on Xi
2592 // b, Xi has a non-empty set of bounds
2594 public bool FixDependentTypes (ResolveContext ec, ref bool fixed_any)
2596 for (int i = 0; i < unfixed_types.Length; ++i) {
2597 if (unfixed_types[i] == null)
2598 continue;
2600 if (bounds[i] == null)
2601 continue;
2603 if (!FixType (ec, i))
2604 return false;
2606 fixed_any = true;
2609 return true;
2613 // All unfixed type variables Xi which depend on no Xj are fixed
2615 public bool FixIndependentTypeArguments (ResolveContext ec, Type[] methodParameters, ref bool fixed_any)
2617 ArrayList types_to_fix = new ArrayList (unfixed_types);
2618 for (int i = 0; i < methodParameters.Length; ++i) {
2619 Type t = methodParameters[i];
2621 if (!TypeManager.IsDelegateType (t)) {
2622 if (TypeManager.DropGenericTypeArguments (t) != TypeManager.expression_type)
2623 continue;
2625 t = t.GetGenericArguments () [0];
2628 if (t.IsGenericParameter)
2629 continue;
2631 MethodInfo invoke = Delegate.GetInvokeMethod (ec.Compiler, t, t);
2632 Type rtype = invoke.ReturnType;
2633 if (!rtype.IsGenericParameter && !rtype.IsGenericType)
2634 continue;
2636 #if MS_COMPATIBLE
2637 // Blablabla, because reflection does not work with dynamic types
2638 if (rtype.IsGenericParameter) {
2639 Type [] g_args = t.GetGenericArguments ();
2640 rtype = g_args [rtype.GenericParameterPosition];
2642 #endif
2643 // Remove dependent types, they cannot be fixed yet
2644 RemoveDependentTypes (types_to_fix, rtype);
2647 foreach (Type t in types_to_fix) {
2648 if (t == null)
2649 continue;
2651 int idx = IsUnfixed (t);
2652 if (idx >= 0 && !FixType (ec, idx)) {
2653 return false;
2657 fixed_any = types_to_fix.Count > 0;
2658 return true;
2662 // 26.3.3.10 Fixing
2664 public bool FixType (ResolveContext ec, int i)
2666 // It's already fixed
2667 if (unfixed_types[i] == null)
2668 throw new InternalErrorException ("Type argument has been already fixed");
2670 if (failed)
2671 return false;
2673 ArrayList candidates = (ArrayList)bounds [i];
2674 if (candidates == null)
2675 return false;
2677 if (candidates.Count == 1) {
2678 unfixed_types[i] = null;
2679 Type t = ((BoundInfo) candidates[0]).Type;
2680 if (t == TypeManager.null_type)
2681 return false;
2683 fixed_types [i] = t;
2684 return true;
2688 // Determines a unique type from which there is
2689 // a standard implicit conversion to all the other
2690 // candidate types.
2692 Type best_candidate = null;
2693 int cii;
2694 int candidates_count = candidates.Count;
2695 for (int ci = 0; ci < candidates_count; ++ci) {
2696 BoundInfo bound = (BoundInfo)candidates [ci];
2697 for (cii = 0; cii < candidates_count; ++cii) {
2698 if (cii == ci)
2699 continue;
2701 BoundInfo cbound = (BoundInfo) candidates[cii];
2703 // Same type parameters with different bounds
2704 if (cbound.Type == bound.Type) {
2705 if (bound.Kind != BoundKind.Exact)
2706 bound = cbound;
2708 continue;
2711 if (bound.Kind == BoundKind.Exact || cbound.Kind == BoundKind.Exact) {
2712 if (cbound.Kind != BoundKind.Exact) {
2713 if (!Convert.ImplicitConversionExists (ec, new TypeExpression (cbound.Type, Location.Null), bound.Type)) {
2714 break;
2717 continue;
2720 if (bound.Kind != BoundKind.Exact) {
2721 if (!Convert.ImplicitConversionExists (ec, new TypeExpression (bound.Type, Location.Null), cbound.Type)) {
2722 break;
2725 bound = cbound;
2726 continue;
2729 break;
2732 if (bound.Kind == BoundKind.Lower) {
2733 if (!Convert.ImplicitConversionExists (ec, new TypeExpression (cbound.Type, Location.Null), bound.Type)) {
2734 break;
2736 } else {
2737 if (!Convert.ImplicitConversionExists (ec, new TypeExpression (bound.Type, Location.Null), cbound.Type)) {
2738 break;
2743 if (cii != candidates_count)
2744 continue;
2746 if (best_candidate != null && best_candidate != bound.Type)
2747 return false;
2749 best_candidate = bound.Type;
2752 if (best_candidate == null)
2753 return false;
2755 unfixed_types[i] = null;
2756 fixed_types[i] = best_candidate;
2757 return true;
2761 // Uses inferred types to inflate delegate type argument
2763 public Type InflateGenericArgument (Type parameter)
2765 if (parameter.IsGenericParameter) {
2767 // Inflate method generic argument (MVAR) only
2769 if (parameter.DeclaringMethod == null)
2770 return parameter;
2772 return fixed_types [parameter.GenericParameterPosition];
2775 if (parameter.IsGenericType) {
2776 Type [] parameter_targs = parameter.GetGenericArguments ();
2777 for (int ii = 0; ii < parameter_targs.Length; ++ii) {
2778 parameter_targs [ii] = InflateGenericArgument (parameter_targs [ii]);
2780 return parameter.GetGenericTypeDefinition ().MakeGenericType (parameter_targs);
2783 return parameter;
2787 // Tests whether all delegate input arguments are fixed and generic output type
2788 // requires output type inference
2790 public bool IsReturnTypeNonDependent (ResolveContext ec, MethodInfo invoke, Type returnType)
2792 if (returnType.IsGenericParameter) {
2793 if (IsFixed (returnType))
2794 return false;
2795 } else if (returnType.IsGenericType) {
2796 if (TypeManager.IsDelegateType (returnType)) {
2797 invoke = Delegate.GetInvokeMethod (ec.Compiler, returnType, returnType);
2798 return IsReturnTypeNonDependent (ec, invoke, invoke.ReturnType);
2801 Type[] g_args = returnType.GetGenericArguments ();
2803 // At least one unfixed return type has to exist
2804 if (AllTypesAreFixed (g_args))
2805 return false;
2806 } else {
2807 return false;
2810 // All generic input arguments have to be fixed
2811 AParametersCollection d_parameters = TypeManager.GetParameterData (invoke);
2812 return AllTypesAreFixed (d_parameters.Types);
2815 bool IsFixed (Type type)
2817 return IsUnfixed (type) == -1;
2820 int IsUnfixed (Type type)
2822 if (!type.IsGenericParameter)
2823 return -1;
2825 //return unfixed_types[type.GenericParameterPosition] != null;
2826 for (int i = 0; i < unfixed_types.Length; ++i) {
2827 if (unfixed_types [i] == type)
2828 return i;
2831 return -1;
2835 // 26.3.3.9 Lower-bound Inference
2837 public int LowerBoundInference (Type u, Type v)
2839 return LowerBoundInference (u, v, false);
2843 // Lower-bound (false) or Upper-bound (true) inference based on inversed argument
2845 int LowerBoundInference (Type u, Type v, bool inversed)
2847 // If V is one of the unfixed type arguments
2848 int pos = IsUnfixed (v);
2849 if (pos != -1) {
2850 AddToBounds (new BoundInfo (u, inversed ? BoundKind.Upper : BoundKind.Lower), pos);
2851 return 1;
2854 // If U is an array type
2855 if (u.IsArray) {
2856 int u_dim = u.GetArrayRank ();
2857 Type v_i;
2858 Type u_i = TypeManager.GetElementType (u);
2860 if (v.IsArray) {
2861 if (u_dim != v.GetArrayRank ())
2862 return 0;
2864 v_i = TypeManager.GetElementType (v);
2866 if (TypeManager.IsValueType (u_i))
2867 return ExactInference (u_i, v_i);
2869 return LowerBoundInference (u_i, v_i, inversed);
2872 if (u_dim != 1)
2873 return 0;
2875 if (v.IsGenericType) {
2876 Type g_v = v.GetGenericTypeDefinition ();
2877 if ((g_v != TypeManager.generic_ilist_type) && (g_v != TypeManager.generic_icollection_type) &&
2878 (g_v != TypeManager.generic_ienumerable_type))
2879 return 0;
2881 v_i = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (v) [0]);
2882 if (TypeManager.IsValueType (u_i))
2883 return ExactInference (u_i, v_i);
2885 return LowerBoundInference (u_i, v_i);
2887 } else if (v.IsGenericType && !v.IsGenericTypeDefinition) {
2889 // if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
2890 // such that U is identical to, inherits from (directly or indirectly),
2891 // or implements (directly or indirectly) C<U1..Uk>
2893 ArrayList u_candidates = new ArrayList ();
2894 if (u.IsGenericType)
2895 u_candidates.Add (u);
2897 for (Type t = u.BaseType; t != null; t = t.BaseType) {
2898 if (t.IsGenericType && !t.IsGenericTypeDefinition)
2899 u_candidates.Add (t);
2902 // TODO: Implement GetGenericInterfaces only and remove
2903 // the if from foreach
2904 u_candidates.AddRange (TypeManager.GetInterfaces (u));
2906 Type open_v = v.GetGenericTypeDefinition ();
2907 Type [] unique_candidate_targs = null;
2908 Type [] ga_v = v.GetGenericArguments ();
2909 foreach (Type u_candidate in u_candidates) {
2910 if (!u_candidate.IsGenericType || u_candidate.IsGenericTypeDefinition)
2911 continue;
2913 if (TypeManager.DropGenericTypeArguments (u_candidate) != open_v)
2914 continue;
2917 // The unique set of types U1..Uk means that if we have an interface I<T>,
2918 // class U : I<int>, I<long> then no type inference is made when inferring
2919 // type I<T> by applying type U because T could be int or long
2921 if (unique_candidate_targs != null) {
2922 Type[] second_unique_candidate_targs = u_candidate.GetGenericArguments ();
2923 if (TypeManager.IsEqual (unique_candidate_targs, second_unique_candidate_targs)) {
2924 unique_candidate_targs = second_unique_candidate_targs;
2925 continue;
2929 // This should always cause type inference failure
2931 failed = true;
2932 return 1;
2935 unique_candidate_targs = u_candidate.GetGenericArguments ();
2938 if (unique_candidate_targs != null) {
2939 Type[] ga_open_v = open_v.GetGenericArguments ();
2940 int score = 0;
2941 for (int i = 0; i < unique_candidate_targs.Length; ++i) {
2942 Variance variance = TypeManager.GetTypeParameterVariance (ga_open_v [i]);
2944 Type u_i = unique_candidate_targs [i];
2945 if (variance == Variance.None || TypeManager.IsValueType (u_i)) {
2946 if (ExactInference (u_i, ga_v [i]) == 0)
2947 ++score;
2948 } else {
2949 bool upper_bound = (variance == Variance.Contravariant && !inversed) ||
2950 (variance == Variance.Covariant && inversed);
2952 if (LowerBoundInference (u_i, ga_v [i], upper_bound) == 0)
2953 ++score;
2956 return score;
2960 return 0;
2964 // 26.3.3.6 Output Type Inference
2966 public int OutputTypeInference (ResolveContext ec, Expression e, Type t)
2968 // If e is a lambda or anonymous method with inferred return type
2969 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
2970 if (ame != null) {
2971 Type rt = ame.InferReturnType (ec, this, t);
2972 MethodInfo invoke = Delegate.GetInvokeMethod (ec.Compiler, t, t);
2974 if (rt == null) {
2975 AParametersCollection pd = TypeManager.GetParameterData (invoke);
2976 return ame.Parameters.Count == pd.Count ? 1 : 0;
2979 Type rtype = invoke.ReturnType;
2980 #if MS_COMPATIBLE
2981 // Blablabla, because reflection does not work with dynamic types
2982 Type [] g_args = t.GetGenericArguments ();
2983 rtype = g_args [rtype.GenericParameterPosition];
2984 #endif
2985 return LowerBoundInference (rt, rtype) + 1;
2989 // if E is a method group and T is a delegate type or expression tree type
2990 // return type Tb with parameter types T1..Tk and return type Tb, and overload
2991 // resolution of E with the types T1..Tk yields a single method with return type U,
2992 // then a lower-bound inference is made from U for Tb.
2994 if (e is MethodGroupExpr) {
2995 // TODO: Or expression tree
2996 if (!TypeManager.IsDelegateType (t))
2997 return 0;
2999 MethodInfo invoke = Delegate.GetInvokeMethod (ec.Compiler, t, t);
3000 Type rtype = invoke.ReturnType;
3001 #if MS_COMPATIBLE
3002 // Blablabla, because reflection does not work with dynamic types
3003 Type [] g_args = t.GetGenericArguments ();
3004 rtype = g_args [rtype.GenericParameterPosition];
3005 #endif
3007 if (!TypeManager.IsGenericType (rtype))
3008 return 0;
3010 MethodGroupExpr mg = (MethodGroupExpr) e;
3011 Arguments args = DelegateCreation.CreateDelegateMethodArguments (TypeManager.GetParameterData (invoke), e.Location);
3012 mg = mg.OverloadResolve (ec, ref args, true, e.Location);
3013 if (mg == null)
3014 return 0;
3016 // TODO: What should happen when return type is of generic type ?
3017 throw new NotImplementedException ();
3018 // return LowerBoundInference (null, rtype) + 1;
3022 // if e is an expression with type U, then
3023 // a lower-bound inference is made from U for T
3025 return LowerBoundInference (e.Type, t) * 2;
3028 void RemoveDependentTypes (ArrayList types, Type returnType)
3030 int idx = IsUnfixed (returnType);
3031 if (idx >= 0) {
3032 types [idx] = null;
3033 return;
3036 if (returnType.IsGenericType) {
3037 foreach (Type t in returnType.GetGenericArguments ()) {
3038 RemoveDependentTypes (types, t);
3043 public bool UnfixedVariableExists {
3044 get {
3045 if (unfixed_types == null)
3046 return false;
3048 foreach (Type ut in unfixed_types)
3049 if (ut != null)
3050 return true;
3051 return false;