2 // generic.cs: Generics support
4 // Authors: Martin Baulig (martin@ximian.com)
5 // Miguel de Icaza (miguel@ximian.com)
6 // Marek Safar (marek.safar@gmail.com)
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
10 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004-2008 Novell, Inc
14 using System
.Reflection
;
15 using System
.Reflection
.Emit
;
16 using System
.Globalization
;
17 using System
.Collections
;
19 using System
.Text
.RegularExpressions
;
21 namespace Mono
.CSharp
{
24 /// Abstract base class for type parameter constraints.
25 /// The type parameter can come from a generic type definition or from reflection.
27 public abstract class GenericConstraints
{
28 public abstract string TypeParameter
{
32 public abstract GenericParameterAttributes Attributes
{
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
{
56 public abstract Type
[] InterfaceConstraints
{
60 public abstract Type EffectiveBaseClass
{
65 // Returns whether the type parameter is "known to be a reference type".
67 public virtual bool IsReferenceType
{
69 if (HasReferenceTypeConstraint
)
71 if (HasValueTypeConstraint
)
74 if (ClassConstraint
!= null) {
75 if (ClassConstraint
.IsValueType
)
78 if (ClassConstraint
!= TypeManager
.object_type
)
82 foreach (Type t
in InterfaceConstraints
) {
83 if (!t
.IsGenericParameter
)
86 GenericConstraints gc
= TypeManager
.GetTypeParameterConstraints (t
);
87 if ((gc
!= null) && gc
.IsReferenceType
)
96 // Returns whether the type parameter is "known to be a value type".
98 public virtual bool IsValueType
{
100 if (HasValueTypeConstraint
)
102 if (HasReferenceTypeConstraint
)
105 if (ClassConstraint
!= null) {
106 if (!TypeManager
.IsValueType (ClassConstraint
))
109 if (ClassConstraint
!= TypeManager
.value_type
)
113 foreach (Type t
in InterfaceConstraints
) {
114 if (!t
.IsGenericParameter
)
117 GenericConstraints gc
= TypeManager
.GetTypeParameterConstraints (t
);
118 if ((gc
!= null) && gc
.IsValueType
)
127 public class ReflectionConstraints
: GenericConstraints
129 GenericParameterAttributes attrs
;
131 Type class_constraint
;
132 Type
[] iface_constraints
;
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
)
141 return new ReflectionConstraints (t
.Name
, constraints
, attrs
);
144 private ReflectionConstraints (string name
, Type
[] constraints
, GenericParameterAttributes 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);
154 iface_constraints
= constraints
;
156 if (HasValueTypeConstraint
)
157 base_type
= TypeManager
.value_type
;
158 else if (class_constraint
!= null)
159 base_type
= class_constraint
;
161 base_type
= TypeManager
.object_type
;
164 public override string TypeParameter
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; }
193 // Don't add or modify internal values, they are used as -/+ calculation signs
200 public enum SpecialConstraint
208 /// Tracks the constraints for a type parameter from a generic type definition.
210 public class Constraints
: GenericConstraints
{
212 ArrayList constraints
;
216 // name is the identifier, constraints is an arraylist of
217 // Expressions (with types) or `true' for the constructor constraint.
219 public Constraints (string name
, ArrayList constraints
,
223 this.constraints
= constraints
;
227 public override string TypeParameter
{
233 public Constraints
Clone ()
235 return new Constraints (name
, constraints
, loc
);
238 GenericParameterAttributes attrs
;
239 TypeExpr class_constraint
;
240 ArrayList iface_constraints
;
241 ArrayList type_param_constraints
;
243 Type class_constraint_type
;
244 Type
[] iface_constraint_types
;
245 Type effective_base_type
;
250 /// Resolve the constraints - but only resolve things into Expression's, not
251 /// into actual types.
253 public bool Resolve (IResolveContext ec
, TypeParameter tp
)
258 iface_constraints
= new ArrayList (2); // TODO: Too expensive allocation
259 type_param_constraints
= new ArrayList ();
261 foreach (object obj
in constraints
) {
262 if (HasConstructorConstraint
) {
263 Report
.Error (401, loc
,
264 "The new() constraint must be the last constraint specified");
268 if (obj
is SpecialConstraint
) {
269 SpecialConstraint sc
= (SpecialConstraint
) obj
;
271 if (sc
== SpecialConstraint
.Constructor
) {
272 if (!HasValueTypeConstraint
) {
273 attrs
|= GenericParameterAttributes
.DefaultConstructorConstraint
;
277 Report
.Error (451, loc
, "The `new()' constraint " +
278 "cannot be used with the `struct' constraint");
282 if ((num_constraints
> 0) || HasReferenceTypeConstraint
|| HasValueTypeConstraint
) {
283 Report
.Error (449, loc
, "The `class' or `struct' " +
284 "constraint must be the first constraint specified");
288 if (sc
== SpecialConstraint
.ReferenceType
)
289 attrs
|= GenericParameterAttributes
.ReferenceTypeConstraint
;
291 attrs
|= GenericParameterAttributes
.NotNullableValueTypeConstraint
;
295 int errors
= Report
.Errors
;
296 FullNamedExpression fn
= ((Expression
) obj
).ResolveAsTypeStep (ec
, false);
299 if (errors
!= Report
.Errors
)
302 NamespaceEntry
.Error_NamespaceNotFound (loc
, ((Expression
)obj
).GetSignatureForError ());
307 GenericTypeExpr cexpr
= fn
as GenericTypeExpr
;
309 expr
= cexpr
.ResolveAsBaseTerminal (ec
, false);
311 expr
= ((Expression
) obj
).ResolveAsTypeTerminal (ec
, false);
313 if ((expr
== null) || (expr
.Type
== null))
316 if (!ec
.GenericDeclContainer
.IsAccessibleAs (fn
.Type
)) {
317 Report
.SymbolRelatedToPreviousError (fn
.Type
);
318 Report
.Error (703, loc
,
319 "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
320 fn
.GetSignatureForError (), ec
.GenericDeclContainer
.GetSignatureForError ());
324 TypeParameterExpr texpr
= expr
as TypeParameterExpr
;
326 type_param_constraints
.Add (expr
);
327 else if (expr
.IsInterface
)
328 iface_constraints
.Add (expr
);
329 else if (class_constraint
!= null || iface_constraints
.Count
!= 0) {
330 Report
.Error (406, loc
,
331 "The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
332 expr
.GetSignatureForError ());
334 } else if (HasReferenceTypeConstraint
|| HasValueTypeConstraint
) {
335 Report
.Error (450, loc
, "`{0}': cannot specify both " +
336 "a constraint class and the `class' " +
337 "or `struct' constraint", expr
.GetSignatureForError ());
340 class_constraint
= expr
;
344 // Checks whether each generic method parameter constraint type
345 // is valid with respect to T
347 if (tp
!= null && tp
.Type
.DeclaringMethod
!= null) {
348 TypeManager
.CheckTypeVariance (expr
.Type
, Variance
.Contravariant
, ec
as MemberCore
);
354 ArrayList list
= new ArrayList ();
355 foreach (TypeExpr iface_constraint
in iface_constraints
) {
356 foreach (Type type
in list
) {
357 if (!type
.Equals (iface_constraint
.Type
))
360 Report
.Error (405, loc
,
361 "Duplicate constraint `{0}' for type " +
362 "parameter `{1}'.", iface_constraint
.GetSignatureForError (),
367 list
.Add (iface_constraint
.Type
);
370 foreach (TypeParameterExpr expr
in type_param_constraints
) {
371 foreach (Type type
in list
) {
372 if (!type
.Equals (expr
.Type
))
375 Report
.Error (405, loc
,
376 "Duplicate constraint `{0}' for type " +
377 "parameter `{1}'.", expr
.GetSignatureForError (), name
);
381 list
.Add (expr
.Type
);
384 iface_constraint_types
= new Type
[list
.Count
];
385 list
.CopyTo (iface_constraint_types
, 0);
387 if (class_constraint
!= null) {
388 class_constraint_type
= class_constraint
.Type
;
389 if (class_constraint_type
== null)
392 if (class_constraint_type
.IsSealed
) {
393 if (class_constraint_type
.IsAbstract
)
395 Report
.Error (717, loc
, "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
396 TypeManager
.CSharpName (class_constraint_type
));
400 Report
.Error (701, loc
, "`{0}' is not a valid constraint. A constraint must be an interface, " +
401 "a non-sealed class or a type parameter", TypeManager
.CSharpName(class_constraint_type
));
406 if ((class_constraint_type
== TypeManager
.array_type
) ||
407 (class_constraint_type
== TypeManager
.delegate_type
) ||
408 (class_constraint_type
== TypeManager
.enum_type
) ||
409 (class_constraint_type
== TypeManager
.value_type
) ||
410 (class_constraint_type
== TypeManager
.object_type
) ||
411 class_constraint_type
== TypeManager
.multicast_delegate_type
) {
412 Report
.Error (702, loc
,
413 "A constraint cannot be special class `{0}'",
414 TypeManager
.CSharpName (class_constraint_type
));
419 if (class_constraint_type
!= null)
420 effective_base_type
= class_constraint_type
;
421 else if (HasValueTypeConstraint
)
422 effective_base_type
= TypeManager
.value_type
;
424 effective_base_type
= TypeManager
.object_type
;
426 if ((attrs
& GenericParameterAttributes
.NotNullableValueTypeConstraint
) != 0)
427 attrs
|= GenericParameterAttributes
.DefaultConstructorConstraint
;
433 bool CheckTypeParameterConstraints (TypeParameter tparam
, ref TypeExpr prevConstraint
, ArrayList seen
)
437 Constraints constraints
= tparam
.Constraints
;
438 if (constraints
== null)
441 if (constraints
.HasValueTypeConstraint
) {
442 Report
.Error (456, loc
,
443 "Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
449 // Checks whether there are no conflicts between type parameter constraints
453 // where U : A, B // A and B are not convertible
455 if (constraints
.HasClassConstraint
) {
456 if (prevConstraint
!= null) {
457 Type t2
= constraints
.ClassConstraint
;
458 TypeExpr e2
= constraints
.class_constraint
;
460 if (!Convert
.ImplicitReferenceConversionExists (prevConstraint
, t2
) &&
461 !Convert
.ImplicitReferenceConversionExists (e2
, prevConstraint
.Type
)) {
462 Report
.Error (455, loc
,
463 "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
464 name
, TypeManager
.CSharpName (prevConstraint
.Type
), TypeManager
.CSharpName (t2
));
469 prevConstraint
= constraints
.class_constraint
;
472 if (constraints
.type_param_constraints
== null)
475 foreach (TypeParameterExpr expr
in constraints
.type_param_constraints
) {
476 if (seen
.Contains (expr
.TypeParameter
)) {
477 Report
.Error (454, loc
, "Circular constraint " +
478 "dependency involving `{0}' and `{1}'",
479 tparam
.Name
, expr
.GetSignatureForError ());
483 if (!CheckTypeParameterConstraints (expr
.TypeParameter
, ref prevConstraint
, seen
))
491 /// Resolve the constraints into actual types.
493 public bool ResolveTypes (IResolveContext ec
)
498 resolved_types
= true;
500 foreach (object obj
in constraints
) {
501 GenericTypeExpr cexpr
= obj
as GenericTypeExpr
;
505 if (!cexpr
.CheckConstraints (ec
))
509 if (type_param_constraints
.Count
!= 0) {
510 ArrayList seen
= new ArrayList ();
511 TypeExpr prev_constraint
= class_constraint
;
512 foreach (TypeParameterExpr expr
in type_param_constraints
) {
513 if (!CheckTypeParameterConstraints (expr
.TypeParameter
, ref prev_constraint
, seen
))
519 for (int i
= 0; i
< iface_constraints
.Count
; ++i
) {
520 TypeExpr iface_constraint
= (TypeExpr
) iface_constraints
[i
];
521 iface_constraint
= iface_constraint
.ResolveAsTypeTerminal (ec
, false);
522 if (iface_constraint
== null)
524 iface_constraints
[i
] = iface_constraint
;
527 if (class_constraint
!= null) {
528 class_constraint
= class_constraint
.ResolveAsTypeTerminal (ec
, false);
529 if (class_constraint
== null)
536 public override GenericParameterAttributes Attributes
{
537 get { return attrs; }
540 public override bool HasClassConstraint
{
541 get { return class_constraint != null; }
544 public override Type ClassConstraint
{
545 get { return class_constraint_type; }
548 public override Type
[] InterfaceConstraints
{
549 get { return iface_constraint_types; }
552 public override Type EffectiveBaseClass
{
553 get { return effective_base_type; }
556 public bool IsSubclassOf (Type t
)
558 if ((class_constraint_type
!= null) &&
559 class_constraint_type
.IsSubclassOf (t
))
562 if (iface_constraint_types
== null)
565 foreach (Type iface
in iface_constraint_types
) {
566 if (TypeManager
.IsSubclassOf (iface
, t
))
573 public Location Location
{
580 /// This is used when we're implementing a generic interface method.
581 /// Each method type parameter in implementing method must have the same
582 /// constraints than the corresponding type parameter in the interface
583 /// method. To do that, we're called on each of the implementing method's
586 public bool AreEqual (GenericConstraints gc
)
588 if (gc
.Attributes
!= attrs
)
591 if (HasClassConstraint
!= gc
.HasClassConstraint
)
593 if (HasClassConstraint
&& !TypeManager
.IsEqual (gc
.ClassConstraint
, ClassConstraint
))
596 int gc_icount
= gc
.InterfaceConstraints
!= null ?
597 gc
.InterfaceConstraints
.Length
: 0;
598 int icount
= InterfaceConstraints
!= null ?
599 InterfaceConstraints
.Length
: 0;
601 if (gc_icount
!= icount
)
604 for (int i
= 0; i
< gc
.InterfaceConstraints
.Length
; ++i
) {
605 Type iface
= gc
.InterfaceConstraints
[i
];
606 if (iface
.IsGenericType
)
607 iface
= iface
.GetGenericTypeDefinition ();
610 for (int ii
= 0; i
< InterfaceConstraints
.Length
; ++ii
) {
611 Type check
= InterfaceConstraints
[ii
];
612 if (check
.IsGenericType
)
613 check
= check
.GetGenericTypeDefinition ();
615 if (TypeManager
.IsEqual (iface
, check
)) {
628 public void VerifyClsCompliance ()
630 if (class_constraint_type
!= null && !AttributeTester
.IsClsCompliant (class_constraint_type
))
631 Warning_ConstrainIsNotClsCompliant (class_constraint_type
, class_constraint
.Location
);
633 if (iface_constraint_types
!= null) {
634 for (int i
= 0; i
< iface_constraint_types
.Length
; ++i
) {
635 if (!AttributeTester
.IsClsCompliant (iface_constraint_types
[i
]))
636 Warning_ConstrainIsNotClsCompliant (iface_constraint_types
[i
],
637 ((TypeExpr
)iface_constraints
[i
]).Location
);
642 void Warning_ConstrainIsNotClsCompliant (Type t
, Location loc
)
644 Report
.SymbolRelatedToPreviousError (t
);
645 Report
.Warning (3024, 1, loc
, "Constraint type `{0}' is not CLS-compliant",
646 TypeManager
.CSharpName (t
));
651 /// A type parameter from a generic type definition.
653 public class TypeParameter
: MemberCore
, IMemberContainer
655 static readonly string[] attribute_target
= new string [] { "type parameter" }
;
658 GenericConstraints gc
;
659 Constraints constraints
;
660 GenericTypeParameterBuilder type
;
661 MemberCache member_cache
;
664 public TypeParameter (DeclSpace parent
, DeclSpace decl
, string name
,
665 Constraints constraints
, Attributes attrs
, Variance variance
, Location loc
)
666 : base (parent
, new MemberName (name
, loc
), attrs
)
669 this.constraints
= constraints
;
670 this.variance
= variance
;
673 public GenericConstraints GenericConstraints
{
674 get { return gc != null ? gc : constraints; }
677 public Constraints Constraints
{
678 get { return constraints; }
681 public DeclSpace DeclSpace
{
685 public Variance Variance
{
686 get { return variance; }
694 /// This is the first method which is called during the resolving
695 /// process; we're called immediately after creating the type parameters
696 /// with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
699 /// We're either called from TypeContainer.DefineType() or from
700 /// GenericMethod.Define() (called from Method.Define()).
702 public void Define (GenericTypeParameterBuilder type
)
704 if (this.type
!= null)
705 throw new InvalidOperationException ();
708 TypeManager
.AddTypeParameter (type
, this);
711 public void ErrorInvalidVariance (MemberCore mc
, Variance expected
)
713 Report
.SymbolRelatedToPreviousError (mc
);
714 string input_variance
= Variance
== Variance
.Contravariant
? "contravariant" : "covariant";
715 string gtype_variance
;
717 case Variance
.Contravariant
: gtype_variance
= "contravariantly"; break;
718 case Variance
.Covariant
: gtype_variance
= "covariantly"; break;
719 default: gtype_variance
= "invariantly"; break;
722 Delegate d
= mc
as Delegate
;
723 string parameters
= d
!= null ? d
.Parameters
.GetSignatureForError () : "";
725 Report
.Error (1961, Location
,
726 "The {2} type parameter `{0}' must be {3} valid on `{1}{4}'",
727 GetSignatureForError (), mc
.GetSignatureForError (), input_variance
, gtype_variance
, parameters
);
731 /// This is the second method which is called during the resolving
732 /// process - in case of class type parameters, we're called from
733 /// TypeContainer.ResolveType() - after it resolved the class'es
734 /// base class and interfaces. For method type parameters, we're
735 /// called immediately after Define().
737 /// We're just resolving the constraints into expressions here, we
738 /// don't resolve them into actual types.
740 /// Note that in the special case of partial generic classes, we may be
741 /// called _before_ Define() and we may also be called multiple types.
743 public bool Resolve (DeclSpace ds
)
745 if (constraints
!= null) {
746 if (!constraints
.Resolve (ds
, this)) {
756 /// This is the third method which is called during the resolving
757 /// process. We're called immediately after calling DefineConstraints()
758 /// on all of the current class'es type parameters.
760 /// Our job is to resolve the constraints to actual types.
762 /// Note that we may have circular dependencies on type parameters - this
763 /// is why Resolve() and ResolveType() are separate.
765 public bool ResolveType (IResolveContext ec
)
767 if (constraints
!= null) {
768 if (!constraints
.ResolveTypes (ec
)) {
778 /// This is the fourth and last method which is called during the resolving
779 /// process. We're called after everything is fully resolved and actually
780 /// register the constraints with SRE and the TypeManager.
782 public bool DefineType (IResolveContext ec
)
784 return DefineType (ec
, null, null, false);
788 /// This is the fith and last method which is called during the resolving
789 /// process. We're called after everything is fully resolved and actually
790 /// register the constraints with SRE and the TypeManager.
792 /// The `builder', `implementing' and `is_override' arguments are only
793 /// applicable to method type parameters.
795 public bool DefineType (IResolveContext ec
, MethodBuilder builder
,
796 MethodInfo implementing
, bool is_override
)
798 if (!ResolveType (ec
))
801 if (implementing
!= null) {
802 if (is_override
&& (constraints
!= null)) {
803 Report
.Error (460, Location
,
804 "`{0}': Cannot specify constraints for overrides or explicit interface implementation methods",
805 TypeManager
.CSharpSignature (builder
));
809 MethodBase mb
= TypeManager
.DropGenericMethodArguments (implementing
);
811 int pos
= type
.GenericParameterPosition
;
812 Type mparam
= mb
.GetGenericArguments () [pos
];
813 GenericConstraints temp_gc
= ReflectionConstraints
.GetConstraints (mparam
);
816 gc
= new InflatedConstraints (temp_gc
, implementing
.DeclaringType
);
817 else if (constraints
!= null)
818 gc
= new InflatedConstraints (constraints
, implementing
.DeclaringType
);
821 if (constraints
!= null) {
824 else if (!constraints
.AreEqual (gc
))
827 if (!is_override
&& (temp_gc
!= null))
832 Report
.SymbolRelatedToPreviousError (implementing
);
835 425, Location
, "The constraints for type " +
836 "parameter `{0}' of method `{1}' must match " +
837 "the constraints for type parameter `{2}' " +
838 "of interface method `{3}'. Consider using " +
839 "an explicit interface implementation instead",
840 Name
, TypeManager
.CSharpSignature (builder
),
841 TypeManager
.CSharpName (mparam
), TypeManager
.CSharpSignature (mb
));
844 } else if (DeclSpace
is CompilerGeneratedClass
) {
845 TypeParameter
[] tparams
= DeclSpace
.TypeParameters
;
846 Type
[] types
= new Type
[tparams
.Length
];
847 for (int i
= 0; i
< tparams
.Length
; i
++)
848 types
[i
] = tparams
[i
].Type
;
850 if (constraints
!= null)
851 gc
= new InflatedConstraints (constraints
, types
);
853 gc
= (GenericConstraints
) constraints
;
856 SetConstraints (type
);
860 public void SetConstraints (GenericTypeParameterBuilder type
)
862 GenericParameterAttributes attr
= GenericParameterAttributes
.None
;
863 if (variance
== Variance
.Contravariant
)
864 attr
|= GenericParameterAttributes
.Contravariant
;
865 else if (variance
== Variance
.Covariant
)
866 attr
|= GenericParameterAttributes
.Covariant
;
869 if (gc
.HasClassConstraint
|| gc
.HasValueTypeConstraint
)
870 type
.SetBaseTypeConstraint (gc
.EffectiveBaseClass
);
872 attr
|= gc
.Attributes
;
873 type
.SetInterfaceConstraints (gc
.InterfaceConstraints
);
874 TypeManager
.RegisterBuilder (type
, gc
.InterfaceConstraints
);
877 type
.SetGenericParameterAttributes (attr
);
881 /// This is called for each part of a partial generic type definition.
883 /// If `new_constraints' is not null and we don't already have constraints,
884 /// they become our constraints. If we already have constraints, we must
885 /// check that they're the same.
888 public bool UpdateConstraints (IResolveContext ec
, Constraints new_constraints
)
891 throw new InvalidOperationException ();
893 if (new_constraints
== null)
896 if (!new_constraints
.Resolve (ec
, this))
898 if (!new_constraints
.ResolveTypes (ec
))
901 if (constraints
!= null)
902 return constraints
.AreEqual (new_constraints
);
904 constraints
= new_constraints
;
908 public override void Emit ()
910 if (OptAttributes
!= null)
911 OptAttributes
.Emit ();
916 public override string DocCommentHeader
{
918 throw new InvalidOperationException (
919 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
927 public override bool Define ()
932 public override void ApplyAttributeBuilder (Attribute a
, CustomAttributeBuilder cb
, PredefinedAttributes pa
)
934 type
.SetCustomAttribute (cb
);
937 public override AttributeTargets AttributeTargets
{
939 return AttributeTargets
.GenericParameter
;
943 public override string[] ValidAttributeTargets
{
945 return attribute_target
;
953 string IMemberContainer
.Name
{
957 MemberCache IMemberContainer
.BaseCache
{
962 if (gc
.EffectiveBaseClass
.BaseType
== null)
965 return TypeManager
.LookupMemberCache (gc
.EffectiveBaseClass
.BaseType
);
969 bool IMemberContainer
.IsInterface
{
970 get { return false; }
973 MemberList IMemberContainer
.GetMembers (MemberTypes mt
, BindingFlags bf
)
975 throw new NotSupportedException ();
978 public MemberCache MemberCache
{
980 if (member_cache
!= null)
986 Type
[] ifaces
= TypeManager
.ExpandInterfaces (gc
.InterfaceConstraints
);
987 member_cache
= new MemberCache (this, gc
.EffectiveBaseClass
, ifaces
);
993 public MemberList
FindMembers (MemberTypes mt
, BindingFlags bf
,
994 MemberFilter filter
, object criteria
)
997 return MemberList
.Empty
;
999 ArrayList members
= new ArrayList ();
1001 if (gc
.HasClassConstraint
) {
1002 MemberList list
= TypeManager
.FindMembers (
1003 gc
.ClassConstraint
, mt
, bf
, filter
, criteria
);
1005 members
.AddRange (list
);
1008 Type
[] ifaces
= TypeManager
.ExpandInterfaces (gc
.InterfaceConstraints
);
1009 foreach (Type t
in ifaces
) {
1010 MemberList list
= TypeManager
.FindMembers (
1011 t
, mt
, bf
, filter
, criteria
);
1013 members
.AddRange (list
);
1016 return new MemberList (members
);
1019 public bool IsSubclassOf (Type t
)
1021 if (type
.Equals (t
))
1024 if (constraints
!= null)
1025 return constraints
.IsSubclassOf (t
);
1030 public void InflateConstraints (Type declaring
)
1032 if (constraints
!= null)
1033 gc
= new InflatedConstraints (constraints
, declaring
);
1036 public override bool IsClsComplianceRequired ()
1041 protected class InflatedConstraints
: GenericConstraints
1043 GenericConstraints gc
;
1045 Type class_constraint
;
1046 Type
[] iface_constraints
;
1049 public InflatedConstraints (GenericConstraints gc
, Type declaring
)
1050 : this (gc
, TypeManager
.GetTypeArguments (declaring
))
1053 public InflatedConstraints (GenericConstraints gc
, Type
[] dargs
)
1058 ArrayList list
= new ArrayList ();
1059 if (gc
.HasClassConstraint
)
1060 list
.Add (inflate (gc
.ClassConstraint
));
1061 foreach (Type iface
in gc
.InterfaceConstraints
)
1062 list
.Add (inflate (iface
));
1064 bool has_class_constr
= false;
1065 if (list
.Count
> 0) {
1066 Type first
= (Type
) list
[0];
1067 has_class_constr
= !first
.IsGenericParameter
&& !first
.IsInterface
;
1070 if ((list
.Count
> 0) && has_class_constr
) {
1071 class_constraint
= (Type
) list
[0];
1072 iface_constraints
= new Type
[list
.Count
- 1];
1073 list
.CopyTo (1, iface_constraints
, 0, list
.Count
- 1);
1075 iface_constraints
= new Type
[list
.Count
];
1076 list
.CopyTo (iface_constraints
, 0);
1079 if (HasValueTypeConstraint
)
1080 base_type
= TypeManager
.value_type
;
1081 else if (class_constraint
!= null)
1082 base_type
= class_constraint
;
1084 base_type
= TypeManager
.object_type
;
1087 Type
inflate (Type t
)
1091 if (t
.IsGenericParameter
)
1092 return t
.GenericParameterPosition
< dargs
.Length
? dargs
[t
.GenericParameterPosition
] : t
;
1093 if (t
.IsGenericType
) {
1094 Type
[] args
= t
.GetGenericArguments ();
1095 Type
[] inflated
= new Type
[args
.Length
];
1097 for (int i
= 0; i
< args
.Length
; i
++)
1098 inflated
[i
] = inflate (args
[i
]);
1100 t
= t
.GetGenericTypeDefinition ();
1101 t
= t
.MakeGenericType (inflated
);
1107 public override string TypeParameter
{
1108 get { return gc.TypeParameter; }
1111 public override GenericParameterAttributes Attributes
{
1112 get { return gc.Attributes; }
1115 public override Type ClassConstraint
{
1116 get { return class_constraint; }
1119 public override Type EffectiveBaseClass
{
1120 get { return base_type; }
1123 public override Type
[] InterfaceConstraints
{
1124 get { return iface_constraints; }
1130 /// A TypeExpr which already resolved to a type parameter.
1132 public class TypeParameterExpr
: TypeExpr
{
1133 TypeParameter type_parameter
;
1135 public TypeParameter TypeParameter
{
1137 return type_parameter
;
1141 public TypeParameterExpr (TypeParameter type_parameter
, Location loc
)
1143 this.type_parameter
= type_parameter
;
1147 protected override TypeExpr
DoResolveAsTypeStep (IResolveContext ec
)
1149 throw new NotSupportedException ();
1152 public override FullNamedExpression
ResolveAsTypeStep (IResolveContext ec
, bool silent
)
1154 type
= type_parameter
.Type
;
1155 eclass
= ExprClass
.TypeParameter
;
1159 public override bool IsInterface
{
1160 get { return false; }
1163 public override bool CheckAccessLevel (DeclSpace ds
)
1170 // Tracks the type arguments when instantiating a generic type. It's used
1171 // by both type arguments and type parameters
1173 public class TypeArguments
{
1177 public TypeArguments ()
1179 args
= new ArrayList ();
1182 public TypeArguments (params FullNamedExpression
[] types
)
1184 this.args
= new ArrayList (types
);
1187 public void Add (FullNamedExpression type
)
1192 public void Add (TypeArguments new_args
)
1194 args
.AddRange (new_args
.args
);
1197 // TODO: Should be deleted
1198 public TypeParameterName
[] GetDeclarations ()
1200 return (TypeParameterName
[]) args
.ToArray (typeof (TypeParameterName
));
1204 /// We may only be used after Resolve() is called and return the fully
1207 public Type
[] Arguments
{
1219 public string GetSignatureForError()
1221 StringBuilder sb
= new StringBuilder();
1222 for (int i
= 0; i
< Count
; ++i
)
1224 Expression expr
= (Expression
)args
[i
];
1225 sb
.Append(expr
.GetSignatureForError());
1229 return sb
.ToString();
1233 /// Resolve the type arguments.
1235 public bool Resolve (IResolveContext ec
)
1238 return atypes
.Length
!= 0;
1240 int count
= args
.Count
;
1243 atypes
= new Type
[count
];
1245 for (int i
= 0; i
< count
; i
++){
1246 TypeExpr te
= ((FullNamedExpression
) args
[i
]).ResolveAsTypeTerminal (ec
, false);
1252 atypes
[i
] = te
.Type
;
1254 if (te
.Type
.IsSealed
&& te
.Type
.IsAbstract
) {
1255 Report
.Error (718, te
.Location
, "`{0}': static classes cannot be used as generic arguments",
1256 te
.GetSignatureForError ());
1260 if (te
.Type
.IsPointer
|| TypeManager
.IsSpecialType (te
.Type
)) {
1261 Report
.Error (306, te
.Location
,
1262 "The type `{0}' may not be used as a type argument",
1263 te
.GetSignatureForError ());
1269 atypes
= Type
.EmptyTypes
;
1274 public TypeArguments
Clone ()
1276 TypeArguments copy
= new TypeArguments ();
1277 foreach (Expression ta
in args
)
1284 public class TypeParameterName
: SimpleName
1286 Attributes attributes
;
1289 public TypeParameterName (string name
, Attributes attrs
, Location loc
)
1290 : this (name
, attrs
, Variance
.None
, loc
)
1294 public TypeParameterName (string name
, Attributes attrs
, Variance variance
, Location loc
)
1298 this.variance
= variance
;
1301 public Attributes OptAttributes
{
1307 public Variance Variance
{
1315 /// A reference expression to generic type
1317 class GenericTypeExpr
: TypeExpr
1320 Type
[] gen_params
; // TODO: Waiting for constrains check cleanup
1324 // Should be carefully used only with defined generic containers. Type parameters
1325 // can be used as type arguments in this case.
1327 // TODO: This could be GenericTypeExpr specialization
1329 public GenericTypeExpr (DeclSpace gType
, Location l
)
1331 open_type
= gType
.TypeBuilder
.GetGenericTypeDefinition ();
1333 args
= new TypeArguments ();
1334 foreach (TypeParameter type_param
in gType
.TypeParameters
)
1335 args
.Add (new TypeParameterExpr (type_param
, l
));
1341 /// Instantiate the generic type `t' with the type arguments `args'.
1342 /// Use this constructor if you already know the fully resolved
1345 public GenericTypeExpr (Type t
, TypeArguments args
, Location l
)
1347 open_type
= t
.GetGenericTypeDefinition ();
1353 public TypeArguments TypeArguments
{
1354 get { return args; }
1357 public override string GetSignatureForError ()
1359 return TypeManager
.CSharpName (type
);
1362 protected override TypeExpr
DoResolveAsTypeStep (IResolveContext ec
)
1364 if (eclass
!= ExprClass
.Invalid
)
1367 eclass
= ExprClass
.Type
;
1369 if (!args
.Resolve (ec
))
1372 gen_params
= open_type
.GetGenericArguments ();
1373 Type
[] atypes
= args
.Arguments
;
1375 if (atypes
.Length
!= gen_params
.Length
) {
1376 Namespace
.Error_InvalidNumberOfTypeArguments (open_type
, loc
);
1381 // Now bind the parameters
1383 type
= open_type
.MakeGenericType (atypes
);
1388 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1389 /// after fully resolving the constructed type.
1391 public bool CheckConstraints (IResolveContext ec
)
1393 return ConstraintChecker
.CheckConstraints (ec
, open_type
, gen_params
, args
.Arguments
, loc
);
1396 public override bool CheckAccessLevel (DeclSpace ds
)
1398 return ds
.CheckAccessLevel (open_type
);
1401 public override bool IsClass
{
1402 get { return open_type.IsClass; }
1405 public override bool IsValueType
{
1406 get { return TypeManager.IsStruct (open_type); }
1409 public override bool IsInterface
{
1410 get { return open_type.IsInterface; }
1413 public override bool IsSealed
{
1414 get { return open_type.IsSealed; }
1417 public override bool Equals (object obj
)
1419 GenericTypeExpr cobj
= obj
as GenericTypeExpr
;
1423 if ((type
== null) || (cobj
.type
== null))
1426 return type
== cobj
.type
;
1429 public override int GetHashCode ()
1431 return base.GetHashCode ();
1435 public abstract class ConstraintChecker
1437 protected readonly Type
[] gen_params
;
1438 protected readonly Type
[] atypes
;
1439 protected readonly Location loc
;
1441 protected ConstraintChecker (Type
[] gen_params
, Type
[] atypes
, Location loc
)
1443 this.gen_params
= gen_params
;
1444 this.atypes
= atypes
;
1449 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1450 /// after fully resolving the constructed type.
1452 public bool CheckConstraints (IResolveContext ec
)
1454 for (int i
= 0; i
< gen_params
.Length
; i
++) {
1455 if (!CheckConstraints (ec
, i
))
1462 protected bool CheckConstraints (IResolveContext ec
, int index
)
1464 Type atype
= atypes
[index
];
1465 Type ptype
= gen_params
[index
];
1470 Expression aexpr
= new EmptyExpression (atype
);
1472 GenericConstraints gc
= TypeManager
.GetTypeParameterConstraints (ptype
);
1476 bool is_class
, is_struct
;
1477 if (atype
.IsGenericParameter
) {
1478 GenericConstraints agc
= TypeManager
.GetTypeParameterConstraints (atype
);
1480 if (agc
is Constraints
)
1481 ((Constraints
) agc
).Resolve (ec
, null);
1482 is_class
= agc
.IsReferenceType
;
1483 is_struct
= agc
.IsValueType
;
1485 is_class
= is_struct
= false;
1488 is_class
= TypeManager
.IsReferenceType (atype
);
1489 is_struct
= TypeManager
.IsValueType (atype
) && !TypeManager
.IsNullableType (atype
);
1493 // First, check the `class' and `struct' constraints.
1495 if (gc
.HasReferenceTypeConstraint
&& !is_class
) {
1496 Report
.Error (452, loc
, "The type `{0}' must be " +
1497 "a reference type in order to use it " +
1498 "as type parameter `{1}' in the " +
1499 "generic type or method `{2}'.",
1500 TypeManager
.CSharpName (atype
),
1501 TypeManager
.CSharpName (ptype
),
1502 GetSignatureForError ());
1504 } else if (gc
.HasValueTypeConstraint
&& !is_struct
) {
1505 Report
.Error (453, loc
, "The type `{0}' must be a " +
1506 "non-nullable value type in order to use it " +
1507 "as type parameter `{1}' in the " +
1508 "generic type or method `{2}'.",
1509 TypeManager
.CSharpName (atype
),
1510 TypeManager
.CSharpName (ptype
),
1511 GetSignatureForError ());
1516 // The class constraint comes next.
1518 if (gc
.HasClassConstraint
) {
1519 if (!CheckConstraint (ec
, ptype
, aexpr
, gc
.ClassConstraint
))
1524 // Now, check the interface constraints.
1526 if (gc
.InterfaceConstraints
!= null) {
1527 foreach (Type it
in gc
.InterfaceConstraints
) {
1528 if (!CheckConstraint (ec
, ptype
, aexpr
, it
))
1534 // Finally, check the constructor constraint.
1537 if (!gc
.HasConstructorConstraint
)
1540 if (TypeManager
.IsBuiltinType (atype
) || TypeManager
.IsValueType (atype
))
1543 if (HasDefaultConstructor (atype
))
1546 Report_SymbolRelatedToPreviousError ();
1547 Report
.SymbolRelatedToPreviousError (atype
);
1548 Report
.Error (310, loc
, "The type `{0}' must have a public " +
1549 "parameterless constructor in order to use it " +
1550 "as parameter `{1}' in the generic type or " +
1552 TypeManager
.CSharpName (atype
),
1553 TypeManager
.CSharpName (ptype
),
1554 GetSignatureForError ());
1558 protected bool CheckConstraint (IResolveContext ec
, Type ptype
, Expression expr
,
1561 if (TypeManager
.HasGenericArguments (ctype
)) {
1562 Type
[] types
= TypeManager
.GetTypeArguments (ctype
);
1564 TypeArguments new_args
= new TypeArguments ();
1566 for (int i
= 0; i
< types
.Length
; i
++) {
1569 if (t
.IsGenericParameter
) {
1570 int pos
= t
.GenericParameterPosition
;
1573 new_args
.Add (new TypeExpression (t
, loc
));
1576 TypeExpr ct
= new GenericTypeExpr (ctype
, new_args
, loc
);
1577 if (ct
.ResolveAsTypeStep (ec
, false) == null)
1580 } else if (ctype
.IsGenericParameter
) {
1581 int pos
= ctype
.GenericParameterPosition
;
1582 if (ctype
.DeclaringMethod
== null) {
1586 ctype
= atypes
[pos
];
1590 if (Convert
.ImplicitStandardConversionExists (expr
, ctype
))
1593 Report_SymbolRelatedToPreviousError ();
1594 Report
.SymbolRelatedToPreviousError (expr
.Type
);
1596 if (TypeManager
.IsNullableType (expr
.Type
) && ctype
.IsInterface
) {
1597 Report
.Error (313, loc
,
1598 "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. " +
1599 "The nullable type `{0}' never satisfies interface constraint of type `{3}'",
1600 TypeManager
.CSharpName (expr
.Type
), TypeManager
.CSharpName (ptype
),
1601 GetSignatureForError (), TypeManager
.CSharpName (ctype
));
1603 Report
.Error (309, loc
,
1604 "The type `{0}' must be convertible to `{1}' in order to " +
1605 "use it as parameter `{2}' in the generic type or method `{3}'",
1606 TypeManager
.CSharpName (expr
.Type
), TypeManager
.CSharpName (ctype
),
1607 TypeManager
.CSharpName (ptype
), GetSignatureForError ());
1612 static bool HasDefaultConstructor (Type atype
)
1614 TypeParameter tparam
= TypeManager
.LookupTypeParameter (atype
);
1615 if (tparam
!= null) {
1616 if (tparam
.GenericConstraints
== null)
1619 return tparam
.GenericConstraints
.HasConstructorConstraint
||
1620 tparam
.GenericConstraints
.HasValueTypeConstraint
;
1623 if (atype
.IsAbstract
)
1627 atype
= TypeManager
.DropGenericTypeArguments (atype
);
1628 if (atype
is TypeBuilder
) {
1629 TypeContainer tc
= TypeManager
.LookupTypeContainer (atype
);
1630 if (tc
.InstanceConstructors
== null) {
1631 atype
= atype
.BaseType
;
1635 foreach (Constructor c
in tc
.InstanceConstructors
) {
1636 if ((c
.ModFlags
& Modifiers
.PUBLIC
) == 0)
1638 if ((c
.Parameters
.FixedParameters
!= null) &&
1639 (c
.Parameters
.FixedParameters
.Length
!= 0))
1641 if (c
.Parameters
.HasArglist
|| c
.Parameters
.HasParams
)
1648 MemberInfo
[] list
= TypeManager
.MemberLookup (null, null, atype
, MemberTypes
.Constructor
,
1649 BindingFlags
.Public
| BindingFlags
.Instance
| BindingFlags
.DeclaredOnly
,
1650 ConstructorInfo
.ConstructorName
, null);
1655 foreach (MethodBase mb
in list
) {
1656 AParametersCollection pd
= TypeManager
.GetParameterData (mb
);
1664 protected abstract string GetSignatureForError ();
1665 protected abstract void Report_SymbolRelatedToPreviousError ();
1667 public static bool CheckConstraints (EmitContext ec
, MethodBase definition
,
1668 MethodBase instantiated
, Location loc
)
1670 MethodConstraintChecker checker
= new MethodConstraintChecker (
1671 definition
, definition
.GetGenericArguments (),
1672 instantiated
.GetGenericArguments (), loc
);
1674 return checker
.CheckConstraints (ec
);
1677 public static bool CheckConstraints (IResolveContext ec
, Type gt
, Type
[] gen_params
,
1678 Type
[] atypes
, Location loc
)
1680 TypeConstraintChecker checker
= new TypeConstraintChecker (
1681 gt
, gen_params
, atypes
, loc
);
1683 return checker
.CheckConstraints (ec
);
1686 protected class MethodConstraintChecker
: ConstraintChecker
1688 MethodBase definition
;
1690 public MethodConstraintChecker (MethodBase definition
, Type
[] gen_params
,
1691 Type
[] atypes
, Location loc
)
1692 : base (gen_params
, atypes
, loc
)
1694 this.definition
= definition
;
1697 protected override string GetSignatureForError ()
1699 return TypeManager
.CSharpSignature (definition
);
1702 protected override void Report_SymbolRelatedToPreviousError ()
1704 Report
.SymbolRelatedToPreviousError (definition
);
1708 protected class TypeConstraintChecker
: ConstraintChecker
1712 public TypeConstraintChecker (Type gt
, Type
[] gen_params
, Type
[] atypes
,
1714 : base (gen_params
, atypes
, loc
)
1719 protected override string GetSignatureForError ()
1721 return TypeManager
.CSharpName (gt
);
1724 protected override void Report_SymbolRelatedToPreviousError ()
1726 Report
.SymbolRelatedToPreviousError (gt
);
1732 /// A generic method definition.
1734 public class GenericMethod
: DeclSpace
1736 FullNamedExpression return_type
;
1737 ParametersCompiled parameters
;
1739 public GenericMethod (NamespaceEntry ns
, DeclSpace parent
, MemberName name
,
1740 FullNamedExpression return_type
, ParametersCompiled parameters
)
1741 : base (ns
, parent
, name
, null)
1743 this.return_type
= return_type
;
1744 this.parameters
= parameters
;
1747 public override TypeBuilder
DefineType ()
1749 throw new Exception ();
1752 public override bool Define ()
1754 for (int i
= 0; i
< TypeParameters
.Length
; i
++)
1755 if (!TypeParameters
[i
].Resolve (this))
1762 /// Define and resolve the type parameters.
1763 /// We're called from Method.Define().
1765 public bool Define (MethodOrOperator m
)
1767 TypeParameterName
[] names
= MemberName
.TypeArguments
.GetDeclarations ();
1768 string[] snames
= new string [names
.Length
];
1769 for (int i
= 0; i
< names
.Length
; i
++) {
1770 string type_argument_name
= names
[i
].Name
;
1771 int idx
= parameters
.GetParameterIndexByName (type_argument_name
);
1775 b
= new Block (null);
1777 b
.Error_AlreadyDeclaredTypeParameter (parameters
[i
].Location
,
1778 type_argument_name
, "method parameter");
1781 snames
[i
] = type_argument_name
;
1784 GenericTypeParameterBuilder
[] gen_params
= m
.MethodBuilder
.DefineGenericParameters (snames
);
1785 for (int i
= 0; i
< TypeParameters
.Length
; i
++)
1786 TypeParameters
[i
].Define (gen_params
[i
]);
1791 for (int i
= 0; i
< TypeParameters
.Length
; i
++) {
1792 if (!TypeParameters
[i
].ResolveType (this))
1800 /// We're called from MethodData.Define() after creating the MethodBuilder.
1802 public bool DefineType (EmitContext ec
, MethodBuilder mb
,
1803 MethodInfo implementing
, bool is_override
)
1805 for (int i
= 0; i
< TypeParameters
.Length
; i
++)
1806 if (!TypeParameters
[i
].DefineType (
1807 ec
, mb
, implementing
, is_override
))
1810 bool ok
= parameters
.Resolve (ec
);
1812 if ((return_type
!= null) && (return_type
.ResolveAsTypeTerminal (ec
, false) == null))
1818 public void EmitAttributes ()
1820 for (int i
= 0; i
< TypeParameters
.Length
; i
++)
1821 TypeParameters
[i
].Emit ();
1823 if (OptAttributes
!= null)
1824 OptAttributes
.Emit ();
1827 public override MemberList
FindMembers (MemberTypes mt
, BindingFlags bf
,
1828 MemberFilter filter
, object criteria
)
1830 throw new Exception ();
1833 public override MemberCache MemberCache
{
1839 public override AttributeTargets AttributeTargets
{
1841 return AttributeTargets
.Method
| AttributeTargets
.ReturnValue
;
1845 public override string DocCommentHeader
{
1846 get { return "M:"; }
1849 public new void VerifyClsCompliance ()
1851 foreach (TypeParameter tp
in TypeParameters
) {
1852 if (tp
.Constraints
== null)
1855 tp
.Constraints
.VerifyClsCompliance ();
1860 public partial class TypeManager
1862 static public Type activator_type
;
1864 public static TypeContainer
LookupGenericTypeContainer (Type t
)
1866 t
= DropGenericTypeArguments (t
);
1867 return LookupTypeContainer (t
);
1870 public static Variance
GetTypeParameterVariance (Type type
)
1872 TypeParameter tparam
= LookupTypeParameter (type
);
1874 return tparam
.Variance
;
1876 switch (type
.GenericParameterAttributes
& GenericParameterAttributes
.VarianceMask
) {
1877 case GenericParameterAttributes
.Covariant
:
1878 return Variance
.Covariant
;
1879 case GenericParameterAttributes
.Contravariant
:
1880 return Variance
.Contravariant
;
1882 return Variance
.None
;
1886 public static Variance
CheckTypeVariance (Type t
, Variance expected
, MemberCore member
)
1888 TypeParameter tp
= LookupTypeParameter (t
);
1890 Variance v
= tp
.Variance
;
1891 if (expected
== Variance
.None
&& v
!= expected
||
1892 expected
== Variance
.Covariant
&& v
== Variance
.Contravariant
||
1893 expected
== Variance
.Contravariant
&& v
== Variance
.Covariant
)
1894 tp
.ErrorInvalidVariance (member
, expected
);
1899 if (t
.IsGenericType
) {
1900 Type
[] targs_definition
= GetTypeArguments (DropGenericTypeArguments (t
));
1901 Type
[] targs
= GetTypeArguments (t
);
1902 for (int i
= 0; i
< targs_definition
.Length
; ++i
) {
1903 Variance v
= GetTypeParameterVariance (targs_definition
[i
]);
1904 CheckTypeVariance (targs
[i
], (Variance
) ((int)v
* (int)expected
), member
);
1911 return CheckTypeVariance (GetElementType (t
), expected
, member
);
1913 return Variance
.None
;
1916 public static bool IsVariantOf (Type type1
, Type type2
)
1918 if (!type1
.IsGenericType
|| !type2
.IsGenericType
)
1921 Type generic_target_type
= DropGenericTypeArguments (type2
);
1922 if (DropGenericTypeArguments (type1
) != generic_target_type
)
1925 Type
[] t1
= GetTypeArguments (type1
);
1926 Type
[] t2
= GetTypeArguments (type2
);
1927 Type
[] targs_definition
= GetTypeArguments (generic_target_type
);
1928 for (int i
= 0; i
< targs_definition
.Length
; ++i
) {
1929 Variance v
= GetTypeParameterVariance (targs_definition
[i
]);
1930 if (v
== Variance
.None
) {
1936 if (v
== Variance
.Covariant
) {
1937 if (!Convert
.ImplicitReferenceConversionExists (new EmptyExpression (t1
[i
]), t2
[i
]))
1939 } else if (!Convert
.ImplicitReferenceConversionExists (new EmptyExpression (t2
[i
]), t1
[i
])) {
1948 /// Check whether `a' and `b' may become equal generic types.
1949 /// The algorithm to do that is a little bit complicated.
1951 public static bool MayBecomeEqualGenericTypes (Type a
, Type b
, Type
[] class_inferred
,
1952 Type
[] method_inferred
)
1954 if (a
.IsGenericParameter
) {
1956 // If a is an array of a's type, they may never
1960 b
= GetElementType (b
);
1966 // If b is a generic parameter or an actual type,
1967 // they may become equal:
1969 // class X<T,U> : I<T>, I<U>
1970 // class X<T> : I<T>, I<float>
1972 if (b
.IsGenericParameter
|| !b
.IsGenericType
) {
1973 int pos
= a
.GenericParameterPosition
;
1974 Type
[] args
= a
.DeclaringMethod
!= null ? method_inferred
: class_inferred
;
1975 if (args
[pos
] == null) {
1980 return args
[pos
] == a
;
1984 // We're now comparing a type parameter with a
1985 // generic instance. They may become equal unless
1986 // the type parameter appears anywhere in the
1987 // generic instance:
1989 // class X<T,U> : I<T>, I<X<U>>
1990 // -> error because you could instanciate it as
1993 // class X<T> : I<T>, I<X<T>> -> ok
1996 Type
[] bargs
= GetTypeArguments (b
);
1997 for (int i
= 0; i
< bargs
.Length
; i
++) {
1998 if (a
.Equals (bargs
[i
]))
2005 if (b
.IsGenericParameter
)
2006 return MayBecomeEqualGenericTypes (b
, a
, class_inferred
, method_inferred
);
2009 // At this point, neither a nor b are a type parameter.
2011 // If one of them is a generic instance, let
2012 // MayBecomeEqualGenericInstances() compare them (if the
2013 // other one is not a generic instance, they can never
2017 if (a
.IsGenericType
|| b
.IsGenericType
)
2018 return MayBecomeEqualGenericInstances (a
, b
, class_inferred
, method_inferred
);
2021 // If both of them are arrays.
2024 if (a
.IsArray
&& b
.IsArray
) {
2025 if (a
.GetArrayRank () != b
.GetArrayRank ())
2028 a
= GetElementType (a
);
2029 b
= GetElementType (b
);
2031 return MayBecomeEqualGenericTypes (a
, b
, class_inferred
, method_inferred
);
2035 // Ok, two ordinary types.
2038 return a
.Equals (b
);
2042 // Checks whether two generic instances may become equal for some
2043 // particular instantiation (26.3.1).
2045 public static bool MayBecomeEqualGenericInstances (Type a
, Type b
,
2046 Type
[] class_inferred
,
2047 Type
[] method_inferred
)
2049 if (!a
.IsGenericType
|| !b
.IsGenericType
)
2051 if (a
.GetGenericTypeDefinition () != b
.GetGenericTypeDefinition ())
2054 return MayBecomeEqualGenericInstances (
2055 GetTypeArguments (a
), GetTypeArguments (b
), class_inferred
, method_inferred
);
2058 public static bool MayBecomeEqualGenericInstances (Type
[] aargs
, Type
[] bargs
,
2059 Type
[] class_inferred
,
2060 Type
[] method_inferred
)
2062 if (aargs
.Length
!= bargs
.Length
)
2065 for (int i
= 0; i
< aargs
.Length
; i
++) {
2066 if (!MayBecomeEqualGenericTypes (aargs
[i
], bargs
[i
], class_inferred
, method_inferred
))
2074 /// Type inference. Try to infer the type arguments from `method',
2075 /// which is invoked with the arguments `arguments'. This is used
2076 /// when resolving an Invocation or a DelegateInvocation and the user
2077 /// did not explicitly specify type arguments.
2079 public static int InferTypeArguments (EmitContext ec
, Arguments arguments
, ref MethodBase method
)
2081 ATypeInference ti
= ATypeInference
.CreateInstance (arguments
);
2082 Type
[] i_args
= ti
.InferMethodArguments (ec
, method
);
2084 return ti
.InferenceScore
;
2086 if (i_args
.Length
== 0)
2089 method
= ((MethodInfo
) method
).MakeGenericMethod (i_args
);
2096 public static bool InferTypeArguments (AParametersCollection param
, ref MethodBase method
)
2098 if (!TypeManager
.IsGenericMethod (method
))
2101 ATypeInference ti
= ATypeInference
.CreateInstance (DelegateCreation
.CreateDelegateMethodArguments (param
, Location
.Null
));
2102 Type
[] i_args
= ti
.InferDelegateArguments (method
);
2106 method
= ((MethodInfo
) method
).MakeGenericMethod (i_args
);
2111 abstract class ATypeInference
2113 protected readonly Arguments arguments
;
2114 protected readonly int arg_count
;
2116 protected ATypeInference (Arguments arguments
)
2118 this.arguments
= arguments
;
2119 if (arguments
!= null)
2120 arg_count
= arguments
.Count
;
2123 public static ATypeInference
CreateInstance (Arguments arguments
)
2125 return new TypeInference (arguments
);
2128 public virtual int InferenceScore
{
2130 return int.MaxValue
;
2134 public abstract Type
[] InferMethodArguments (EmitContext ec
, MethodBase method
);
2135 public abstract Type
[] InferDelegateArguments (MethodBase method
);
2139 // Implements C# type inference
2141 class TypeInference
: ATypeInference
2144 // Tracks successful rate of type inference
2146 int score
= int.MaxValue
;
2148 public TypeInference (Arguments arguments
)
2153 public override int InferenceScore
{
2159 public override Type
[] InferDelegateArguments (MethodBase method
)
2161 AParametersCollection pd
= TypeManager
.GetParameterData (method
);
2162 if (arg_count
!= pd
.Count
)
2165 Type
[] d_gargs
= method
.GetGenericArguments ();
2166 TypeInferenceContext context
= new TypeInferenceContext (d_gargs
);
2168 // A lower-bound inference is made from each argument type Uj of D
2169 // to the corresponding parameter type Tj of M
2170 for (int i
= 0; i
< arg_count
; ++i
) {
2171 Type t
= pd
.Types
[i
];
2172 if (!t
.IsGenericParameter
)
2175 context
.LowerBoundInference (arguments
[i
].Expr
.Type
, t
);
2178 if (!context
.FixAllTypes ())
2181 return context
.InferredTypeArguments
;
2184 public override Type
[] InferMethodArguments (EmitContext ec
, MethodBase method
)
2186 Type
[] method_generic_args
= method
.GetGenericArguments ();
2187 TypeInferenceContext context
= new TypeInferenceContext (method_generic_args
);
2188 if (!context
.UnfixedVariableExists
)
2189 return Type
.EmptyTypes
;
2191 AParametersCollection pd
= TypeManager
.GetParameterData (method
);
2192 if (!InferInPhases (ec
, context
, pd
))
2195 return context
.InferredTypeArguments
;
2199 // Implements method type arguments inference
2201 bool InferInPhases (EmitContext ec
, TypeInferenceContext tic
, AParametersCollection methodParameters
)
2203 int params_arguments_start
;
2204 if (methodParameters
.HasParams
) {
2205 params_arguments_start
= methodParameters
.Count
- 1;
2207 params_arguments_start
= arg_count
;
2210 Type
[] ptypes
= methodParameters
.Types
;
2213 // The first inference phase
2215 Type method_parameter
= null;
2216 for (int i
= 0; i
< arg_count
; i
++) {
2217 Argument a
= arguments
[i
];
2221 if (i
< params_arguments_start
) {
2222 method_parameter
= methodParameters
.Types
[i
];
2223 } else if (i
== params_arguments_start
) {
2224 if (arg_count
== params_arguments_start
+ 1 && TypeManager
.HasElementType (a
.Type
))
2225 method_parameter
= methodParameters
.Types
[params_arguments_start
];
2227 method_parameter
= TypeManager
.GetElementType (methodParameters
.Types
[params_arguments_start
]);
2229 ptypes
= (Type
[]) ptypes
.Clone ();
2230 ptypes
[i
] = method_parameter
;
2234 // When a lambda expression, an anonymous method
2235 // is used an explicit argument type inference takes a place
2237 AnonymousMethodExpression am
= a
.Expr
as AnonymousMethodExpression
;
2239 if (am
.ExplicitTypeInference (tic
, method_parameter
))
2245 score
-= tic
.ExactInference (a
.Type
, method_parameter
);
2249 if (a
.Expr
.Type
== TypeManager
.null_type
)
2252 if (TypeManager
.IsValueType (method_parameter
)) {
2253 score
-= tic
.LowerBoundInference (a
.Type
, method_parameter
);
2258 // Otherwise an output type inference is made
2260 score
-= tic
.OutputTypeInference (ec
, a
.Expr
, method_parameter
);
2264 // Part of the second phase but because it happens only once
2265 // we don't need to call it in cycle
2267 bool fixed_any
= false;
2268 if (!tic
.FixIndependentTypeArguments (ptypes
, ref fixed_any
))
2271 return DoSecondPhase (ec
, tic
, ptypes
, !fixed_any
);
2274 bool DoSecondPhase (EmitContext ec
, TypeInferenceContext tic
, Type
[] methodParameters
, bool fixDependent
)
2276 bool fixed_any
= false;
2277 if (fixDependent
&& !tic
.FixDependentTypes (ref fixed_any
))
2280 // If no further unfixed type variables exist, type inference succeeds
2281 if (!tic
.UnfixedVariableExists
)
2284 if (!fixed_any
&& fixDependent
)
2287 // For all arguments where the corresponding argument output types
2288 // contain unfixed type variables but the input types do not,
2289 // an output type inference is made
2290 for (int i
= 0; i
< arg_count
; i
++) {
2292 // Align params arguments
2293 Type t_i
= methodParameters
[i
>= methodParameters
.Length
? methodParameters
.Length
- 1: i
];
2295 if (!TypeManager
.IsDelegateType (t_i
)) {
2296 if (TypeManager
.DropGenericTypeArguments (t_i
) != TypeManager
.expression_type
)
2299 t_i
= t_i
.GetGenericArguments () [0];
2302 MethodInfo mi
= Delegate
.GetInvokeMethod (t_i
, t_i
);
2303 Type rtype
= mi
.ReturnType
;
2306 // Blablabla, because reflection does not work with dynamic types
2307 Type
[] g_args
= t_i
.GetGenericArguments ();
2308 rtype
= g_args
[rtype
.GenericParameterPosition
];
2311 if (tic
.IsReturnTypeNonDependent (mi
, rtype
))
2312 score
-= tic
.OutputTypeInference (ec
, arguments
[i
].Expr
, t_i
);
2316 return DoSecondPhase (ec
, tic
, methodParameters
, true);
2320 public class TypeInferenceContext
2331 public readonly Type Type
;
2332 public readonly BoundKind Kind
;
2334 public BoundInfo (Type type
, BoundKind kind
)
2340 public override int GetHashCode ()
2342 return Type
.GetHashCode ();
2345 public override bool Equals (object obj
)
2347 BoundInfo a
= (BoundInfo
) obj
;
2348 return Type
== a
.Type
&& Kind
== a
.Kind
;
2352 readonly Type
[] unfixed_types
;
2353 readonly Type
[] fixed_types
;
2354 readonly ArrayList
[] bounds
;
2357 public TypeInferenceContext (Type
[] typeArguments
)
2359 if (typeArguments
.Length
== 0)
2360 throw new ArgumentException ("Empty generic arguments");
2362 fixed_types
= new Type
[typeArguments
.Length
];
2363 for (int i
= 0; i
< typeArguments
.Length
; ++i
) {
2364 if (typeArguments
[i
].IsGenericParameter
) {
2365 if (bounds
== null) {
2366 bounds
= new ArrayList
[typeArguments
.Length
];
2367 unfixed_types
= new Type
[typeArguments
.Length
];
2369 unfixed_types
[i
] = typeArguments
[i
];
2371 fixed_types
[i
] = typeArguments
[i
];
2376 public Type
[] InferredTypeArguments
{
2382 void AddToBounds (BoundInfo bound
, int index
)
2385 // Some types cannot be used as type arguments
2387 if (bound
.Type
== TypeManager
.void_type
|| bound
.Type
.IsPointer
)
2390 ArrayList a
= bounds
[index
];
2392 a
= new ArrayList ();
2395 if (a
.Contains (bound
))
2400 // SPEC: does not cover type inference using constraints
2402 //if (TypeManager.IsGenericParameter (t)) {
2403 // GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
2404 // if (constraints != null) {
2405 // //if (constraints.EffectiveBaseClass != null)
2406 // // t = constraints.EffectiveBaseClass;
2412 bool AllTypesAreFixed (Type
[] types
)
2414 foreach (Type t
in types
) {
2415 if (t
.IsGenericParameter
) {
2421 if (t
.IsGenericType
)
2422 return AllTypesAreFixed (t
.GetGenericArguments ());
2429 // 26.3.3.8 Exact Inference
2431 public int ExactInference (Type u
, Type v
)
2433 // If V is an array type
2438 if (u
.GetArrayRank () != v
.GetArrayRank ())
2441 return ExactInference (TypeManager
.GetElementType (u
), TypeManager
.GetElementType (v
));
2444 // If V is constructed type and U is constructed type
2445 if (v
.IsGenericType
&& !v
.IsGenericTypeDefinition
) {
2446 if (!u
.IsGenericType
)
2449 Type
[] ga_u
= u
.GetGenericArguments ();
2450 Type
[] ga_v
= v
.GetGenericArguments ();
2451 if (ga_u
.Length
!= ga_v
.Length
)
2455 for (int i
= 0; i
< ga_u
.Length
; ++i
)
2456 score
+= ExactInference (ga_u
[i
], ga_v
[i
]);
2458 return score
> 0 ? 1 : 0;
2461 // If V is one of the unfixed type arguments
2462 int pos
= IsUnfixed (v
);
2466 AddToBounds (new BoundInfo (u
, BoundKind
.Exact
), pos
);
2470 public bool FixAllTypes ()
2472 for (int i
= 0; i
< unfixed_types
.Length
; ++i
) {
2480 // All unfixed type variables Xi are fixed for which all of the following hold:
2481 // a, There is at least one type variable Xj that depends on Xi
2482 // b, Xi has a non-empty set of bounds
2484 public bool FixDependentTypes (ref bool fixed_any
)
2486 for (int i
= 0; i
< unfixed_types
.Length
; ++i
) {
2487 if (unfixed_types
[i
] == null)
2490 if (bounds
[i
] == null)
2503 // All unfixed type variables Xi which depend on no Xj are fixed
2505 public bool FixIndependentTypeArguments (Type
[] methodParameters
, ref bool fixed_any
)
2507 ArrayList types_to_fix
= new ArrayList (unfixed_types
);
2508 for (int i
= 0; i
< methodParameters
.Length
; ++i
) {
2509 Type t
= methodParameters
[i
];
2511 if (!TypeManager
.IsDelegateType (t
)) {
2512 if (TypeManager
.DropGenericTypeArguments (t
) != TypeManager
.expression_type
)
2515 t
= t
.GetGenericArguments () [0];
2518 if (t
.IsGenericParameter
)
2521 MethodInfo invoke
= Delegate
.GetInvokeMethod (t
, t
);
2522 Type rtype
= invoke
.ReturnType
;
2523 if (!rtype
.IsGenericParameter
&& !rtype
.IsGenericType
)
2527 // Blablabla, because reflection does not work with dynamic types
2528 if (rtype
.IsGenericParameter
) {
2529 Type
[] g_args
= t
.GetGenericArguments ();
2530 rtype
= g_args
[rtype
.GenericParameterPosition
];
2533 // Remove dependent types, they cannot be fixed yet
2534 RemoveDependentTypes (types_to_fix
, rtype
);
2537 foreach (Type t
in types_to_fix
) {
2541 int idx
= IsUnfixed (t
);
2542 if (idx
>= 0 && !FixType (idx
)) {
2547 fixed_any
= types_to_fix
.Count
> 0;
2554 public bool FixType (int i
)
2556 // It's already fixed
2557 if (unfixed_types
[i
] == null)
2558 throw new InternalErrorException ("Type argument has been already fixed");
2563 ArrayList candidates
= (ArrayList
)bounds
[i
];
2564 if (candidates
== null)
2567 if (candidates
.Count
== 1) {
2568 unfixed_types
[i
] = null;
2569 fixed_types
[i
] = ((BoundInfo
) candidates
[0]).Type
;
2574 // Determines a unique type from which there is
2575 // a standard implicit conversion to all the other
2578 Type best_candidate
= null;
2580 int candidates_count
= candidates
.Count
;
2581 for (int ci
= 0; ci
< candidates_count
; ++ci
) {
2582 BoundInfo bound
= (BoundInfo
)candidates
[ci
];
2583 for (cii
= 0; cii
< candidates_count
; ++cii
) {
2587 BoundInfo cbound
= (BoundInfo
) candidates
[cii
];
2589 // Same type parameters with different bounds
2590 if (cbound
.Type
== bound
.Type
) {
2591 if (bound
.Kind
!= BoundKind
.Exact
)
2597 if (bound
.Kind
== BoundKind
.Exact
|| cbound
.Kind
== BoundKind
.Exact
) {
2598 if (cbound
.Kind
!= BoundKind
.Exact
) {
2599 if (!Convert
.ImplicitConversionExists (null, new TypeExpression (cbound
.Type
, Location
.Null
), bound
.Type
)) {
2606 if (bound
.Kind
!= BoundKind
.Exact
) {
2607 if (!Convert
.ImplicitConversionExists (null, new TypeExpression (bound
.Type
, Location
.Null
), cbound
.Type
)) {
2618 if (bound
.Kind
== BoundKind
.Lower
) {
2619 if (!Convert
.ImplicitConversionExists (null, new TypeExpression (cbound
.Type
, Location
.Null
), bound
.Type
)) {
2623 if (!Convert
.ImplicitConversionExists (null, new TypeExpression (bound
.Type
, Location
.Null
), cbound
.Type
)) {
2629 if (cii
!= candidates_count
)
2632 if (best_candidate
!= null && best_candidate
!= bound
.Type
)
2635 best_candidate
= bound
.Type
;
2638 if (best_candidate
== null)
2641 unfixed_types
[i
] = null;
2642 fixed_types
[i
] = best_candidate
;
2647 // Uses inferred types to inflate delegate type argument
2649 public Type
InflateGenericArgument (Type parameter
)
2651 if (parameter
.IsGenericParameter
) {
2653 // Inflate method generic argument (MVAR) only
2655 if (parameter
.DeclaringMethod
== null)
2658 return fixed_types
[parameter
.GenericParameterPosition
];
2661 if (parameter
.IsGenericType
) {
2662 Type
[] parameter_targs
= parameter
.GetGenericArguments ();
2663 for (int ii
= 0; ii
< parameter_targs
.Length
; ++ii
) {
2664 parameter_targs
[ii
] = InflateGenericArgument (parameter_targs
[ii
]);
2666 return parameter
.GetGenericTypeDefinition ().MakeGenericType (parameter_targs
);
2673 // Tests whether all delegate input arguments are fixed and generic output type
2674 // requires output type inference
2676 public bool IsReturnTypeNonDependent (MethodInfo invoke
, Type returnType
)
2678 if (returnType
.IsGenericParameter
) {
2679 if (IsFixed (returnType
))
2681 } else if (returnType
.IsGenericType
) {
2682 if (TypeManager
.IsDelegateType (returnType
)) {
2683 invoke
= Delegate
.GetInvokeMethod (returnType
, returnType
);
2684 return IsReturnTypeNonDependent (invoke
, invoke
.ReturnType
);
2687 Type
[] g_args
= returnType
.GetGenericArguments ();
2689 // At least one unfixed return type has to exist
2690 if (AllTypesAreFixed (g_args
))
2696 // All generic input arguments have to be fixed
2697 AParametersCollection d_parameters
= TypeManager
.GetParameterData (invoke
);
2698 return AllTypesAreFixed (d_parameters
.Types
);
2701 bool IsFixed (Type type
)
2703 return IsUnfixed (type
) == -1;
2706 int IsUnfixed (Type type
)
2708 if (!type
.IsGenericParameter
)
2711 //return unfixed_types[type.GenericParameterPosition] != null;
2712 for (int i
= 0; i
< unfixed_types
.Length
; ++i
) {
2713 if (unfixed_types
[i
] == type
)
2721 // 26.3.3.9 Lower-bound Inference
2723 public int LowerBoundInference (Type u
, Type v
)
2725 return LowerBoundInference (u
, v
, false);
2729 // Lower-bound (false) or Upper-bound (true) inference based on inversed argument
2731 int LowerBoundInference (Type u
, Type v
, bool inversed
)
2733 // If V is one of the unfixed type arguments
2734 int pos
= IsUnfixed (v
);
2736 AddToBounds (new BoundInfo (u
, inversed
? BoundKind
.Upper
: BoundKind
.Lower
), pos
);
2740 // If U is an array type
2742 int u_dim
= u
.GetArrayRank ();
2744 Type u_i
= TypeManager
.GetElementType (u
);
2747 if (u_dim
!= v
.GetArrayRank ())
2750 v_i
= TypeManager
.GetElementType (v
);
2752 if (TypeManager
.IsValueType (u_i
))
2753 return ExactInference (u_i
, v_i
);
2755 return LowerBoundInference (u_i
, v_i
, inversed
);
2761 if (v
.IsGenericType
) {
2762 Type g_v
= v
.GetGenericTypeDefinition ();
2763 if ((g_v
!= TypeManager
.generic_ilist_type
) && (g_v
!= TypeManager
.generic_icollection_type
) &&
2764 (g_v
!= TypeManager
.generic_ienumerable_type
))
2767 v_i
= TypeManager
.GetTypeArguments (v
) [0];
2768 if (TypeManager
.IsValueType (u_i
))
2769 return ExactInference (u_i
, v_i
);
2771 return LowerBoundInference (u_i
, v_i
);
2773 } else if (v
.IsGenericType
&& !v
.IsGenericTypeDefinition
) {
2775 // if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
2776 // such that U is identical to, inherits from (directly or indirectly),
2777 // or implements (directly or indirectly) C<U1..Uk>
2779 ArrayList u_candidates
= new ArrayList ();
2780 if (u
.IsGenericType
)
2781 u_candidates
.Add (u
);
2783 for (Type t
= u
.BaseType
; t
!= null; t
= t
.BaseType
) {
2784 if (t
.IsGenericType
&& !t
.IsGenericTypeDefinition
)
2785 u_candidates
.Add (t
);
2788 // TODO: Implement GetGenericInterfaces only and remove
2789 // the if from foreach
2790 u_candidates
.AddRange (TypeManager
.GetInterfaces (u
));
2792 Type open_v
= v
.GetGenericTypeDefinition ();
2793 Type
[] unique_candidate_targs
= null;
2794 Type
[] ga_v
= v
.GetGenericArguments ();
2795 foreach (Type u_candidate
in u_candidates
) {
2796 if (!u_candidate
.IsGenericType
|| u_candidate
.IsGenericTypeDefinition
)
2799 if (TypeManager
.DropGenericTypeArguments (u_candidate
) != open_v
)
2803 // The unique set of types U1..Uk means that if we have an interface I<T>,
2804 // class U : I<int>, I<long> then no type inference is made when inferring
2805 // type I<T> by applying type U because T could be int or long
2807 if (unique_candidate_targs
!= null) {
2808 Type
[] second_unique_candidate_targs
= u_candidate
.GetGenericArguments ();
2809 if (TypeManager
.IsEqual (unique_candidate_targs
, second_unique_candidate_targs
)) {
2810 unique_candidate_targs
= second_unique_candidate_targs
;
2815 // This should always cause type inference failure
2821 unique_candidate_targs
= u_candidate
.GetGenericArguments ();
2824 if (unique_candidate_targs
!= null) {
2825 Type
[] ga_open_v
= open_v
.GetGenericArguments ();
2827 for (int i
= 0; i
< unique_candidate_targs
.Length
; ++i
) {
2828 Variance variance
= TypeManager
.GetTypeParameterVariance (ga_open_v
[i
]);
2830 Type u_i
= unique_candidate_targs
[i
];
2831 if (variance
== Variance
.None
|| TypeManager
.IsValueType (u_i
)) {
2832 if (ExactInference (u_i
, ga_v
[i
]) == 0)
2835 bool upper_bound
= (variance
== Variance
.Contravariant
&& !inversed
) ||
2836 (variance
== Variance
.Covariant
&& inversed
);
2838 if (LowerBoundInference (u_i
, ga_v
[i
], upper_bound
) == 0)
2850 // 26.3.3.6 Output Type Inference
2852 public int OutputTypeInference (EmitContext ec
, Expression e
, Type t
)
2854 // If e is a lambda or anonymous method with inferred return type
2855 AnonymousMethodExpression ame
= e
as AnonymousMethodExpression
;
2857 Type rt
= ame
.InferReturnType (ec
, this, t
);
2858 MethodInfo invoke
= Delegate
.GetInvokeMethod (t
, t
);
2861 AParametersCollection pd
= TypeManager
.GetParameterData (invoke
);
2862 return ame
.Parameters
.Count
== pd
.Count
? 1 : 0;
2865 Type rtype
= invoke
.ReturnType
;
2867 // Blablabla, because reflection does not work with dynamic types
2868 Type
[] g_args
= t
.GetGenericArguments ();
2869 rtype
= g_args
[rtype
.GenericParameterPosition
];
2871 return LowerBoundInference (rt
, rtype
) + 1;
2875 // if E is a method group and T is a delegate type or expression tree type
2876 // return type Tb with parameter types T1..Tk and return type Tb, and overload
2877 // resolution of E with the types T1..Tk yields a single method with return type U,
2878 // then a lower-bound inference is made from U for Tb.
2880 if (e
is MethodGroupExpr
) {
2881 // TODO: Or expression tree
2882 if (!TypeManager
.IsDelegateType (t
))
2885 MethodInfo invoke
= Delegate
.GetInvokeMethod (t
, t
);
2886 Type rtype
= invoke
.ReturnType
;
2888 // Blablabla, because reflection does not work with dynamic types
2889 Type
[] g_args
= t
.GetGenericArguments ();
2890 rtype
= g_args
[rtype
.GenericParameterPosition
];
2893 if (!TypeManager
.IsGenericType (rtype
))
2896 MethodGroupExpr mg
= (MethodGroupExpr
) e
;
2897 Arguments args
= DelegateCreation
.CreateDelegateMethodArguments (TypeManager
.GetParameterData (invoke
), e
.Location
);
2898 mg
= mg
.OverloadResolve (ec
, ref args
, true, e
.Location
);
2902 // TODO: What should happen when return type is of generic type ?
2903 throw new NotImplementedException ();
2904 // return LowerBoundInference (null, rtype) + 1;
2908 // if e is an expression with type U, then
2909 // a lower-bound inference is made from U for T
2911 return LowerBoundInference (e
.Type
, t
) * 2;
2914 void RemoveDependentTypes (ArrayList types
, Type returnType
)
2916 int idx
= IsUnfixed (returnType
);
2922 if (returnType
.IsGenericType
) {
2923 foreach (Type t
in returnType
.GetGenericArguments ()) {
2924 RemoveDependentTypes (types
, t
);
2929 public bool UnfixedVariableExists
{
2931 if (unfixed_types
== null)
2934 foreach (Type ut
in unfixed_types
)