* Vbc.cs (AddResponseFileCommands): Escape DefineConstants as it can
[mcs.git] / mcs / generic.cs
blob850a1709d04ce35c0de98f5b705ee2f903995924
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 if ((constraints.Length > 0) && !constraints[0].IsInterface) {
150 class_constraint = constraints[0];
151 iface_constraints = new Type[constraints.Length - 1];
152 Array.Copy (constraints, 1, iface_constraints, 0, constraints.Length - 1);
153 } else
154 iface_constraints = constraints;
156 if (HasValueTypeConstraint)
157 base_type = TypeManager.value_type;
158 else if (class_constraint != null)
159 base_type = class_constraint;
160 else
161 base_type = TypeManager.object_type;
164 public override string TypeParameter
166 get { return name; }
169 public override GenericParameterAttributes Attributes
171 get { return attrs; }
174 public override Type ClassConstraint
176 get { return class_constraint; }
179 public override Type EffectiveBaseClass
181 get { return base_type; }
184 public override Type[] InterfaceConstraints
186 get { return iface_constraints; }
190 public enum Variance
192 None,
193 Covariant,
194 Contravariant
197 public enum SpecialConstraint
199 Constructor,
200 ReferenceType,
201 ValueType
204 /// <summary>
205 /// Tracks the constraints for a type parameter from a generic type definition.
206 /// </summary>
207 public class Constraints : GenericConstraints {
208 string name;
209 ArrayList constraints;
210 Location loc;
213 // name is the identifier, constraints is an arraylist of
214 // Expressions (with types) or `true' for the constructor constraint.
216 public Constraints (string name, ArrayList constraints,
217 Location loc)
219 this.name = name;
220 this.constraints = constraints;
221 this.loc = loc;
224 public override string TypeParameter {
225 get {
226 return name;
230 public Constraints Clone ()
232 return new Constraints (name, constraints, loc);
235 GenericParameterAttributes attrs;
236 TypeExpr class_constraint;
237 ArrayList iface_constraints;
238 ArrayList type_param_constraints;
239 int num_constraints;
240 Type class_constraint_type;
241 Type[] iface_constraint_types;
242 Type effective_base_type;
243 bool resolved;
244 bool resolved_types;
246 /// <summary>
247 /// Resolve the constraints - but only resolve things into Expression's, not
248 /// into actual types.
249 /// </summary>
250 public bool Resolve (IResolveContext ec)
252 if (resolved)
253 return true;
255 iface_constraints = new ArrayList (2); // TODO: Too expensive allocation
256 type_param_constraints = new ArrayList ();
258 foreach (object obj in constraints) {
259 if (HasConstructorConstraint) {
260 Report.Error (401, loc,
261 "The new() constraint must be the last constraint specified");
262 return false;
265 if (obj is SpecialConstraint) {
266 SpecialConstraint sc = (SpecialConstraint) obj;
268 if (sc == SpecialConstraint.Constructor) {
269 if (!HasValueTypeConstraint) {
270 attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
271 continue;
274 Report.Error (451, loc, "The `new()' constraint " +
275 "cannot be used with the `struct' constraint");
276 return false;
279 if ((num_constraints > 0) || HasReferenceTypeConstraint || HasValueTypeConstraint) {
280 Report.Error (449, loc, "The `class' or `struct' " +
281 "constraint must be the first constraint specified");
282 return false;
285 if (sc == SpecialConstraint.ReferenceType)
286 attrs |= GenericParameterAttributes.ReferenceTypeConstraint;
287 else
288 attrs |= GenericParameterAttributes.NotNullableValueTypeConstraint;
289 continue;
292 int errors = Report.Errors;
293 FullNamedExpression fn = ((Expression) obj).ResolveAsTypeStep (ec, false);
295 if (fn == null) {
296 if (errors != Report.Errors)
297 return false;
299 NamespaceEntry.Error_NamespaceNotFound (loc, ((Expression)obj).GetSignatureForError ());
300 return false;
303 TypeExpr expr;
304 GenericTypeExpr cexpr = fn as GenericTypeExpr;
305 if (cexpr != null) {
306 expr = cexpr.ResolveAsBaseTerminal (ec, false);
307 } else
308 expr = ((Expression) obj).ResolveAsTypeTerminal (ec, false);
310 if ((expr == null) || (expr.Type == null))
311 return false;
313 if (!ec.GenericDeclContainer.IsAccessibleAs (fn.Type)) {
314 Report.SymbolRelatedToPreviousError (fn.Type);
315 Report.Error (703, loc,
316 "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
317 fn.GetSignatureForError (), ec.GenericDeclContainer.GetSignatureForError ());
318 return false;
321 TypeParameterExpr texpr = expr as TypeParameterExpr;
322 if (texpr != null)
323 type_param_constraints.Add (expr);
324 else if (expr.IsInterface)
325 iface_constraints.Add (expr);
326 else if (class_constraint != null || iface_constraints.Count != 0) {
327 Report.Error (406, loc,
328 "The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
329 expr.GetSignatureForError ());
330 return false;
331 } else if (HasReferenceTypeConstraint || HasValueTypeConstraint) {
332 Report.Error (450, loc, "`{0}': cannot specify both " +
333 "a constraint class and the `class' " +
334 "or `struct' constraint", expr.GetSignatureForError ());
335 return false;
336 } else
337 class_constraint = expr;
339 num_constraints++;
342 ArrayList list = new ArrayList ();
343 foreach (TypeExpr iface_constraint in iface_constraints) {
344 foreach (Type type in list) {
345 if (!type.Equals (iface_constraint.Type))
346 continue;
348 Report.Error (405, loc,
349 "Duplicate constraint `{0}' for type " +
350 "parameter `{1}'.", iface_constraint.GetSignatureForError (),
351 name);
352 return false;
355 list.Add (iface_constraint.Type);
358 foreach (TypeParameterExpr expr in type_param_constraints) {
359 foreach (Type type in list) {
360 if (!type.Equals (expr.Type))
361 continue;
363 Report.Error (405, loc,
364 "Duplicate constraint `{0}' for type " +
365 "parameter `{1}'.", expr.GetSignatureForError (), name);
366 return false;
369 list.Add (expr.Type);
372 iface_constraint_types = new Type [list.Count];
373 list.CopyTo (iface_constraint_types, 0);
375 if (class_constraint != null) {
376 class_constraint_type = class_constraint.Type;
377 if (class_constraint_type == null)
378 return false;
380 if (class_constraint_type.IsSealed) {
381 if (class_constraint_type.IsAbstract)
383 Report.Error (717, loc, "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
384 TypeManager.CSharpName (class_constraint_type));
386 else
388 Report.Error (701, loc, "`{0}' is not a valid constraint. A constraint must be an interface, " +
389 "a non-sealed class or a type parameter", TypeManager.CSharpName(class_constraint_type));
391 return false;
394 if ((class_constraint_type == TypeManager.array_type) ||
395 (class_constraint_type == TypeManager.delegate_type) ||
396 (class_constraint_type == TypeManager.enum_type) ||
397 (class_constraint_type == TypeManager.value_type) ||
398 (class_constraint_type == TypeManager.object_type) ||
399 class_constraint_type == TypeManager.multicast_delegate_type) {
400 Report.Error (702, loc,
401 "A constraint cannot be special class `{0}'",
402 TypeManager.CSharpName (class_constraint_type));
403 return false;
407 if (class_constraint_type != null)
408 effective_base_type = class_constraint_type;
409 else if (HasValueTypeConstraint)
410 effective_base_type = TypeManager.value_type;
411 else
412 effective_base_type = TypeManager.object_type;
414 if ((attrs & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0)
415 attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
417 resolved = true;
418 return true;
421 bool CheckTypeParameterConstraints (TypeParameter tparam, ref TypeExpr prevConstraint, ArrayList seen)
423 seen.Add (tparam);
425 Constraints constraints = tparam.Constraints;
426 if (constraints == null)
427 return true;
429 if (constraints.HasValueTypeConstraint) {
430 Report.Error (456, loc,
431 "Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
432 tparam.Name, name);
433 return false;
437 // Checks whether there are no conflicts between type parameter constraints
439 // class Foo<T, U>
440 // where T : A
441 // where U : A, B // A and B are not convertible
443 if (constraints.HasClassConstraint) {
444 if (prevConstraint != null) {
445 Type t2 = constraints.ClassConstraint;
446 TypeExpr e2 = constraints.class_constraint;
448 if (!Convert.ImplicitReferenceConversionExists (prevConstraint, t2) &&
449 !Convert.ImplicitReferenceConversionExists (e2, prevConstraint.Type)) {
450 Report.Error (455, loc,
451 "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
452 name, TypeManager.CSharpName (prevConstraint.Type), TypeManager.CSharpName (t2));
453 return false;
457 prevConstraint = constraints.class_constraint;
460 if (constraints.type_param_constraints == null)
461 return true;
463 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
464 if (seen.Contains (expr.TypeParameter)) {
465 Report.Error (454, loc, "Circular constraint " +
466 "dependency involving `{0}' and `{1}'",
467 tparam.Name, expr.GetSignatureForError ());
468 return false;
471 if (!CheckTypeParameterConstraints (expr.TypeParameter, ref prevConstraint, seen))
472 return false;
475 return true;
478 /// <summary>
479 /// Resolve the constraints into actual types.
480 /// </summary>
481 public bool ResolveTypes (IResolveContext ec)
483 if (resolved_types)
484 return true;
486 resolved_types = true;
488 foreach (object obj in constraints) {
489 GenericTypeExpr cexpr = obj as GenericTypeExpr;
490 if (cexpr == null)
491 continue;
493 if (!cexpr.CheckConstraints (ec))
494 return false;
497 if (type_param_constraints.Count != 0) {
498 ArrayList seen = new ArrayList ();
499 TypeExpr prev_constraint = class_constraint;
500 foreach (TypeParameterExpr expr in type_param_constraints) {
501 if (!CheckTypeParameterConstraints (expr.TypeParameter, ref prev_constraint, seen))
502 return false;
503 seen.Clear ();
507 for (int i = 0; i < iface_constraints.Count; ++i) {
508 TypeExpr iface_constraint = (TypeExpr) iface_constraints [i];
509 iface_constraint = iface_constraint.ResolveAsTypeTerminal (ec, false);
510 if (iface_constraint == null)
511 return false;
512 iface_constraints [i] = iface_constraint;
515 if (class_constraint != null) {
516 class_constraint = class_constraint.ResolveAsTypeTerminal (ec, false);
517 if (class_constraint == null)
518 return false;
521 return true;
524 public override GenericParameterAttributes Attributes {
525 get { return attrs; }
528 public override bool HasClassConstraint {
529 get { return class_constraint != null; }
532 public override Type ClassConstraint {
533 get { return class_constraint_type; }
536 public override Type[] InterfaceConstraints {
537 get { return iface_constraint_types; }
540 public override Type EffectiveBaseClass {
541 get { return effective_base_type; }
544 public bool IsSubclassOf (Type t)
546 if ((class_constraint_type != null) &&
547 class_constraint_type.IsSubclassOf (t))
548 return true;
550 if (iface_constraint_types == null)
551 return false;
553 foreach (Type iface in iface_constraint_types) {
554 if (TypeManager.IsSubclassOf (iface, t))
555 return true;
558 return false;
561 public Location Location {
562 get {
563 return loc;
567 /// <summary>
568 /// This is used when we're implementing a generic interface method.
569 /// Each method type parameter in implementing method must have the same
570 /// constraints than the corresponding type parameter in the interface
571 /// method. To do that, we're called on each of the implementing method's
572 /// type parameters.
573 /// </summary>
574 public bool AreEqual (GenericConstraints gc)
576 if (gc.Attributes != attrs)
577 return false;
579 if (HasClassConstraint != gc.HasClassConstraint)
580 return false;
581 if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
582 return false;
584 int gc_icount = gc.InterfaceConstraints != null ?
585 gc.InterfaceConstraints.Length : 0;
586 int icount = InterfaceConstraints != null ?
587 InterfaceConstraints.Length : 0;
589 if (gc_icount != icount)
590 return false;
592 for (int i = 0; i < gc.InterfaceConstraints.Length; ++i) {
593 Type iface = gc.InterfaceConstraints [i];
594 if (iface.IsGenericType)
595 iface = iface.GetGenericTypeDefinition ();
597 bool ok = false;
598 for (int ii = 0; i < InterfaceConstraints.Length; ++ii) {
599 Type check = InterfaceConstraints [ii];
600 if (check.IsGenericType)
601 check = check.GetGenericTypeDefinition ();
603 if (TypeManager.IsEqual (iface, check)) {
604 ok = true;
605 break;
609 if (!ok)
610 return false;
613 return true;
616 public void VerifyClsCompliance ()
618 if (class_constraint_type != null && !AttributeTester.IsClsCompliant (class_constraint_type))
619 Warning_ConstrainIsNotClsCompliant (class_constraint_type, class_constraint.Location);
621 if (iface_constraint_types != null) {
622 for (int i = 0; i < iface_constraint_types.Length; ++i) {
623 if (!AttributeTester.IsClsCompliant (iface_constraint_types [i]))
624 Warning_ConstrainIsNotClsCompliant (iface_constraint_types [i],
625 ((TypeExpr)iface_constraints [i]).Location);
630 void Warning_ConstrainIsNotClsCompliant (Type t, Location loc)
632 Report.SymbolRelatedToPreviousError (t);
633 Report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
634 TypeManager.CSharpName (t));
638 /// <summary>
639 /// A type parameter from a generic type definition.
640 /// </summary>
641 public class TypeParameter : MemberCore, IMemberContainer
643 static readonly string[] attribute_target = new string [] { "type parameter" };
645 DeclSpace decl;
646 GenericConstraints gc;
647 Constraints constraints;
648 GenericTypeParameterBuilder type;
649 MemberCache member_cache;
650 Variance variance;
652 public TypeParameter (DeclSpace parent, DeclSpace decl, string name,
653 Constraints constraints, Attributes attrs, Variance variance, Location loc)
654 : base (parent, new MemberName (name, loc), attrs)
656 this.decl = decl;
657 this.constraints = constraints;
658 this.variance = variance;
659 if (variance != Variance.None && !(decl is Interface) && !(decl is Delegate)) {
660 Report.Error (-36, loc, "Generic variance can only be used with interfaces and delegates");
664 public GenericConstraints GenericConstraints {
665 get { return gc != null ? gc : constraints; }
668 public Constraints Constraints {
669 get { return constraints; }
672 public DeclSpace DeclSpace {
673 get { return decl; }
676 public Variance Variance {
677 get { return variance; }
680 public Type Type {
681 get { return type; }
684 /// <summary>
685 /// This is the first method which is called during the resolving
686 /// process; we're called immediately after creating the type parameters
687 /// with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
688 /// MethodBuilder).
690 /// We're either called from TypeContainer.DefineType() or from
691 /// GenericMethod.Define() (called from Method.Define()).
692 /// </summary>
693 public void Define (GenericTypeParameterBuilder type)
695 if (this.type != null)
696 throw new InvalidOperationException ();
698 this.type = type;
699 TypeManager.AddTypeParameter (type, this);
702 /// <summary>
703 /// This is the second method which is called during the resolving
704 /// process - in case of class type parameters, we're called from
705 /// TypeContainer.ResolveType() - after it resolved the class'es
706 /// base class and interfaces. For method type parameters, we're
707 /// called immediately after Define().
709 /// We're just resolving the constraints into expressions here, we
710 /// don't resolve them into actual types.
712 /// Note that in the special case of partial generic classes, we may be
713 /// called _before_ Define() and we may also be called multiple types.
714 /// </summary>
715 public bool Resolve (DeclSpace ds)
717 if (constraints != null) {
718 if (!constraints.Resolve (ds)) {
719 constraints = null;
720 return false;
724 return true;
727 /// <summary>
728 /// This is the third method which is called during the resolving
729 /// process. We're called immediately after calling DefineConstraints()
730 /// on all of the current class'es type parameters.
732 /// Our job is to resolve the constraints to actual types.
734 /// Note that we may have circular dependencies on type parameters - this
735 /// is why Resolve() and ResolveType() are separate.
736 /// </summary>
737 public bool ResolveType (IResolveContext ec)
739 if (constraints != null) {
740 if (!constraints.ResolveTypes (ec)) {
741 constraints = null;
742 return false;
746 return true;
749 /// <summary>
750 /// This is the fourth and last method which is called during the resolving
751 /// process. We're called after everything is fully resolved and actually
752 /// register the constraints with SRE and the TypeManager.
753 /// </summary>
754 public bool DefineType (IResolveContext ec)
756 return DefineType (ec, null, null, false);
759 /// <summary>
760 /// This is the fith and last method which is called during the resolving
761 /// process. We're called after everything is fully resolved and actually
762 /// register the constraints with SRE and the TypeManager.
764 /// The `builder', `implementing' and `is_override' arguments are only
765 /// applicable to method type parameters.
766 /// </summary>
767 public bool DefineType (IResolveContext ec, MethodBuilder builder,
768 MethodInfo implementing, bool is_override)
770 if (!ResolveType (ec))
771 return false;
773 if (implementing != null) {
774 if (is_override && (constraints != null)) {
775 Report.Error (460, Location,
776 "`{0}': Cannot specify constraints for overrides or explicit interface implementation methods",
777 TypeManager.CSharpSignature (builder));
778 return false;
781 MethodBase mb = TypeManager.DropGenericMethodArguments (implementing);
783 int pos = type.GenericParameterPosition;
784 Type mparam = mb.GetGenericArguments () [pos];
785 GenericConstraints temp_gc = ReflectionConstraints.GetConstraints (mparam);
787 if (temp_gc != null)
788 gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
789 else if (constraints != null)
790 gc = new InflatedConstraints (constraints, implementing.DeclaringType);
792 bool ok = true;
793 if (constraints != null) {
794 if (temp_gc == null)
795 ok = false;
796 else if (!constraints.AreEqual (gc))
797 ok = false;
798 } else {
799 if (!is_override && (temp_gc != null))
800 ok = false;
803 if (!ok) {
804 Report.SymbolRelatedToPreviousError (implementing);
806 Report.Error (
807 425, Location, "The constraints for type " +
808 "parameter `{0}' of method `{1}' must match " +
809 "the constraints for type parameter `{2}' " +
810 "of interface method `{3}'. Consider using " +
811 "an explicit interface implementation instead",
812 Name, TypeManager.CSharpSignature (builder),
813 TypeManager.CSharpName (mparam), TypeManager.CSharpSignature (mb));
814 return false;
816 } else if (DeclSpace is CompilerGeneratedClass) {
817 TypeParameter[] tparams = DeclSpace.TypeParameters;
818 Type[] types = new Type [tparams.Length];
819 for (int i = 0; i < tparams.Length; i++)
820 types [i] = tparams [i].Type;
822 if (constraints != null)
823 gc = new InflatedConstraints (constraints, types);
824 } else {
825 gc = (GenericConstraints) constraints;
828 SetConstraints (type);
829 return true;
832 public void SetConstraints (GenericTypeParameterBuilder type)
834 GenericParameterAttributes attr = GenericParameterAttributes.None;
835 if (variance == Variance.Contravariant)
836 attr |= GenericParameterAttributes.Contravariant;
837 else if (variance == Variance.Covariant)
838 attr |= GenericParameterAttributes.Covariant;
840 if (gc != null) {
841 if (gc.HasClassConstraint || gc.HasValueTypeConstraint)
842 type.SetBaseTypeConstraint (gc.EffectiveBaseClass);
844 attr |= gc.Attributes;
845 type.SetInterfaceConstraints (gc.InterfaceConstraints);
846 TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
849 type.SetGenericParameterAttributes (attr);
852 /// <summary>
853 /// This is called for each part of a partial generic type definition.
855 /// If `new_constraints' is not null and we don't already have constraints,
856 /// they become our constraints. If we already have constraints, we must
857 /// check that they're the same.
858 /// con
859 /// </summary>
860 public bool UpdateConstraints (IResolveContext ec, Constraints new_constraints)
862 if (type == null)
863 throw new InvalidOperationException ();
865 if (new_constraints == null)
866 return true;
868 if (!new_constraints.Resolve (ec))
869 return false;
870 if (!new_constraints.ResolveTypes (ec))
871 return false;
873 if (constraints != null)
874 return constraints.AreEqual (new_constraints);
876 constraints = new_constraints;
877 return true;
880 public override void Emit ()
882 if (OptAttributes != null)
883 OptAttributes.Emit ();
885 base.Emit ();
888 public override string DocCommentHeader {
889 get {
890 throw new InvalidOperationException (
891 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
896 // MemberContainer
899 public override bool Define ()
901 return true;
904 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
906 type.SetCustomAttribute (cb);
909 public override AttributeTargets AttributeTargets {
910 get {
911 return AttributeTargets.GenericParameter;
915 public override string[] ValidAttributeTargets {
916 get {
917 return attribute_target;
922 // IMemberContainer
925 string IMemberContainer.Name {
926 get { return Name; }
929 MemberCache IMemberContainer.BaseCache {
930 get {
931 if (gc == null)
932 return null;
934 if (gc.EffectiveBaseClass.BaseType == null)
935 return null;
937 return TypeManager.LookupMemberCache (gc.EffectiveBaseClass.BaseType);
941 bool IMemberContainer.IsInterface {
942 get { return false; }
945 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
947 throw new NotSupportedException ();
950 public MemberCache MemberCache {
951 get {
952 if (member_cache != null)
953 return member_cache;
955 if (gc == null)
956 return null;
958 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
959 member_cache = new MemberCache (this, gc.EffectiveBaseClass, ifaces);
961 return member_cache;
965 public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
966 MemberFilter filter, object criteria)
968 if (gc == null)
969 return MemberList.Empty;
971 ArrayList members = new ArrayList ();
973 if (gc.HasClassConstraint) {
974 MemberList list = TypeManager.FindMembers (
975 gc.ClassConstraint, mt, bf, filter, criteria);
977 members.AddRange (list);
980 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
981 foreach (Type t in ifaces) {
982 MemberList list = TypeManager.FindMembers (
983 t, mt, bf, filter, criteria);
985 members.AddRange (list);
988 return new MemberList (members);
991 public bool IsSubclassOf (Type t)
993 if (type.Equals (t))
994 return true;
996 if (constraints != null)
997 return constraints.IsSubclassOf (t);
999 return false;
1002 public void InflateConstraints (Type declaring)
1004 if (constraints != null)
1005 gc = new InflatedConstraints (constraints, declaring);
1008 public override bool IsClsComplianceRequired ()
1010 return false;
1013 protected class InflatedConstraints : GenericConstraints
1015 GenericConstraints gc;
1016 Type base_type;
1017 Type class_constraint;
1018 Type[] iface_constraints;
1019 Type[] dargs;
1021 public InflatedConstraints (GenericConstraints gc, Type declaring)
1022 : this (gc, TypeManager.GetTypeArguments (declaring))
1025 public InflatedConstraints (GenericConstraints gc, Type[] dargs)
1027 this.gc = gc;
1028 this.dargs = dargs;
1030 ArrayList list = new ArrayList ();
1031 if (gc.HasClassConstraint)
1032 list.Add (inflate (gc.ClassConstraint));
1033 foreach (Type iface in gc.InterfaceConstraints)
1034 list.Add (inflate (iface));
1036 bool has_class_constr = false;
1037 if (list.Count > 0) {
1038 Type first = (Type) list [0];
1039 has_class_constr = !first.IsGenericParameter && !first.IsInterface;
1042 if ((list.Count > 0) && has_class_constr) {
1043 class_constraint = (Type) list [0];
1044 iface_constraints = new Type [list.Count - 1];
1045 list.CopyTo (1, iface_constraints, 0, list.Count - 1);
1046 } else {
1047 iface_constraints = new Type [list.Count];
1048 list.CopyTo (iface_constraints, 0);
1051 if (HasValueTypeConstraint)
1052 base_type = TypeManager.value_type;
1053 else if (class_constraint != null)
1054 base_type = class_constraint;
1055 else
1056 base_type = TypeManager.object_type;
1059 Type inflate (Type t)
1061 if (t == null)
1062 return null;
1063 if (t.IsGenericParameter)
1064 return t.GenericParameterPosition < dargs.Length ? dargs [t.GenericParameterPosition] : t;
1065 if (t.IsGenericType) {
1066 Type[] args = t.GetGenericArguments ();
1067 Type[] inflated = new Type [args.Length];
1069 for (int i = 0; i < args.Length; i++)
1070 inflated [i] = inflate (args [i]);
1072 t = t.GetGenericTypeDefinition ();
1073 t = t.MakeGenericType (inflated);
1076 return t;
1079 public override string TypeParameter {
1080 get { return gc.TypeParameter; }
1083 public override GenericParameterAttributes Attributes {
1084 get { return gc.Attributes; }
1087 public override Type ClassConstraint {
1088 get { return class_constraint; }
1091 public override Type EffectiveBaseClass {
1092 get { return base_type; }
1095 public override Type[] InterfaceConstraints {
1096 get { return iface_constraints; }
1101 /// <summary>
1102 /// A TypeExpr which already resolved to a type parameter.
1103 /// </summary>
1104 public class TypeParameterExpr : TypeExpr {
1105 TypeParameter type_parameter;
1107 public TypeParameter TypeParameter {
1108 get {
1109 return type_parameter;
1113 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1115 this.type_parameter = type_parameter;
1116 this.loc = loc;
1119 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1121 throw new NotSupportedException ();
1124 public override FullNamedExpression ResolveAsTypeStep (IResolveContext ec, bool silent)
1126 type = type_parameter.Type;
1127 eclass = ExprClass.TypeParameter;
1128 return this;
1131 public override bool IsInterface {
1132 get { return false; }
1135 public override bool CheckAccessLevel (DeclSpace ds)
1137 return true;
1142 // Tracks the type arguments when instantiating a generic type. It's used
1143 // by both type arguments and type parameters
1145 public class TypeArguments {
1146 ArrayList args;
1147 Type[] atypes;
1149 public TypeArguments ()
1151 args = new ArrayList ();
1154 public TypeArguments (params FullNamedExpression[] types)
1156 this.args = new ArrayList (types);
1159 public void Add (FullNamedExpression type)
1161 args.Add (type);
1164 public void Add (TypeArguments new_args)
1166 args.AddRange (new_args.args);
1169 // TODO: Should be deleted
1170 public TypeParameterName[] GetDeclarations ()
1172 return (TypeParameterName[]) args.ToArray (typeof (TypeParameterName));
1175 /// <summary>
1176 /// We may only be used after Resolve() is called and return the fully
1177 /// resolved types.
1178 /// </summary>
1179 public Type[] Arguments {
1180 get {
1181 return atypes;
1185 public int Count {
1186 get {
1187 return args.Count;
1191 public string GetSignatureForError()
1193 StringBuilder sb = new StringBuilder();
1194 for (int i = 0; i < Count; ++i)
1196 Expression expr = (Expression)args [i];
1197 sb.Append(expr.GetSignatureForError());
1198 if (i + 1 < Count)
1199 sb.Append(',');
1201 return sb.ToString();
1204 /// <summary>
1205 /// Resolve the type arguments.
1206 /// </summary>
1207 public bool Resolve (IResolveContext ec)
1209 if (atypes != null)
1210 return atypes.Length != 0;
1212 int count = args.Count;
1213 bool ok = true;
1215 atypes = new Type [count];
1217 for (int i = 0; i < count; i++){
1218 TypeExpr te = ((FullNamedExpression) args[i]).ResolveAsTypeTerminal (ec, false);
1219 if (te == null) {
1220 ok = false;
1221 continue;
1224 atypes[i] = te.Type;
1226 if (te.Type.IsSealed && te.Type.IsAbstract) {
1227 Report.Error (718, te.Location, "`{0}': static classes cannot be used as generic arguments",
1228 te.GetSignatureForError ());
1229 ok = false;
1232 if (te.Type.IsPointer || TypeManager.IsSpecialType (te.Type)) {
1233 Report.Error (306, te.Location,
1234 "The type `{0}' may not be used as a type argument",
1235 te.GetSignatureForError ());
1236 ok = false;
1240 if (!ok)
1241 atypes = Type.EmptyTypes;
1243 return ok;
1246 public TypeArguments Clone ()
1248 TypeArguments copy = new TypeArguments ();
1249 foreach (Expression ta in args)
1250 copy.args.Add (ta);
1252 return copy;
1256 public class TypeParameterName : SimpleName
1258 Attributes attributes;
1259 Variance variance;
1261 public TypeParameterName (string name, Attributes attrs, Location loc)
1262 : this (name, attrs, Variance.None, loc)
1266 public TypeParameterName (string name, Attributes attrs, Variance variance, Location loc)
1267 : base (name, loc)
1269 attributes = attrs;
1270 this.variance = variance;
1273 public Attributes OptAttributes {
1274 get {
1275 return attributes;
1279 public Variance Variance {
1280 get {
1281 return variance;
1286 /// <summary>
1287 /// A reference expression to generic type
1288 /// </summary>
1289 class GenericTypeExpr : TypeExpr
1291 TypeArguments args;
1292 Type[] gen_params; // TODO: Waiting for constrains check cleanup
1293 Type open_type;
1296 // Should be carefully used only with defined generic containers. Type parameters
1297 // can be used as type arguments in this case.
1299 // TODO: This could be GenericTypeExpr specialization
1301 public GenericTypeExpr (DeclSpace gType, Location l)
1303 open_type = gType.TypeBuilder.GetGenericTypeDefinition ();
1305 args = new TypeArguments ();
1306 foreach (TypeParameter type_param in gType.TypeParameters)
1307 args.Add (new TypeParameterExpr (type_param, l));
1309 this.loc = l;
1312 /// <summary>
1313 /// Instantiate the generic type `t' with the type arguments `args'.
1314 /// Use this constructor if you already know the fully resolved
1315 /// generic type.
1316 /// </summary>
1317 public GenericTypeExpr (Type t, TypeArguments args, Location l)
1319 open_type = t.GetGenericTypeDefinition ();
1321 loc = l;
1322 this.args = args;
1325 public TypeArguments TypeArguments {
1326 get { return args; }
1329 public override string GetSignatureForError ()
1331 return TypeManager.CSharpName (type);
1334 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1336 if (eclass != ExprClass.Invalid)
1337 return this;
1339 eclass = ExprClass.Type;
1341 if (!args.Resolve (ec))
1342 return null;
1344 gen_params = open_type.GetGenericArguments ();
1345 Type[] atypes = args.Arguments;
1347 if (atypes.Length != gen_params.Length) {
1348 Namespace.Error_InvalidNumberOfTypeArguments (open_type, loc);
1349 return null;
1353 // Now bind the parameters
1355 type = open_type.MakeGenericType (atypes);
1356 return this;
1359 /// <summary>
1360 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1361 /// after fully resolving the constructed type.
1362 /// </summary>
1363 public bool CheckConstraints (IResolveContext ec)
1365 return ConstraintChecker.CheckConstraints (ec, open_type, gen_params, args.Arguments, loc);
1368 static bool IsVariant (Type type)
1370 return (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) != 0;
1373 static bool IsCovariant (Type type)
1375 return (type.GenericParameterAttributes & GenericParameterAttributes.Covariant) != 0;
1378 static bool IsContravariant (Type type)
1380 return (type.GenericParameterAttributes & GenericParameterAttributes.Contravariant) != 0;
1383 public bool VerifyVariantTypeParameters ()
1385 for (int i = 0; i < args.Count; i++) {
1386 Type argument = args.Arguments[i];
1387 if (argument.IsGenericParameter && IsVariant (argument)) {
1388 if (IsContravariant (argument) && !IsContravariant (gen_params[i])) {
1389 Report.Error (-34, loc, "Contravariant type parameters can only be used " +
1390 "as type arguments in contravariant positions");
1391 return false;
1393 else if (IsCovariant (argument) && !IsCovariant (gen_params[i])) {
1394 Report.Error (-35, loc, "Covariant type parameters can only be used " +
1395 "as type arguments in covariant positions");
1396 return false;
1400 return true;
1404 public override bool CheckAccessLevel (DeclSpace ds)
1406 return ds.CheckAccessLevel (open_type);
1409 public override bool IsClass {
1410 get { return open_type.IsClass; }
1413 public override bool IsValueType {
1414 get { return TypeManager.IsStruct (open_type); }
1417 public override bool IsInterface {
1418 get { return open_type.IsInterface; }
1421 public override bool IsSealed {
1422 get { return open_type.IsSealed; }
1425 public override bool Equals (object obj)
1427 GenericTypeExpr cobj = obj as GenericTypeExpr;
1428 if (cobj == null)
1429 return false;
1431 if ((type == null) || (cobj.type == null))
1432 return false;
1434 return type == cobj.type;
1437 public override int GetHashCode ()
1439 return base.GetHashCode ();
1443 public abstract class ConstraintChecker
1445 protected readonly Type[] gen_params;
1446 protected readonly Type[] atypes;
1447 protected readonly Location loc;
1449 protected ConstraintChecker (Type[] gen_params, Type[] atypes, Location loc)
1451 this.gen_params = gen_params;
1452 this.atypes = atypes;
1453 this.loc = loc;
1456 /// <summary>
1457 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1458 /// after fully resolving the constructed type.
1459 /// </summary>
1460 public bool CheckConstraints (IResolveContext ec)
1462 for (int i = 0; i < gen_params.Length; i++) {
1463 if (!CheckConstraints (ec, i))
1464 return false;
1467 return true;
1470 protected bool CheckConstraints (IResolveContext ec, int index)
1472 Type atype = atypes [index];
1473 Type ptype = gen_params [index];
1475 if (atype == ptype)
1476 return true;
1478 Expression aexpr = new EmptyExpression (atype);
1480 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1481 if (gc == null)
1482 return true;
1484 bool is_class, is_struct;
1485 if (atype.IsGenericParameter) {
1486 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1487 if (agc != null) {
1488 if (agc is Constraints)
1489 ((Constraints) agc).Resolve (ec);
1490 is_class = agc.IsReferenceType;
1491 is_struct = agc.IsValueType;
1492 } else {
1493 is_class = is_struct = false;
1495 } else {
1496 #if MS_COMPATIBLE
1497 is_class = false;
1498 if (!atype.IsGenericType)
1499 #endif
1500 is_class = atype.IsClass || atype.IsInterface;
1501 is_struct = TypeManager.IsValueType (atype) && !TypeManager.IsNullableType (atype);
1505 // First, check the `class' and `struct' constraints.
1507 if (gc.HasReferenceTypeConstraint && !is_class) {
1508 Report.Error (452, loc, "The type `{0}' must be " +
1509 "a reference type in order to use it " +
1510 "as type parameter `{1}' in the " +
1511 "generic type or method `{2}'.",
1512 TypeManager.CSharpName (atype),
1513 TypeManager.CSharpName (ptype),
1514 GetSignatureForError ());
1515 return false;
1516 } else if (gc.HasValueTypeConstraint && !is_struct) {
1517 Report.Error (453, loc, "The type `{0}' must be a " +
1518 "non-nullable value type in order to use it " +
1519 "as type parameter `{1}' in the " +
1520 "generic type or method `{2}'.",
1521 TypeManager.CSharpName (atype),
1522 TypeManager.CSharpName (ptype),
1523 GetSignatureForError ());
1524 return false;
1528 // The class constraint comes next.
1530 if (gc.HasClassConstraint) {
1531 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint))
1532 return false;
1536 // Now, check the interface constraints.
1538 if (gc.InterfaceConstraints != null) {
1539 foreach (Type it in gc.InterfaceConstraints) {
1540 if (!CheckConstraint (ec, ptype, aexpr, it))
1541 return false;
1546 // Finally, check the constructor constraint.
1549 if (!gc.HasConstructorConstraint)
1550 return true;
1552 if (TypeManager.IsBuiltinType (atype) || TypeManager.IsValueType (atype))
1553 return true;
1555 if (HasDefaultConstructor (atype))
1556 return true;
1558 Report_SymbolRelatedToPreviousError ();
1559 Report.SymbolRelatedToPreviousError (atype);
1560 Report.Error (310, loc, "The type `{0}' must have a public " +
1561 "parameterless constructor in order to use it " +
1562 "as parameter `{1}' in the generic type or " +
1563 "method `{2}'",
1564 TypeManager.CSharpName (atype),
1565 TypeManager.CSharpName (ptype),
1566 GetSignatureForError ());
1567 return false;
1570 protected bool CheckConstraint (IResolveContext ec, Type ptype, Expression expr,
1571 Type ctype)
1573 if (TypeManager.HasGenericArguments (ctype)) {
1574 Type[] types = TypeManager.GetTypeArguments (ctype);
1576 TypeArguments new_args = new TypeArguments ();
1578 for (int i = 0; i < types.Length; i++) {
1579 Type t = types [i];
1581 if (t.IsGenericParameter) {
1582 int pos = t.GenericParameterPosition;
1583 t = atypes [pos];
1585 new_args.Add (new TypeExpression (t, loc));
1588 TypeExpr ct = new GenericTypeExpr (ctype, new_args, loc);
1589 if (ct.ResolveAsTypeStep (ec, false) == null)
1590 return false;
1591 ctype = ct.Type;
1592 } else if (ctype.IsGenericParameter) {
1593 int pos = ctype.GenericParameterPosition;
1594 if (ctype.DeclaringMethod == null) {
1595 // FIXME: Implement
1596 return true;
1597 } else {
1598 ctype = atypes [pos];
1602 if (Convert.ImplicitStandardConversionExists (expr, ctype))
1603 return true;
1605 Report_SymbolRelatedToPreviousError ();
1606 Report.SymbolRelatedToPreviousError (expr.Type);
1608 if (TypeManager.IsNullableType (expr.Type) && ctype.IsInterface) {
1609 Report.Error (313, loc,
1610 "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. " +
1611 "The nullable type `{0}' never satisfies interface constraint of type `{3}'",
1612 TypeManager.CSharpName (expr.Type), TypeManager.CSharpName (ptype),
1613 GetSignatureForError (), TypeManager.CSharpName (ctype));
1614 } else {
1615 Report.Error (309, loc,
1616 "The type `{0}' must be convertible to `{1}' in order to " +
1617 "use it as parameter `{2}' in the generic type or method `{3}'",
1618 TypeManager.CSharpName (expr.Type), TypeManager.CSharpName (ctype),
1619 TypeManager.CSharpName (ptype), GetSignatureForError ());
1621 return false;
1624 static bool HasDefaultConstructor (Type atype)
1626 TypeParameter tparam = TypeManager.LookupTypeParameter (atype);
1627 if (tparam != null) {
1628 if (tparam.GenericConstraints == null)
1629 return false;
1631 return tparam.GenericConstraints.HasConstructorConstraint ||
1632 tparam.GenericConstraints.HasValueTypeConstraint;
1635 if (atype.IsAbstract)
1636 return false;
1638 again:
1639 atype = TypeManager.DropGenericTypeArguments (atype);
1640 if (atype is TypeBuilder) {
1641 TypeContainer tc = TypeManager.LookupTypeContainer (atype);
1642 if (tc.InstanceConstructors == null) {
1643 atype = atype.BaseType;
1644 goto again;
1647 foreach (Constructor c in tc.InstanceConstructors) {
1648 if ((c.ModFlags & Modifiers.PUBLIC) == 0)
1649 continue;
1650 if ((c.Parameters.FixedParameters != null) &&
1651 (c.Parameters.FixedParameters.Length != 0))
1652 continue;
1653 if (c.Parameters.HasArglist || c.Parameters.HasParams)
1654 continue;
1656 return true;
1660 MemberInfo [] list = TypeManager.MemberLookup (null, null, atype, MemberTypes.Constructor,
1661 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
1662 ConstructorInfo.ConstructorName, null);
1664 if (list == null)
1665 return false;
1667 foreach (MethodBase mb in list) {
1668 AParametersCollection pd = TypeManager.GetParameterData (mb);
1669 if (pd.Count == 0)
1670 return true;
1673 return false;
1676 protected abstract string GetSignatureForError ();
1677 protected abstract void Report_SymbolRelatedToPreviousError ();
1679 public static bool CheckConstraints (EmitContext ec, MethodBase definition,
1680 MethodBase instantiated, Location loc)
1682 MethodConstraintChecker checker = new MethodConstraintChecker (
1683 definition, definition.GetGenericArguments (),
1684 instantiated.GetGenericArguments (), loc);
1686 return checker.CheckConstraints (ec);
1689 public static bool CheckConstraints (IResolveContext ec, Type gt, Type[] gen_params,
1690 Type[] atypes, Location loc)
1692 TypeConstraintChecker checker = new TypeConstraintChecker (
1693 gt, gen_params, atypes, loc);
1695 return checker.CheckConstraints (ec);
1698 protected class MethodConstraintChecker : ConstraintChecker
1700 MethodBase definition;
1702 public MethodConstraintChecker (MethodBase definition, Type[] gen_params,
1703 Type[] atypes, Location loc)
1704 : base (gen_params, atypes, loc)
1706 this.definition = definition;
1709 protected override string GetSignatureForError ()
1711 return TypeManager.CSharpSignature (definition);
1714 protected override void Report_SymbolRelatedToPreviousError ()
1716 Report.SymbolRelatedToPreviousError (definition);
1720 protected class TypeConstraintChecker : ConstraintChecker
1722 Type gt;
1724 public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
1725 Location loc)
1726 : base (gen_params, atypes, loc)
1728 this.gt = gt;
1731 protected override string GetSignatureForError ()
1733 return TypeManager.CSharpName (gt);
1736 protected override void Report_SymbolRelatedToPreviousError ()
1738 Report.SymbolRelatedToPreviousError (gt);
1743 /// <summary>
1744 /// A generic method definition.
1745 /// </summary>
1746 public class GenericMethod : DeclSpace
1748 FullNamedExpression return_type;
1749 ParametersCompiled parameters;
1751 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
1752 FullNamedExpression return_type, ParametersCompiled parameters)
1753 : base (ns, parent, name, null)
1755 this.return_type = return_type;
1756 this.parameters = parameters;
1759 public override TypeBuilder DefineType ()
1761 throw new Exception ();
1764 public override bool Define ()
1766 for (int i = 0; i < TypeParameters.Length; i++)
1767 if (!TypeParameters [i].Resolve (this))
1768 return false;
1770 return true;
1773 /// <summary>
1774 /// Define and resolve the type parameters.
1775 /// We're called from Method.Define().
1776 /// </summary>
1777 public bool Define (MethodOrOperator m)
1779 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1780 string[] snames = new string [names.Length];
1781 for (int i = 0; i < names.Length; i++) {
1782 string type_argument_name = names[i].Name;
1783 int idx = parameters.GetParameterIndexByName (type_argument_name);
1784 if (idx >= 0) {
1785 Block b = m.Block;
1786 if (b == null)
1787 b = new Block (null);
1789 b.Error_AlreadyDeclaredTypeParameter (parameters [i].Location,
1790 type_argument_name, "method parameter");
1793 snames[i] = type_argument_name;
1796 GenericTypeParameterBuilder[] gen_params = m.MethodBuilder.DefineGenericParameters (snames);
1797 for (int i = 0; i < TypeParameters.Length; i++)
1798 TypeParameters [i].Define (gen_params [i]);
1800 if (!Define ())
1801 return false;
1803 for (int i = 0; i < TypeParameters.Length; i++) {
1804 if (!TypeParameters [i].ResolveType (this))
1805 return false;
1808 return true;
1811 /// <summary>
1812 /// We're called from MethodData.Define() after creating the MethodBuilder.
1813 /// </summary>
1814 public bool DefineType (EmitContext ec, MethodBuilder mb,
1815 MethodInfo implementing, bool is_override)
1817 for (int i = 0; i < TypeParameters.Length; i++)
1818 if (!TypeParameters [i].DefineType (
1819 ec, mb, implementing, is_override))
1820 return false;
1822 bool ok = parameters.Resolve (ec);
1824 if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec, false) == null))
1825 ok = false;
1827 return ok;
1830 public void EmitAttributes ()
1832 for (int i = 0; i < TypeParameters.Length; i++)
1833 TypeParameters [i].Emit ();
1835 if (OptAttributes != null)
1836 OptAttributes.Emit ();
1839 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1840 MemberFilter filter, object criteria)
1842 throw new Exception ();
1845 public override MemberCache MemberCache {
1846 get {
1847 return null;
1851 public override AttributeTargets AttributeTargets {
1852 get {
1853 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1857 public override string DocCommentHeader {
1858 get { return "M:"; }
1861 public new void VerifyClsCompliance ()
1863 foreach (TypeParameter tp in TypeParameters) {
1864 if (tp.Constraints == null)
1865 continue;
1867 tp.Constraints.VerifyClsCompliance ();
1872 public partial class TypeManager
1874 static public Type activator_type;
1876 public static TypeContainer LookupGenericTypeContainer (Type t)
1878 t = DropGenericTypeArguments (t);
1879 return LookupTypeContainer (t);
1882 /// <summary>
1883 /// Check whether `a' and `b' may become equal generic types.
1884 /// The algorithm to do that is a little bit complicated.
1885 /// </summary>
1886 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_inferred,
1887 Type[] method_inferred)
1889 if (a.IsGenericParameter) {
1891 // If a is an array of a's type, they may never
1892 // become equal.
1894 while (b.IsArray) {
1895 b = GetElementType (b);
1896 if (a.Equals (b))
1897 return false;
1901 // If b is a generic parameter or an actual type,
1902 // they may become equal:
1904 // class X<T,U> : I<T>, I<U>
1905 // class X<T> : I<T>, I<float>
1907 if (b.IsGenericParameter || !b.IsGenericType) {
1908 int pos = a.GenericParameterPosition;
1909 Type[] args = a.DeclaringMethod != null ? method_inferred : class_inferred;
1910 if (args [pos] == null) {
1911 args [pos] = b;
1912 return true;
1915 return args [pos] == a;
1919 // We're now comparing a type parameter with a
1920 // generic instance. They may become equal unless
1921 // the type parameter appears anywhere in the
1922 // generic instance:
1924 // class X<T,U> : I<T>, I<X<U>>
1925 // -> error because you could instanciate it as
1926 // X<X<int>,int>
1928 // class X<T> : I<T>, I<X<T>> -> ok
1931 Type[] bargs = GetTypeArguments (b);
1932 for (int i = 0; i < bargs.Length; i++) {
1933 if (a.Equals (bargs [i]))
1934 return false;
1937 return true;
1940 if (b.IsGenericParameter)
1941 return MayBecomeEqualGenericTypes (b, a, class_inferred, method_inferred);
1944 // At this point, neither a nor b are a type parameter.
1946 // If one of them is a generic instance, let
1947 // MayBecomeEqualGenericInstances() compare them (if the
1948 // other one is not a generic instance, they can never
1949 // become equal).
1952 if (a.IsGenericType || b.IsGenericType)
1953 return MayBecomeEqualGenericInstances (a, b, class_inferred, method_inferred);
1956 // If both of them are arrays.
1959 if (a.IsArray && b.IsArray) {
1960 if (a.GetArrayRank () != b.GetArrayRank ())
1961 return false;
1963 a = GetElementType (a);
1964 b = GetElementType (b);
1966 return MayBecomeEqualGenericTypes (a, b, class_inferred, method_inferred);
1970 // Ok, two ordinary types.
1973 return a.Equals (b);
1977 // Checks whether two generic instances may become equal for some
1978 // particular instantiation (26.3.1).
1980 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
1981 Type[] class_inferred,
1982 Type[] method_inferred)
1984 if (!a.IsGenericType || !b.IsGenericType)
1985 return false;
1986 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
1987 return false;
1989 return MayBecomeEqualGenericInstances (
1990 GetTypeArguments (a), GetTypeArguments (b), class_inferred, method_inferred);
1993 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
1994 Type[] class_inferred,
1995 Type[] method_inferred)
1997 if (aargs.Length != bargs.Length)
1998 return false;
2000 for (int i = 0; i < aargs.Length; i++) {
2001 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_inferred, method_inferred))
2002 return false;
2005 return true;
2008 /// <summary>
2009 /// Type inference. Try to infer the type arguments from `method',
2010 /// which is invoked with the arguments `arguments'. This is used
2011 /// when resolving an Invocation or a DelegateInvocation and the user
2012 /// did not explicitly specify type arguments.
2013 /// </summary>
2014 public static int InferTypeArguments (EmitContext ec,
2015 ArrayList arguments,
2016 ref MethodBase method)
2018 ATypeInference ti = ATypeInference.CreateInstance (arguments);
2019 Type[] i_args = ti.InferMethodArguments (ec, method);
2020 if (i_args == null)
2021 return ti.InferenceScore;
2023 if (i_args.Length == 0)
2024 return 0;
2026 method = ((MethodInfo) method).MakeGenericMethod (i_args);
2027 return 0;
2030 /// <summary>
2031 /// Type inference.
2032 /// </summary>
2033 public static bool InferTypeArguments (AParametersCollection apd,
2034 ref MethodBase method)
2036 if (!TypeManager.IsGenericMethod (method))
2037 return true;
2039 ATypeInference ti = ATypeInference.CreateInstance (ArrayList.Adapter (apd.Types));
2040 Type[] i_args = ti.InferDelegateArguments (method);
2041 if (i_args == null)
2042 return false;
2044 method = ((MethodInfo) method).MakeGenericMethod (i_args);
2045 return true;
2049 abstract class ATypeInference
2051 protected readonly ArrayList arguments;
2052 protected readonly int arg_count;
2054 protected ATypeInference (ArrayList arguments)
2056 this.arguments = arguments;
2057 if (arguments != null)
2058 arg_count = arguments.Count;
2061 public static ATypeInference CreateInstance (ArrayList arguments)
2063 return new TypeInferenceV3 (arguments);
2066 public virtual int InferenceScore {
2067 get {
2068 return int.MaxValue;
2072 public abstract Type[] InferMethodArguments (EmitContext ec, MethodBase method);
2073 public abstract Type[] InferDelegateArguments (MethodBase method);
2077 // Implements C# 3.0 type inference
2079 class TypeInferenceV3 : ATypeInference
2082 // Tracks successful rate of type inference
2084 int score = int.MaxValue;
2086 public TypeInferenceV3 (ArrayList arguments)
2087 : base (arguments)
2091 public override int InferenceScore {
2092 get {
2093 return score;
2097 public override Type[] InferDelegateArguments (MethodBase method)
2099 AParametersCollection pd = TypeManager.GetParameterData (method);
2100 if (arg_count != pd.Count)
2101 return null;
2103 Type[] d_gargs = method.GetGenericArguments ();
2104 TypeInferenceContext context = new TypeInferenceContext (d_gargs);
2106 // A lower-bound inference is made from each argument type Uj of D
2107 // to the corresponding parameter type Tj of M
2108 for (int i = 0; i < arg_count; ++i) {
2109 Type t = pd.Types [i];
2110 if (!t.IsGenericParameter)
2111 continue;
2113 context.LowerBoundInference ((Type)arguments[i], t);
2116 if (!context.FixAllTypes ())
2117 return null;
2119 return context.InferredTypeArguments;
2122 public override Type[] InferMethodArguments (EmitContext ec, MethodBase method)
2124 Type[] method_generic_args = method.GetGenericArguments ();
2125 TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2126 if (!context.UnfixedVariableExists)
2127 return Type.EmptyTypes;
2129 AParametersCollection pd = TypeManager.GetParameterData (method);
2130 if (!InferInPhases (ec, context, pd))
2131 return null;
2133 return context.InferredTypeArguments;
2137 // Implements method type arguments inference
2139 bool InferInPhases (EmitContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
2141 int params_arguments_start;
2142 if (methodParameters.HasParams) {
2143 params_arguments_start = methodParameters.Count - 1;
2144 } else {
2145 params_arguments_start = arg_count;
2148 Type [] ptypes = methodParameters.Types;
2151 // The first inference phase
2153 Type method_parameter = null;
2154 for (int i = 0; i < arg_count; i++) {
2155 Argument a = (Argument) arguments [i];
2157 if (i < params_arguments_start) {
2158 method_parameter = methodParameters.Types [i];
2159 } else if (i == params_arguments_start) {
2160 if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2161 method_parameter = methodParameters.Types [params_arguments_start];
2162 else
2163 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2165 ptypes = (Type[]) ptypes.Clone ();
2166 ptypes [i] = method_parameter;
2170 // When a lambda expression, an anonymous method
2171 // is used an explicit argument type inference takes a place
2173 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2174 if (am != null) {
2175 if (am.ExplicitTypeInference (tic, method_parameter))
2176 --score;
2177 continue;
2180 if (a.Expr.Type == TypeManager.null_type)
2181 continue;
2184 // Otherwise an output type inference is made
2186 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2190 // Part of the second phase but because it happens only once
2191 // we don't need to call it in cycle
2193 bool fixed_any = false;
2194 if (!tic.FixIndependentTypeArguments (ptypes, ref fixed_any))
2195 return false;
2197 return DoSecondPhase (ec, tic, ptypes, !fixed_any);
2200 bool DoSecondPhase (EmitContext ec, TypeInferenceContext tic, Type[] methodParameters, bool fixDependent)
2202 bool fixed_any = false;
2203 if (fixDependent && !tic.FixDependentTypes (ref fixed_any))
2204 return false;
2206 // If no further unfixed type variables exist, type inference succeeds
2207 if (!tic.UnfixedVariableExists)
2208 return true;
2210 if (!fixed_any && fixDependent)
2211 return false;
2213 // For all arguments where the corresponding argument output types
2214 // contain unfixed type variables but the input types do not,
2215 // an output type inference is made
2216 for (int i = 0; i < arg_count; i++) {
2218 // Align params arguments
2219 Type t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
2221 if (!TypeManager.IsDelegateType (t_i)) {
2222 if (TypeManager.DropGenericTypeArguments (t_i) != TypeManager.expression_type)
2223 continue;
2225 t_i = t_i.GetGenericArguments () [0];
2228 MethodInfo mi = Delegate.GetInvokeMethod (t_i, t_i);
2229 Type rtype = mi.ReturnType;
2231 #if MS_COMPATIBLE
2232 // Blablabla, because reflection does not work with dynamic types
2233 Type[] g_args = t_i.GetGenericArguments ();
2234 rtype = g_args[rtype.GenericParameterPosition];
2235 #endif
2237 if (tic.IsReturnTypeNonDependent (mi, rtype))
2238 score -= tic.OutputTypeInference (ec, ((Argument) arguments [i]).Expr, t_i);
2242 return DoSecondPhase (ec, tic, methodParameters, true);
2246 public class TypeInferenceContext
2248 readonly Type[] unfixed_types;
2249 readonly Type[] fixed_types;
2250 readonly ArrayList[] bounds;
2251 bool failed;
2253 public TypeInferenceContext (Type[] typeArguments)
2255 if (typeArguments.Length == 0)
2256 throw new ArgumentException ("Empty generic arguments");
2258 fixed_types = new Type [typeArguments.Length];
2259 for (int i = 0; i < typeArguments.Length; ++i) {
2260 if (typeArguments [i].IsGenericParameter) {
2261 if (bounds == null) {
2262 bounds = new ArrayList [typeArguments.Length];
2263 unfixed_types = new Type [typeArguments.Length];
2265 unfixed_types [i] = typeArguments [i];
2266 } else {
2267 fixed_types [i] = typeArguments [i];
2272 public Type[] InferredTypeArguments {
2273 get {
2274 return fixed_types;
2278 void AddToBounds (Type t, int index)
2281 // Some types cannot be used as type arguments
2283 if (t == TypeManager.void_type || t.IsPointer)
2284 return;
2286 ArrayList a = bounds [index];
2287 if (a == null) {
2288 a = new ArrayList ();
2289 bounds [index] = a;
2290 } else {
2291 if (a.Contains (t))
2292 return;
2296 // SPEC: does not cover type inference using constraints
2298 //if (TypeManager.IsGenericParameter (t)) {
2299 // GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
2300 // if (constraints != null) {
2301 // //if (constraints.EffectiveBaseClass != null)
2302 // // t = constraints.EffectiveBaseClass;
2303 // }
2305 a.Add (t);
2308 bool AllTypesAreFixed (Type[] types)
2310 foreach (Type t in types) {
2311 if (t.IsGenericParameter) {
2312 if (!IsFixed (t))
2313 return false;
2314 continue;
2317 if (t.IsGenericType)
2318 return AllTypesAreFixed (t.GetGenericArguments ());
2321 return true;
2325 // 26.3.3.8 Exact Inference
2327 public int ExactInference (Type u, Type v)
2329 // If V is an array type
2330 if (v.IsArray) {
2331 if (!u.IsArray)
2332 return 0;
2334 if (u.GetArrayRank () != v.GetArrayRank ())
2335 return 0;
2337 return ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
2340 // If V is constructed type and U is constructed type
2341 if (v.IsGenericType && !v.IsGenericTypeDefinition) {
2342 if (!u.IsGenericType)
2343 return 0;
2345 Type [] ga_u = u.GetGenericArguments ();
2346 Type [] ga_v = v.GetGenericArguments ();
2347 if (ga_u.Length != ga_v.Length)
2348 return 0;
2350 int score = 0;
2351 for (int i = 0; i < ga_u.Length; ++i)
2352 score += ExactInference (ga_u [i], ga_v [i]);
2354 return score > 0 ? 1 : 0;
2357 // If V is one of the unfixed type arguments
2358 int pos = IsUnfixed (v);
2359 if (pos == -1)
2360 return 0;
2362 AddToBounds (u, pos);
2363 return 1;
2366 public bool FixAllTypes ()
2368 for (int i = 0; i < unfixed_types.Length; ++i) {
2369 if (!FixType (i))
2370 return false;
2372 return true;
2376 // All unfixed type variables Xi are fixed for which all of the following hold:
2377 // a, There is at least one type variable Xj that depends on Xi
2378 // b, Xi has a non-empty set of bounds
2380 public bool FixDependentTypes (ref bool fixed_any)
2382 for (int i = 0; i < unfixed_types.Length; ++i) {
2383 if (unfixed_types[i] == null)
2384 continue;
2386 if (bounds[i] == null)
2387 continue;
2389 if (!FixType (i))
2390 return false;
2392 fixed_any = true;
2395 return true;
2399 // All unfixed type variables Xi which depend on no Xj are fixed
2401 public bool FixIndependentTypeArguments (Type[] methodParameters, ref bool fixed_any)
2403 ArrayList types_to_fix = new ArrayList (unfixed_types);
2404 for (int i = 0; i < methodParameters.Length; ++i) {
2405 Type t = methodParameters[i];
2407 if (!TypeManager.IsDelegateType (t)) {
2408 if (TypeManager.DropGenericTypeArguments (t) != TypeManager.expression_type)
2409 continue;
2411 t = t.GetGenericArguments () [0];
2414 if (t.IsGenericParameter)
2415 continue;
2417 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
2418 Type rtype = invoke.ReturnType;
2419 if (!rtype.IsGenericParameter && !rtype.IsGenericType)
2420 continue;
2422 #if MS_COMPATIBLE
2423 // Blablabla, because reflection does not work with dynamic types
2424 if (rtype.IsGenericParameter) {
2425 Type [] g_args = t.GetGenericArguments ();
2426 rtype = g_args [rtype.GenericParameterPosition];
2428 #endif
2429 // Remove dependent types, they cannot be fixed yet
2430 RemoveDependentTypes (types_to_fix, rtype);
2433 foreach (Type t in types_to_fix) {
2434 if (t == null)
2435 continue;
2437 int idx = IsUnfixed (t);
2438 if (idx >= 0 && !FixType (idx)) {
2439 return false;
2443 fixed_any = types_to_fix.Count > 0;
2444 return true;
2448 // 26.3.3.10 Fixing
2450 public bool FixType (int i)
2452 // It's already fixed
2453 if (unfixed_types[i] == null)
2454 throw new InternalErrorException ("Type argument has been already fixed");
2456 if (failed)
2457 return false;
2459 ArrayList candidates = (ArrayList)bounds [i];
2460 if (candidates == null)
2461 return false;
2463 if (candidates.Count == 1) {
2464 unfixed_types[i] = null;
2465 fixed_types[i] = (Type)candidates[0];
2466 return true;
2470 // Determines a unique type from which there is
2471 // a standard implicit conversion to all the other
2472 // candidate types.
2474 Type best_candidate = null;
2475 int cii;
2476 int candidates_count = candidates.Count;
2477 for (int ci = 0; ci < candidates_count; ++ci) {
2478 Type candidate = (Type)candidates [ci];
2479 for (cii = 0; cii < candidates_count; ++cii) {
2480 if (cii == ci)
2481 continue;
2483 if (!Convert.ImplicitConversionExists (null,
2484 new TypeExpression ((Type)candidates [cii], Location.Null), candidate)) {
2485 break;
2489 if (cii != candidates_count)
2490 continue;
2492 if (best_candidate != null)
2493 return false;
2495 best_candidate = candidate;
2498 if (best_candidate == null)
2499 return false;
2501 unfixed_types[i] = null;
2502 fixed_types[i] = best_candidate;
2503 return true;
2507 // Uses inferred types to inflate delegate type argument
2509 public Type InflateGenericArgument (Type parameter)
2511 if (parameter.IsGenericParameter) {
2513 // Inflate method generic argument (MVAR) only
2515 if (parameter.DeclaringMethod == null)
2516 return parameter;
2518 return fixed_types [parameter.GenericParameterPosition];
2521 if (parameter.IsGenericType) {
2522 Type [] parameter_targs = parameter.GetGenericArguments ();
2523 for (int ii = 0; ii < parameter_targs.Length; ++ii) {
2524 parameter_targs [ii] = InflateGenericArgument (parameter_targs [ii]);
2526 return parameter.GetGenericTypeDefinition ().MakeGenericType (parameter_targs);
2529 return parameter;
2533 // Tests whether all delegate input arguments are fixed and generic output type
2534 // requires output type inference
2536 public bool IsReturnTypeNonDependent (MethodInfo invoke, Type returnType)
2538 if (returnType.IsGenericParameter) {
2539 if (IsFixed (returnType))
2540 return false;
2541 } else if (returnType.IsGenericType) {
2542 if (TypeManager.IsDelegateType (returnType)) {
2543 invoke = Delegate.GetInvokeMethod (returnType, returnType);
2544 return IsReturnTypeNonDependent (invoke, invoke.ReturnType);
2547 Type[] g_args = returnType.GetGenericArguments ();
2549 // At least one unfixed return type has to exist
2550 if (AllTypesAreFixed (g_args))
2551 return false;
2552 } else {
2553 return false;
2556 // All generic input arguments have to be fixed
2557 AParametersCollection d_parameters = TypeManager.GetParameterData (invoke);
2558 return AllTypesAreFixed (d_parameters.Types);
2561 bool IsFixed (Type type)
2563 return IsUnfixed (type) == -1;
2566 int IsUnfixed (Type type)
2568 if (!type.IsGenericParameter)
2569 return -1;
2571 //return unfixed_types[type.GenericParameterPosition] != null;
2572 for (int i = 0; i < unfixed_types.Length; ++i) {
2573 if (unfixed_types [i] == type)
2574 return i;
2577 return -1;
2581 // 26.3.3.9 Lower-bound Inference
2583 public int LowerBoundInference (Type u, Type v)
2585 // If V is one of the unfixed type arguments
2586 int pos = IsUnfixed (v);
2587 if (pos != -1) {
2588 AddToBounds (u, pos);
2589 return 1;
2592 // If U is an array type
2593 if (u.IsArray) {
2594 int u_dim = u.GetArrayRank ();
2595 Type v_e;
2596 Type u_e = TypeManager.GetElementType (u);
2598 if (v.IsArray) {
2599 if (u_dim != v.GetArrayRank ())
2600 return 0;
2602 v_e = TypeManager.GetElementType (v);
2604 if (u.IsByRef) {
2605 return LowerBoundInference (u_e, v_e);
2608 return ExactInference (u_e, v_e);
2611 if (u_dim != 1)
2612 return 0;
2614 if (v.IsGenericType) {
2615 Type g_v = v.GetGenericTypeDefinition ();
2616 if ((g_v != TypeManager.generic_ilist_type) && (g_v != TypeManager.generic_icollection_type) &&
2617 (g_v != TypeManager.generic_ienumerable_type))
2618 return 0;
2620 v_e = TypeManager.GetTypeArguments (v)[0];
2622 if (u.IsByRef) {
2623 return LowerBoundInference (u_e, v_e);
2626 return ExactInference (u_e, v_e);
2628 } else if (v.IsGenericType && !v.IsGenericTypeDefinition) {
2630 // if V is a constructed type C<V1..Vk> and there is a unique set of types U1..Uk
2631 // such that a standard implicit conversion exists from U to C<U1..Uk> then an exact
2632 // inference is made from each Ui for the corresponding Vi
2634 ArrayList u_candidates = new ArrayList ();
2635 if (u.IsGenericType)
2636 u_candidates.Add (u);
2638 for (Type t = u.BaseType; t != null; t = t.BaseType) {
2639 if (t.IsGenericType && !t.IsGenericTypeDefinition)
2640 u_candidates.Add (t);
2643 // TODO: Implement GetGenericInterfaces only and remove
2644 // the if from foreach
2645 u_candidates.AddRange (TypeManager.GetInterfaces (u));
2647 Type open_v = v.GetGenericTypeDefinition ();
2648 Type [] unique_candidate_targs = null;
2649 Type [] ga_v = v.GetGenericArguments ();
2650 foreach (Type u_candidate in u_candidates) {
2651 if (!u_candidate.IsGenericType || u_candidate.IsGenericTypeDefinition)
2652 continue;
2654 if (TypeManager.DropGenericTypeArguments (u_candidate) != open_v)
2655 continue;
2658 // The unique set of types U1..Uk means that if we have an interface C<T>,
2659 // class U: C<int>, C<long> then no type inference is made when inferring
2660 // from U to C<T> because T could be int or long
2662 if (unique_candidate_targs != null) {
2663 Type[] second_unique_candidate_targs = u_candidate.GetGenericArguments ();
2664 if (TypeManager.IsEqual (unique_candidate_targs, second_unique_candidate_targs)) {
2665 unique_candidate_targs = second_unique_candidate_targs;
2666 continue;
2670 // This should always cause type inference failure
2672 failed = true;
2673 return 1;
2676 unique_candidate_targs = u_candidate.GetGenericArguments ();
2679 if (unique_candidate_targs != null) {
2680 int score = 0;
2681 for (int i = 0; i < unique_candidate_targs.Length; ++i)
2682 if (ExactInference (unique_candidate_targs [i], ga_v [i]) == 0)
2683 ++score;
2684 return score;
2688 return 0;
2692 // 26.3.3.6 Output Type Inference
2694 public int OutputTypeInference (EmitContext ec, Expression e, Type t)
2696 // If e is a lambda or anonymous method with inferred return type
2697 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
2698 if (ame != null) {
2699 Type rt = ame.InferReturnType (ec, this, t);
2700 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
2702 if (rt == null) {
2703 AParametersCollection pd = TypeManager.GetParameterData (invoke);
2704 return ame.Parameters.Count == pd.Count ? 1 : 0;
2707 Type rtype = invoke.ReturnType;
2708 #if MS_COMPATIBLE
2709 // Blablabla, because reflection does not work with dynamic types
2710 Type [] g_args = t.GetGenericArguments ();
2711 rtype = g_args [rtype.GenericParameterPosition];
2712 #endif
2713 return LowerBoundInference (rt, rtype) + 1;
2717 // if E is a method group and T is a delegate type or expression tree type
2718 // return type Tb with parameter types T1..Tk and return type Tb, and overload
2719 // resolution of E with the types T1..Tk yields a single method with return type U,
2720 // then a lower-bound inference is made from U for Tb.
2722 if (e is MethodGroupExpr) {
2723 // TODO: Or expression tree
2724 if (!TypeManager.IsDelegateType (t))
2725 return 0;
2727 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
2728 Type rtype = invoke.ReturnType;
2729 #if MS_COMPATIBLE
2730 // Blablabla, because reflection does not work with dynamic types
2731 Type [] g_args = t.GetGenericArguments ();
2732 rtype = g_args [rtype.GenericParameterPosition];
2733 #endif
2735 if (!TypeManager.IsGenericType (rtype))
2736 return 0;
2738 MethodGroupExpr mg = (MethodGroupExpr) e;
2739 ArrayList args = DelegateCreation.CreateDelegateMethodArguments (invoke, e.Location);
2740 mg = mg.OverloadResolve (ec, ref args, true, e.Location);
2741 if (mg == null)
2742 return 0;
2744 // TODO: What should happen when return type is of generic type ?
2745 throw new NotImplementedException ();
2746 // return LowerBoundInference (null, rtype) + 1;
2750 // if e is an expression with type U, then
2751 // a lower-bound inference is made from U for T
2753 return LowerBoundInference (e.Type, t) * 2;
2756 void RemoveDependentTypes (ArrayList types, Type returnType)
2758 int idx = IsUnfixed (returnType);
2759 if (idx >= 0) {
2760 types [idx] = null;
2761 return;
2764 if (returnType.IsGenericType) {
2765 foreach (Type t in returnType.GetGenericArguments ()) {
2766 RemoveDependentTypes (types, t);
2771 public bool UnfixedVariableExists {
2772 get {
2773 if (unfixed_types == null)
2774 return false;
2776 foreach (Type ut in unfixed_types)
2777 if (ut != null)
2778 return true;
2779 return false;