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
.Generic
;
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 int interface_constraints_pos
= 0;
150 if ((attrs
& GenericParameterAttributes
.NotNullableValueTypeConstraint
) != 0) {
151 base_type
= TypeManager
.value_type
;
152 interface_constraints_pos
= 1;
153 } else if ((attrs
& GenericParameterAttributes
.ReferenceTypeConstraint
) != 0) {
154 if (constraints
.Length
> 0 && constraints
[0].IsClass
) {
155 class_constraint
= base_type
= constraints
[0];
156 interface_constraints_pos
= 1;
158 base_type
= TypeManager
.object_type
;
161 base_type
= TypeManager
.object_type
;
164 if (constraints
.Length
> interface_constraints_pos
) {
165 if (interface_constraints_pos
== 0) {
166 iface_constraints
= constraints
;
168 iface_constraints
= new Type
[constraints
.Length
- interface_constraints_pos
];
169 Array
.Copy (constraints
, interface_constraints_pos
, iface_constraints
, 0, iface_constraints
.Length
);
172 iface_constraints
= Type
.EmptyTypes
;
176 public override string TypeParameter
181 public override GenericParameterAttributes Attributes
183 get { return attrs; }
186 public override Type ClassConstraint
188 get { return class_constraint; }
191 public override Type EffectiveBaseClass
193 get { return base_type; }
196 public override Type
[] InterfaceConstraints
198 get { return iface_constraints; }
205 // Don't add or modify internal values, they are used as -/+ calculation signs
212 public enum SpecialConstraint
220 /// Tracks the constraints for a type parameter from a generic type definition.
222 public class Constraints
: GenericConstraints
{
224 List
<object> constraints
;
228 // name is the identifier, constraints is an arraylist of
229 // Expressions (with types) or `true' for the constructor constraint.
231 public Constraints (string name
, List
<object> constraints
, Location loc
)
234 this.constraints
= constraints
;
238 public override string TypeParameter
{
244 public Constraints
Clone ()
246 return new Constraints (name
, constraints
, loc
);
249 GenericParameterAttributes attrs
;
250 TypeExpr class_constraint
;
251 List
<TypeExpr
> iface_constraints
;
252 List
<TypeExpr
> type_param_constraints
;
254 Type class_constraint_type
;
255 Type
[] iface_constraint_types
;
256 Type effective_base_type
;
261 /// Resolve the constraints - but only resolve things into Expression's, not
262 /// into actual types.
264 public bool Resolve (MemberCore ec
, TypeParameter tp
, Report Report
)
272 iface_constraints
= new List
<TypeExpr
> (2); // TODO: Too expensive allocation
273 type_param_constraints
= new List
<TypeExpr
> ();
275 foreach (object obj
in constraints
) {
276 if (HasConstructorConstraint
) {
277 Report
.Error (401, loc
,
278 "The new() constraint must be the last constraint specified");
282 if (obj
is SpecialConstraint
) {
283 SpecialConstraint sc
= (SpecialConstraint
) obj
;
285 if (sc
== SpecialConstraint
.Constructor
) {
286 if (!HasValueTypeConstraint
) {
287 attrs
|= GenericParameterAttributes
.DefaultConstructorConstraint
;
291 Report
.Error (451, loc
, "The `new()' constraint " +
292 "cannot be used with the `struct' constraint");
296 if ((num_constraints
> 0) || HasReferenceTypeConstraint
|| HasValueTypeConstraint
) {
297 Report
.Error (449, loc
, "The `class' or `struct' " +
298 "constraint must be the first constraint specified");
302 if (sc
== SpecialConstraint
.ReferenceType
)
303 attrs
|= GenericParameterAttributes
.ReferenceTypeConstraint
;
305 attrs
|= GenericParameterAttributes
.NotNullableValueTypeConstraint
;
309 int errors
= Report
.Errors
;
310 FullNamedExpression fn
= ((Expression
) obj
).ResolveAsTypeStep (ec
, false);
313 if (errors
!= Report
.Errors
)
316 NamespaceEntry
.Error_NamespaceNotFound (loc
, ((Expression
)obj
).GetSignatureForError (), Report
);
321 GenericTypeExpr cexpr
= fn
as GenericTypeExpr
;
323 expr
= cexpr
.ResolveAsBaseTerminal (ec
, false);
324 if (expr
!= null && cexpr
.HasDynamicArguments ()) {
325 Report
.Error (1968, cexpr
.Location
,
326 "A constraint cannot be the dynamic type `{0}'",
327 cexpr
.GetSignatureForError ());
331 expr
= ((Expression
) obj
).ResolveAsTypeTerminal (ec
, false);
333 if ((expr
== null) || (expr
.Type
== null))
336 if (TypeManager
.IsGenericParameter (expr
.Type
))
337 type_param_constraints
.Add (expr
);
338 else if (expr
.IsInterface
)
339 iface_constraints
.Add (expr
);
340 else if (class_constraint
!= null || iface_constraints
.Count
!= 0) {
341 Report
.Error (406, loc
,
342 "The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
343 expr
.GetSignatureForError ());
345 } else if (HasReferenceTypeConstraint
|| HasValueTypeConstraint
) {
346 Report
.Error (450, loc
, "`{0}': cannot specify both " +
347 "a constraint class and the `class' " +
348 "or `struct' constraint", expr
.GetSignatureForError ());
351 class_constraint
= expr
;
355 // Checks whether each generic method parameter constraint type
356 // is valid with respect to T
358 if (tp
!= null && tp
.Type
.DeclaringMethod
!= null) {
359 TypeManager
.CheckTypeVariance (expr
.Type
, Variance
.Contravariant
, ec
as MemberCore
);
362 if (!ec
.IsAccessibleAs (fn
.Type
)) {
363 Report
.SymbolRelatedToPreviousError (fn
.Type
);
364 Report
.Error (703, loc
,
365 "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
366 fn
.GetSignatureForError (), ec
.GetSignatureForError ());
372 var list
= new List
<Type
> ();
373 foreach (TypeExpr iface_constraint
in iface_constraints
) {
374 foreach (Type type
in list
) {
375 if (!type
.Equals (iface_constraint
.Type
))
378 Report
.Error (405, loc
,
379 "Duplicate constraint `{0}' for type " +
380 "parameter `{1}'.", iface_constraint
.GetSignatureForError (),
385 list
.Add (iface_constraint
.Type
);
388 foreach (TypeExpr expr
in type_param_constraints
) {
389 foreach (Type type
in list
) {
390 if (!type
.Equals (expr
.Type
))
393 Report
.Error (405, loc
,
394 "Duplicate constraint `{0}' for type " +
395 "parameter `{1}'.", expr
.GetSignatureForError (), name
);
399 list
.Add (expr
.Type
);
402 iface_constraint_types
= new Type
[list
.Count
];
403 list
.CopyTo (iface_constraint_types
, 0);
405 if (class_constraint
!= null) {
406 class_constraint_type
= class_constraint
.Type
;
407 if (class_constraint_type
== null)
410 if (class_constraint_type
.IsSealed
) {
411 if (class_constraint_type
.IsAbstract
)
413 Report
.Error (717, loc
, "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
414 TypeManager
.CSharpName (class_constraint_type
));
418 Report
.Error (701, loc
, "`{0}' is not a valid constraint. A constraint must be an interface, " +
419 "a non-sealed class or a type parameter", TypeManager
.CSharpName(class_constraint_type
));
424 if ((class_constraint_type
== TypeManager
.array_type
) ||
425 (class_constraint_type
== TypeManager
.delegate_type
) ||
426 (class_constraint_type
== TypeManager
.enum_type
) ||
427 (class_constraint_type
== TypeManager
.value_type
) ||
428 (class_constraint_type
== TypeManager
.object_type
) ||
429 class_constraint_type
== TypeManager
.multicast_delegate_type
) {
430 Report
.Error (702, loc
,
431 "A constraint cannot be special class `{0}'",
432 TypeManager
.CSharpName (class_constraint_type
));
436 if (TypeManager
.IsDynamicType (class_constraint_type
)) {
437 Report
.Error (1967, loc
, "A constraint cannot be the dynamic type");
442 if (class_constraint_type
!= null)
443 effective_base_type
= class_constraint_type
;
444 else if (HasValueTypeConstraint
)
445 effective_base_type
= TypeManager
.value_type
;
447 effective_base_type
= TypeManager
.object_type
;
449 if ((attrs
& GenericParameterAttributes
.NotNullableValueTypeConstraint
) != 0)
450 attrs
|= GenericParameterAttributes
.DefaultConstructorConstraint
;
456 bool CheckTypeParameterConstraints (Type tparam
, ref TypeExpr prevConstraint
, List
<Type
> seen
, Report Report
)
460 Constraints constraints
= TypeManager
.LookupTypeParameter (tparam
).Constraints
;
461 if (constraints
== null)
464 if (constraints
.HasValueTypeConstraint
) {
465 Report
.Error (456, loc
,
466 "Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
472 // Checks whether there are no conflicts between type parameter constraints
476 // where U : A, B // A and B are not convertible
478 if (constraints
.HasClassConstraint
) {
479 if (prevConstraint
!= null) {
480 Type t2
= constraints
.ClassConstraint
;
481 TypeExpr e2
= constraints
.class_constraint
;
483 if (!Convert
.ImplicitReferenceConversionExists (prevConstraint
, t2
) &&
484 !Convert
.ImplicitReferenceConversionExists (e2
, prevConstraint
.Type
)) {
485 Report
.Error (455, loc
,
486 "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
487 name
, TypeManager
.CSharpName (prevConstraint
.Type
), TypeManager
.CSharpName (t2
));
492 prevConstraint
= constraints
.class_constraint
;
495 if (constraints
.type_param_constraints
== null)
498 foreach (TypeExpr expr
in constraints
.type_param_constraints
) {
499 if (seen
.Contains (expr
.Type
)) {
500 Report
.Error (454, loc
, "Circular constraint " +
501 "dependency involving `{0}' and `{1}'",
502 tparam
.Name
, expr
.GetSignatureForError ());
506 if (!CheckTypeParameterConstraints (expr
.Type
, ref prevConstraint
, seen
, Report
))
514 /// Resolve the constraints into actual types.
516 public bool ResolveTypes (IMemberContext ec
, Report r
)
521 resolved_types
= true;
523 foreach (object obj
in constraints
) {
524 GenericTypeExpr cexpr
= obj
as GenericTypeExpr
;
528 if (!cexpr
.CheckConstraints (ec
))
532 if (type_param_constraints
.Count
!= 0) {
533 var seen
= new List
<Type
> ();
534 TypeExpr prev_constraint
= class_constraint
;
535 foreach (TypeExpr expr
in type_param_constraints
) {
536 if (!CheckTypeParameterConstraints (expr
.Type
, ref prev_constraint
, seen
, r
))
542 for (int i
= 0; i
< iface_constraints
.Count
; ++i
) {
543 TypeExpr iface_constraint
= (TypeExpr
) iface_constraints
[i
];
544 iface_constraint
= iface_constraint
.ResolveAsTypeTerminal (ec
, false);
545 if (iface_constraint
== null)
547 iface_constraints
[i
] = iface_constraint
;
550 if (class_constraint
!= null) {
551 class_constraint
= class_constraint
.ResolveAsTypeTerminal (ec
, false);
552 if (class_constraint
== null)
559 public override GenericParameterAttributes Attributes
{
560 get { return attrs; }
563 public override bool HasClassConstraint
{
564 get { return class_constraint != null; }
567 public override Type ClassConstraint
{
568 get { return class_constraint_type; }
571 public override Type
[] InterfaceConstraints
{
572 get { return iface_constraint_types; }
575 public override Type EffectiveBaseClass
{
576 get { return effective_base_type; }
579 public bool IsSubclassOf (Type t
)
581 if ((class_constraint_type
!= null) &&
582 class_constraint_type
.IsSubclassOf (t
))
585 if (iface_constraint_types
== null)
588 foreach (Type iface
in iface_constraint_types
) {
589 if (TypeManager
.IsSubclassOf (iface
, t
))
596 public Location Location
{
603 /// This is used when we're implementing a generic interface method.
604 /// Each method type parameter in implementing method must have the same
605 /// constraints than the corresponding type parameter in the interface
606 /// method. To do that, we're called on each of the implementing method's
609 public bool AreEqual (GenericConstraints gc
)
611 if (gc
.Attributes
!= attrs
)
614 if (HasClassConstraint
!= gc
.HasClassConstraint
)
616 if (HasClassConstraint
&& !TypeManager
.IsEqual (gc
.ClassConstraint
, ClassConstraint
))
619 int gc_icount
= gc
.InterfaceConstraints
!= null ?
620 gc
.InterfaceConstraints
.Length
: 0;
621 int icount
= InterfaceConstraints
!= null ?
622 InterfaceConstraints
.Length
: 0;
624 if (gc_icount
!= icount
)
627 for (int i
= 0; i
< gc
.InterfaceConstraints
.Length
; ++i
) {
628 Type iface
= gc
.InterfaceConstraints
[i
];
629 if (iface
.IsGenericType
)
630 iface
= iface
.GetGenericTypeDefinition ();
633 for (int ii
= 0; ii
< InterfaceConstraints
.Length
; ii
++) {
634 Type check
= InterfaceConstraints
[ii
];
635 if (check
.IsGenericType
)
636 check
= check
.GetGenericTypeDefinition ();
638 if (TypeManager
.IsEqual (iface
, check
)) {
651 public void VerifyClsCompliance (Report r
)
653 if (class_constraint_type
!= null && !AttributeTester
.IsClsCompliant (class_constraint_type
))
654 Warning_ConstrainIsNotClsCompliant (class_constraint_type
, class_constraint
.Location
, r
);
656 if (iface_constraint_types
!= null) {
657 for (int i
= 0; i
< iface_constraint_types
.Length
; ++i
) {
658 if (!AttributeTester
.IsClsCompliant (iface_constraint_types
[i
]))
659 Warning_ConstrainIsNotClsCompliant (iface_constraint_types
[i
],
660 ((TypeExpr
)iface_constraints
[i
]).Location
, r
);
665 void Warning_ConstrainIsNotClsCompliant (Type t
, Location loc
, Report Report
)
667 Report
.SymbolRelatedToPreviousError (t
);
668 Report
.Warning (3024, 1, loc
, "Constraint type `{0}' is not CLS-compliant",
669 TypeManager
.CSharpName (t
));
674 /// A type parameter from a generic type definition.
676 public class TypeParameter
: MemberCore
, IMemberContainer
678 static readonly string[] attribute_target
= new string [] { "type parameter" }
;
681 GenericConstraints gc
;
682 Constraints constraints
;
683 GenericTypeParameterBuilder type
;
684 MemberCache member_cache
;
687 public TypeParameter (DeclSpace parent
, DeclSpace decl
, string name
,
688 Constraints constraints
, Attributes attrs
, Variance variance
, Location loc
)
689 : base (parent
, new MemberName (name
, loc
), attrs
)
692 this.constraints
= constraints
;
693 this.variance
= variance
;
696 public GenericConstraints GenericConstraints
{
697 get { return gc != null ? gc : constraints; }
700 public Constraints Constraints
{
701 get { return constraints; }
704 public DeclSpace DeclSpace
{
708 public Variance Variance
{
709 get { return variance; }
717 /// This is the first method which is called during the resolving
718 /// process; we're called immediately after creating the type parameters
719 /// with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
722 /// We're either called from TypeContainer.DefineType() or from
723 /// GenericMethod.Define() (called from Method.Define()).
725 public void Define (GenericTypeParameterBuilder type
)
727 if (this.type
!= null)
728 throw new InvalidOperationException ();
731 TypeManager
.AddTypeParameter (type
, this);
734 public void ErrorInvalidVariance (IMemberContext mc
, Variance expected
)
736 // TODO: Report.SymbolRelatedToPreviousError (mc);
737 string input_variance
= Variance
== Variance
.Contravariant
? "contravariant" : "covariant";
738 string gtype_variance
;
740 case Variance
.Contravariant
: gtype_variance
= "contravariantly"; break;
741 case Variance
.Covariant
: gtype_variance
= "covariantly"; break;
742 default: gtype_variance
= "invariantly"; break;
745 Delegate d
= mc
as Delegate
;
746 string parameters
= d
!= null ? d
.Parameters
.GetSignatureForError () : "";
748 Report
.Error (1961, Location
,
749 "The {2} type parameter `{0}' must be {3} valid on `{1}{4}'",
750 GetSignatureForError (), mc
.GetSignatureForError (), input_variance
, gtype_variance
, parameters
);
754 /// This is the second method which is called during the resolving
755 /// process - in case of class type parameters, we're called from
756 /// TypeContainer.ResolveType() - after it resolved the class'es
757 /// base class and interfaces. For method type parameters, we're
758 /// called immediately after Define().
760 /// We're just resolving the constraints into expressions here, we
761 /// don't resolve them into actual types.
763 /// Note that in the special case of partial generic classes, we may be
764 /// called _before_ Define() and we may also be called multiple types.
766 public bool Resolve (DeclSpace ds
)
768 if (constraints
!= null) {
769 if (!constraints
.Resolve (ds
, this, Report
)) {
779 /// This is the third method which is called during the resolving
780 /// process. We're called immediately after calling DefineConstraints()
781 /// on all of the current class'es type parameters.
783 /// Our job is to resolve the constraints to actual types.
785 /// Note that we may have circular dependencies on type parameters - this
786 /// is why Resolve() and ResolveType() are separate.
788 public bool ResolveType (IMemberContext ec
)
790 if (constraints
!= null) {
791 if (!constraints
.ResolveTypes (ec
, Report
)) {
801 /// This is the fourth and last method which is called during the resolving
802 /// process. We're called after everything is fully resolved and actually
803 /// register the constraints with SRE and the TypeManager.
805 public bool DefineType (IMemberContext ec
)
807 return DefineType (ec
, null, null, false);
811 /// This is the fith and last method which is called during the resolving
812 /// process. We're called after everything is fully resolved and actually
813 /// register the constraints with SRE and the TypeManager.
815 /// The `builder', `implementing' and `is_override' arguments are only
816 /// applicable to method type parameters.
818 public bool DefineType (IMemberContext ec
, MethodBuilder builder
,
819 MethodInfo implementing
, bool is_override
)
821 if (!ResolveType (ec
))
824 if (implementing
!= null) {
825 if (is_override
&& (constraints
!= null)) {
826 Report
.Error (460, Location
,
827 "`{0}': Cannot specify constraints for overrides or explicit interface implementation methods",
828 TypeManager
.CSharpSignature (builder
));
832 MethodBase mb
= TypeManager
.DropGenericMethodArguments (implementing
);
834 int pos
= type
.GenericParameterPosition
;
835 Type mparam
= mb
.GetGenericArguments () [pos
];
836 GenericConstraints temp_gc
= ReflectionConstraints
.GetConstraints (mparam
);
839 gc
= new InflatedConstraints (temp_gc
, implementing
.DeclaringType
);
840 else if (constraints
!= null)
841 gc
= new InflatedConstraints (constraints
, implementing
.DeclaringType
);
844 if (constraints
!= null) {
847 else if (!constraints
.AreEqual (gc
))
850 if (!is_override
&& (temp_gc
!= null))
855 Report
.SymbolRelatedToPreviousError (implementing
);
858 425, Location
, "The constraints for type " +
859 "parameter `{0}' of method `{1}' must match " +
860 "the constraints for type parameter `{2}' " +
861 "of interface method `{3}'. Consider using " +
862 "an explicit interface implementation instead",
863 Name
, TypeManager
.CSharpSignature (builder
),
864 TypeManager
.CSharpName (mparam
), TypeManager
.CSharpSignature (mb
));
867 } else if (DeclSpace
is CompilerGeneratedClass
) {
868 TypeParameter
[] tparams
= DeclSpace
.TypeParameters
;
869 Type
[] types
= new Type
[tparams
.Length
];
870 for (int i
= 0; i
< tparams
.Length
; i
++)
871 types
[i
] = tparams
[i
].Type
;
873 if (constraints
!= null)
874 gc
= new InflatedConstraints (constraints
, types
);
876 gc
= (GenericConstraints
) constraints
;
879 SetConstraints (type
);
883 public static TypeParameter
FindTypeParameter (TypeParameter
[] tparams
, string name
)
885 foreach (var tp
in tparams
) {
893 public void SetConstraints (GenericTypeParameterBuilder type
)
895 GenericParameterAttributes attr
= GenericParameterAttributes
.None
;
896 if (variance
== Variance
.Contravariant
)
897 attr
|= GenericParameterAttributes
.Contravariant
;
898 else if (variance
== Variance
.Covariant
)
899 attr
|= GenericParameterAttributes
.Covariant
;
902 if (gc
.HasClassConstraint
|| gc
.HasValueTypeConstraint
)
903 type
.SetBaseTypeConstraint (gc
.EffectiveBaseClass
);
905 attr
|= gc
.Attributes
;
906 type
.SetInterfaceConstraints (gc
.InterfaceConstraints
);
907 TypeManager
.RegisterBuilder (type
, gc
.InterfaceConstraints
);
910 type
.SetGenericParameterAttributes (attr
);
914 /// This is called for each part of a partial generic type definition.
916 /// If `new_constraints' is not null and we don't already have constraints,
917 /// they become our constraints. If we already have constraints, we must
918 /// check that they're the same.
921 public bool UpdateConstraints (MemberCore ec
, Constraints new_constraints
)
924 throw new InvalidOperationException ();
926 if (new_constraints
== null)
929 if (!new_constraints
.Resolve (ec
, this, Report
))
931 if (!new_constraints
.ResolveTypes (ec
, Report
))
934 if (constraints
!= null)
935 return constraints
.AreEqual (new_constraints
);
937 constraints
= new_constraints
;
941 public override void Emit ()
943 if (OptAttributes
!= null)
944 OptAttributes
.Emit ();
949 public override string DocCommentHeader
{
951 throw new InvalidOperationException (
952 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
960 public override bool Define ()
965 public override void ApplyAttributeBuilder (Attribute a
, CustomAttributeBuilder cb
, PredefinedAttributes pa
)
967 type
.SetCustomAttribute (cb
);
970 public override AttributeTargets AttributeTargets
{
972 return AttributeTargets
.GenericParameter
;
976 public override string[] ValidAttributeTargets
{
978 return attribute_target
;
986 string IMemberContainer
.Name
{
990 MemberCache IMemberContainer
.BaseCache
{
995 if (gc
.EffectiveBaseClass
.BaseType
== null)
998 return TypeManager
.LookupMemberCache (gc
.EffectiveBaseClass
.BaseType
);
1002 bool IMemberContainer
.IsInterface
{
1003 get { return false; }
1006 MemberList IMemberContainer
.GetMembers (MemberTypes mt
, BindingFlags bf
)
1008 throw new NotSupportedException ();
1011 public MemberCache MemberCache
{
1013 if (member_cache
!= null)
1014 return member_cache
;
1019 Type
[] ifaces
= TypeManager
.ExpandInterfaces (gc
.InterfaceConstraints
);
1020 member_cache
= new MemberCache (this, gc
.EffectiveBaseClass
, ifaces
);
1022 return member_cache
;
1026 public MemberList
FindMembers (MemberTypes mt
, BindingFlags bf
,
1027 MemberFilter filter
, object criteria
)
1030 return MemberList
.Empty
;
1032 var members
= new List
<MemberInfo
> ();
1034 if (gc
.HasClassConstraint
) {
1035 MemberList list
= TypeManager
.FindMembers (
1036 gc
.ClassConstraint
, mt
, bf
, filter
, criteria
);
1038 members
.AddRange (list
);
1041 Type
[] ifaces
= TypeManager
.ExpandInterfaces (gc
.InterfaceConstraints
);
1042 foreach (Type t
in ifaces
) {
1043 MemberList list
= TypeManager
.FindMembers (
1044 t
, mt
, bf
, filter
, criteria
);
1046 members
.AddRange (list
);
1049 return new MemberList (members
);
1052 public bool IsSubclassOf (Type t
)
1054 if (type
.Equals (t
))
1057 if (constraints
!= null)
1058 return constraints
.IsSubclassOf (t
);
1063 public void InflateConstraints (Type declaring
)
1065 if (constraints
!= null)
1066 gc
= new InflatedConstraints (constraints
, declaring
);
1069 public override bool IsClsComplianceRequired ()
1074 protected class InflatedConstraints
: GenericConstraints
1076 GenericConstraints gc
;
1078 Type class_constraint
;
1079 Type
[] iface_constraints
;
1082 public InflatedConstraints (GenericConstraints gc
, Type declaring
)
1083 : this (gc
, TypeManager
.GetTypeArguments (declaring
))
1086 public InflatedConstraints (GenericConstraints gc
, Type
[] dargs
)
1091 var list
= new List
<Type
> ();
1092 if (gc
.HasClassConstraint
)
1093 list
.Add (inflate (gc
.ClassConstraint
));
1094 foreach (Type iface
in gc
.InterfaceConstraints
)
1095 list
.Add (inflate (iface
));
1097 bool has_class_constr
= false;
1098 if (list
.Count
> 0) {
1099 Type first
= (Type
) list
[0];
1100 has_class_constr
= !first
.IsGenericParameter
&& !first
.IsInterface
;
1103 if ((list
.Count
> 0) && has_class_constr
) {
1104 class_constraint
= (Type
) list
[0];
1105 iface_constraints
= new Type
[list
.Count
- 1];
1106 list
.CopyTo (1, iface_constraints
, 0, list
.Count
- 1);
1108 iface_constraints
= new Type
[list
.Count
];
1109 list
.CopyTo (iface_constraints
, 0);
1112 if (HasValueTypeConstraint
)
1113 base_type
= TypeManager
.value_type
;
1114 else if (class_constraint
!= null)
1115 base_type
= class_constraint
;
1117 base_type
= TypeManager
.object_type
;
1120 Type
inflate (Type t
)
1124 if (t
.IsGenericParameter
)
1125 return t
.GenericParameterPosition
< dargs
.Length
? dargs
[t
.GenericParameterPosition
] : t
;
1126 if (t
.IsGenericType
) {
1127 Type
[] args
= t
.GetGenericArguments ();
1128 Type
[] inflated
= new Type
[args
.Length
];
1130 for (int i
= 0; i
< args
.Length
; i
++)
1131 inflated
[i
] = inflate (args
[i
]);
1133 t
= t
.GetGenericTypeDefinition ();
1134 t
= t
.MakeGenericType (inflated
);
1140 public override string TypeParameter
{
1141 get { return gc.TypeParameter; }
1144 public override GenericParameterAttributes Attributes
{
1145 get { return gc.Attributes; }
1148 public override Type ClassConstraint
{
1149 get { return class_constraint; }
1152 public override Type EffectiveBaseClass
{
1153 get { return base_type; }
1156 public override Type
[] InterfaceConstraints
{
1157 get { return iface_constraints; }
1163 /// A TypeExpr which already resolved to a type parameter.
1165 public class TypeParameterExpr
: TypeExpr
{
1167 public TypeParameterExpr (TypeParameter type_parameter
, Location loc
)
1169 this.type
= type_parameter
.Type
;
1170 this.eclass
= ExprClass
.TypeParameter
;
1174 protected override TypeExpr
DoResolveAsTypeStep (IMemberContext ec
)
1176 throw new NotSupportedException ();
1179 public override FullNamedExpression
ResolveAsTypeStep (IMemberContext ec
, bool silent
)
1184 public override bool IsInterface
{
1185 get { return false; }
1188 public override bool CheckAccessLevel (IMemberContext ds
)
1195 // Tracks the type arguments when instantiating a generic type. It's used
1196 // by both type arguments and type parameters
1198 public class TypeArguments
{
1199 List
<FullNamedExpression
> args
;
1202 public TypeArguments ()
1204 args
= new List
<FullNamedExpression
> ();
1207 public TypeArguments (params FullNamedExpression
[] types
)
1209 this.args
= new List
<FullNamedExpression
> (types
);
1212 public void Add (FullNamedExpression type
)
1217 public void Add (TypeArguments new_args
)
1219 args
.AddRange (new_args
.args
);
1222 // TODO: Kill this monster
1223 public TypeParameterName
[] GetDeclarations ()
1225 return args
.ConvertAll (i
=> (TypeParameterName
) i
).ToArray ();
1229 /// We may only be used after Resolve() is called and return the fully
1232 public Type
[] Arguments
{
1244 public string GetSignatureForError()
1246 StringBuilder sb
= new StringBuilder();
1247 for (int i
= 0; i
< Count
; ++i
)
1249 Expression expr
= (Expression
)args
[i
];
1250 sb
.Append(expr
.GetSignatureForError());
1254 return sb
.ToString();
1258 /// Resolve the type arguments.
1260 public bool Resolve (IMemberContext ec
)
1263 return atypes
.Length
!= 0;
1265 int count
= args
.Count
;
1268 atypes
= new Type
[count
];
1270 for (int i
= 0; i
< count
; i
++){
1271 TypeExpr te
= ((FullNamedExpression
) args
[i
]).ResolveAsTypeTerminal (ec
, false);
1277 atypes
[i
] = te
.Type
;
1279 if (te
.Type
.IsSealed
&& te
.Type
.IsAbstract
) {
1280 ec
.Compiler
.Report
.Error (718, te
.Location
, "`{0}': static classes cannot be used as generic arguments",
1281 te
.GetSignatureForError ());
1285 if (te
.Type
.IsPointer
|| TypeManager
.IsSpecialType (te
.Type
)) {
1286 ec
.Compiler
.Report
.Error (306, te
.Location
,
1287 "The type `{0}' may not be used as a type argument",
1288 te
.GetSignatureForError ());
1294 atypes
= Type
.EmptyTypes
;
1299 public TypeArguments
Clone ()
1301 TypeArguments copy
= new TypeArguments ();
1302 foreach (var ta
in args
)
1309 public class TypeParameterName
: SimpleName
1311 Attributes attributes
;
1314 public TypeParameterName (string name
, Attributes attrs
, Location loc
)
1315 : this (name
, attrs
, Variance
.None
, loc
)
1319 public TypeParameterName (string name
, Attributes attrs
, Variance variance
, Location loc
)
1323 this.variance
= variance
;
1326 public Attributes OptAttributes
{
1332 public Variance Variance
{
1340 /// A reference expression to generic type
1342 class GenericTypeExpr
: TypeExpr
1345 Type
[] gen_params
; // TODO: Waiting for constrains check cleanup
1349 // Should be carefully used only with defined generic containers. Type parameters
1350 // can be used as type arguments in this case.
1352 // TODO: This could be GenericTypeExpr specialization
1354 public GenericTypeExpr (DeclSpace gType
, Location l
)
1356 open_type
= gType
.TypeBuilder
.GetGenericTypeDefinition ();
1358 args
= new TypeArguments ();
1359 foreach (TypeParameter type_param
in gType
.TypeParameters
)
1360 args
.Add (new TypeParameterExpr (type_param
, l
));
1366 /// Instantiate the generic type `t' with the type arguments `args'.
1367 /// Use this constructor if you already know the fully resolved
1370 public GenericTypeExpr (Type t
, TypeArguments args
, Location l
)
1372 open_type
= t
.GetGenericTypeDefinition ();
1378 public TypeArguments TypeArguments
{
1379 get { return args; }
1382 public override string GetSignatureForError ()
1384 return TypeManager
.CSharpName (type
);
1387 protected override TypeExpr
DoResolveAsTypeStep (IMemberContext ec
)
1389 eclass
= ExprClass
.Type
;
1391 if (!args
.Resolve (ec
))
1394 gen_params
= open_type
.GetGenericArguments ();
1395 Type
[] atypes
= args
.Arguments
;
1397 if (atypes
.Length
!= gen_params
.Length
) {
1398 Namespace
.Error_InvalidNumberOfTypeArguments (ec
.Compiler
.Report
, open_type
, loc
);
1403 // Now bind the parameters
1405 type
= open_type
.MakeGenericType (atypes
);
1410 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1411 /// after fully resolving the constructed type.
1413 public bool CheckConstraints (IMemberContext ec
)
1415 return ConstraintChecker
.CheckConstraints (ec
, open_type
, gen_params
, args
.Arguments
, loc
);
1418 public override bool CheckAccessLevel (IMemberContext mc
)
1420 return mc
.CurrentTypeDefinition
.CheckAccessLevel (open_type
);
1423 public bool HasDynamicArguments ()
1425 return HasDynamicArguments (args
.Arguments
);
1428 static bool HasDynamicArguments (Type
[] args
)
1430 foreach (var item
in args
)
1432 if (TypeManager
.IsGenericType (item
))
1433 return HasDynamicArguments (TypeManager
.GetTypeArguments (item
));
1435 if (TypeManager
.IsDynamicType (item
))
1442 public override bool IsClass
{
1443 get { return open_type.IsClass; }
1446 public override bool IsValueType
{
1447 get { return TypeManager.IsStruct (open_type); }
1450 public override bool IsInterface
{
1451 get { return open_type.IsInterface; }
1454 public override bool IsSealed
{
1455 get { return open_type.IsSealed; }
1458 public override bool Equals (object obj
)
1460 GenericTypeExpr cobj
= obj
as GenericTypeExpr
;
1464 if ((type
== null) || (cobj
.type
== null))
1467 return type
== cobj
.type
;
1470 public override int GetHashCode ()
1472 return base.GetHashCode ();
1476 public abstract class ConstraintChecker
1478 protected readonly Type
[] gen_params
;
1479 protected readonly Type
[] atypes
;
1480 protected readonly Location loc
;
1481 protected Report Report
;
1483 protected ConstraintChecker (Type
[] gen_params
, Type
[] atypes
, Location loc
, Report r
)
1485 this.gen_params
= gen_params
;
1486 this.atypes
= atypes
;
1492 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1493 /// after fully resolving the constructed type.
1495 public bool CheckConstraints (IMemberContext ec
)
1497 for (int i
= 0; i
< gen_params
.Length
; i
++) {
1498 if (!CheckConstraints (ec
, i
))
1505 protected bool CheckConstraints (IMemberContext ec
, int index
)
1507 Type atype
= TypeManager
.TypeToCoreType (atypes
[index
]);
1508 Type ptype
= gen_params
[index
];
1513 Expression aexpr
= new EmptyExpression (atype
);
1515 GenericConstraints gc
= TypeManager
.GetTypeParameterConstraints (ptype
);
1519 bool is_class
, is_struct
;
1520 if (atype
.IsGenericParameter
) {
1521 GenericConstraints agc
= TypeManager
.GetTypeParameterConstraints (atype
);
1523 if (agc
is Constraints
) {
1524 // FIXME: No constraints can be resolved here, we are in
1525 // completely wrong/different context. This path is hit
1526 // when resolving base type of unresolved generic type
1527 // with constraints. We are waiting with CheckConsttraints
1528 // after type-definition but not in this case
1529 if (!((Constraints
) agc
).Resolve (null, null, Report
))
1532 is_class
= agc
.IsReferenceType
;
1533 is_struct
= agc
.IsValueType
;
1535 is_class
= is_struct
= false;
1538 is_class
= TypeManager
.IsReferenceType (atype
);
1539 is_struct
= TypeManager
.IsValueType (atype
) && !TypeManager
.IsNullableType (atype
);
1543 // First, check the `class' and `struct' constraints.
1545 if (gc
.HasReferenceTypeConstraint
&& !is_class
) {
1546 Report
.Error (452, loc
, "The type `{0}' must be " +
1547 "a reference type in order to use it " +
1548 "as type parameter `{1}' in the " +
1549 "generic type or method `{2}'.",
1550 TypeManager
.CSharpName (atype
),
1551 TypeManager
.CSharpName (ptype
),
1552 GetSignatureForError ());
1554 } else if (gc
.HasValueTypeConstraint
&& !is_struct
) {
1555 Report
.Error (453, loc
, "The type `{0}' must be a " +
1556 "non-nullable value type in order to use it " +
1557 "as type parameter `{1}' in the " +
1558 "generic type or method `{2}'.",
1559 TypeManager
.CSharpName (atype
),
1560 TypeManager
.CSharpName (ptype
),
1561 GetSignatureForError ());
1566 // The class constraint comes next.
1568 if (gc
.HasClassConstraint
) {
1569 if (!CheckConstraint (ec
, ptype
, aexpr
, gc
.ClassConstraint
))
1574 // Now, check the interface constraints.
1576 if (gc
.InterfaceConstraints
!= null) {
1577 foreach (Type it
in gc
.InterfaceConstraints
) {
1578 if (!CheckConstraint (ec
, ptype
, aexpr
, it
))
1584 // Finally, check the constructor constraint.
1587 if (!gc
.HasConstructorConstraint
)
1590 if (TypeManager
.IsValueType (atype
))
1593 if (HasDefaultConstructor (atype
))
1596 Report_SymbolRelatedToPreviousError ();
1597 Report
.SymbolRelatedToPreviousError (atype
);
1598 Report
.Error (310, loc
, "The type `{0}' must have a public " +
1599 "parameterless constructor in order to use it " +
1600 "as parameter `{1}' in the generic type or " +
1602 TypeManager
.CSharpName (atype
),
1603 TypeManager
.CSharpName (ptype
),
1604 GetSignatureForError ());
1608 Type
InflateType(IMemberContext ec
, Type ctype
)
1610 Type
[] types
= TypeManager
.GetTypeArguments (ctype
);
1612 TypeArguments new_args
= new TypeArguments ();
1614 for (int i
= 0; i
< types
.Length
; i
++) {
1615 Type t
= TypeManager
.TypeToCoreType (types
[i
]);
1617 if (t
.IsGenericParameter
) {
1618 int pos
= t
.GenericParameterPosition
;
1619 if (t
.DeclaringMethod
== null && this is MethodConstraintChecker
) {
1620 Type parent
= ((MethodConstraintChecker
) this).declaring_type
;
1621 t
= parent
.GetGenericArguments ()[pos
];
1625 } else if(TypeManager
.HasGenericArguments(t
)) {
1626 t
= InflateType (ec
, t
);
1631 new_args
.Add (new TypeExpression (t
, loc
));
1634 TypeExpr ct
= new GenericTypeExpr (ctype
, new_args
, loc
);
1635 if (ct
.ResolveAsTypeStep (ec
, false) == null)
1641 protected bool CheckConstraint (IMemberContext ec
, Type ptype
, Expression expr
,
1645 // All this is needed because we don't have
1646 // real inflated type hierarchy
1648 if (TypeManager
.HasGenericArguments (ctype
)) {
1649 ctype
= InflateType (ec
, ctype
);
1653 } else if (ctype
.IsGenericParameter
) {
1654 int pos
= ctype
.GenericParameterPosition
;
1655 if (ctype
.DeclaringMethod
== null) {
1659 ctype
= atypes
[pos
];
1663 if (Convert
.ImplicitStandardConversionExists (expr
, ctype
))
1666 Report_SymbolRelatedToPreviousError ();
1667 Report
.SymbolRelatedToPreviousError (expr
.Type
);
1669 if (TypeManager
.IsNullableType (expr
.Type
) && ctype
.IsInterface
) {
1670 Report
.Error (313, loc
,
1671 "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. " +
1672 "The nullable type `{0}' never satisfies interface constraint of type `{3}'",
1673 TypeManager
.CSharpName (expr
.Type
), TypeManager
.CSharpName (ptype
),
1674 GetSignatureForError (), TypeManager
.CSharpName (ctype
));
1676 Report
.Error (309, loc
,
1677 "The type `{0}' must be convertible to `{1}' in order to " +
1678 "use it as parameter `{2}' in the generic type or method `{3}'",
1679 TypeManager
.CSharpName (expr
.Type
), TypeManager
.CSharpName (ctype
),
1680 TypeManager
.CSharpName (ptype
), GetSignatureForError ());
1685 static bool HasDefaultConstructor (Type atype
)
1687 TypeParameter tparam
= TypeManager
.LookupTypeParameter (atype
);
1688 if (tparam
!= null) {
1689 if (tparam
.GenericConstraints
== null)
1692 return tparam
.GenericConstraints
.HasConstructorConstraint
||
1693 tparam
.GenericConstraints
.HasValueTypeConstraint
;
1696 if (atype
.IsAbstract
)
1700 atype
= TypeManager
.DropGenericTypeArguments (atype
);
1701 if (atype
is TypeBuilder
) {
1702 TypeContainer tc
= TypeManager
.LookupTypeContainer (atype
);
1703 if (tc
.InstanceConstructors
== null) {
1704 atype
= atype
.BaseType
;
1708 foreach (Constructor c
in tc
.InstanceConstructors
) {
1709 if ((c
.ModFlags
& Modifiers
.PUBLIC
) == 0)
1711 if ((c
.Parameters
.FixedParameters
!= null) &&
1712 (c
.Parameters
.FixedParameters
.Length
!= 0))
1714 if (c
.Parameters
.HasArglist
|| c
.Parameters
.HasParams
)
1721 MemberInfo
[] list
= TypeManager
.MemberLookup (null, null, atype
, MemberTypes
.Constructor
,
1722 BindingFlags
.Public
| BindingFlags
.Instance
| BindingFlags
.DeclaredOnly
,
1723 ConstructorInfo
.ConstructorName
, null);
1728 foreach (MethodBase mb
in list
) {
1729 AParametersCollection pd
= TypeManager
.GetParameterData (mb
);
1737 protected abstract string GetSignatureForError ();
1738 protected abstract void Report_SymbolRelatedToPreviousError ();
1740 public static bool CheckConstraints (IMemberContext ec
, MethodBase definition
,
1741 MethodBase instantiated
, Location loc
)
1743 MethodConstraintChecker checker
= new MethodConstraintChecker (
1744 definition
, instantiated
.DeclaringType
, definition
.GetGenericArguments (),
1745 instantiated
.GetGenericArguments (), loc
, ec
.Compiler
.Report
);
1747 return checker
.CheckConstraints (ec
);
1750 public static bool CheckConstraints (IMemberContext ec
, Type gt
, Type
[] gen_params
,
1751 Type
[] atypes
, Location loc
)
1753 TypeConstraintChecker checker
= new TypeConstraintChecker (
1754 gt
, gen_params
, atypes
, loc
, ec
.Compiler
.Report
);
1756 return checker
.CheckConstraints (ec
);
1759 protected class MethodConstraintChecker
: ConstraintChecker
1761 MethodBase definition
;
1762 public Type declaring_type
;
1764 public MethodConstraintChecker (MethodBase definition
, Type declaringType
, Type
[] gen_params
,
1765 Type
[] atypes
, Location loc
, Report r
)
1766 : base (gen_params
, atypes
, loc
, r
)
1768 this.declaring_type
= declaringType
;
1769 this.definition
= definition
;
1772 protected override string GetSignatureForError ()
1774 return TypeManager
.CSharpSignature (definition
);
1777 protected override void Report_SymbolRelatedToPreviousError ()
1779 Report
.SymbolRelatedToPreviousError (definition
);
1783 protected class TypeConstraintChecker
: ConstraintChecker
1787 public TypeConstraintChecker (Type gt
, Type
[] gen_params
, Type
[] atypes
,
1788 Location loc
, Report r
)
1789 : base (gen_params
, atypes
, loc
, r
)
1794 protected override string GetSignatureForError ()
1796 return TypeManager
.CSharpName (gt
);
1799 protected override void Report_SymbolRelatedToPreviousError ()
1801 Report
.SymbolRelatedToPreviousError (gt
);
1807 /// A generic method definition.
1809 public class GenericMethod
: DeclSpace
1811 FullNamedExpression return_type
;
1812 ParametersCompiled parameters
;
1814 public GenericMethod (NamespaceEntry ns
, DeclSpace parent
, MemberName name
,
1815 FullNamedExpression return_type
, ParametersCompiled parameters
)
1816 : base (ns
, parent
, name
, null)
1818 this.return_type
= return_type
;
1819 this.parameters
= parameters
;
1822 public override TypeContainer CurrentTypeDefinition
{
1824 return Parent
.CurrentTypeDefinition
;
1828 public override TypeParameter
[] CurrentTypeParameters
{
1830 return base.type_params
;
1834 public override TypeBuilder
DefineType ()
1836 throw new Exception ();
1839 public override bool Define ()
1841 for (int i
= 0; i
< TypeParameters
.Length
; i
++)
1842 if (!TypeParameters
[i
].Resolve (this))
1849 /// Define and resolve the type parameters.
1850 /// We're called from Method.Define().
1852 public bool Define (MethodOrOperator m
)
1854 TypeParameterName
[] names
= MemberName
.TypeArguments
.GetDeclarations ();
1855 string[] snames
= new string [names
.Length
];
1856 for (int i
= 0; i
< names
.Length
; i
++) {
1857 string type_argument_name
= names
[i
].Name
;
1858 int idx
= parameters
.GetParameterIndexByName (type_argument_name
);
1862 b
= new Block (null);
1864 b
.Error_AlreadyDeclaredTypeParameter (Report
, parameters
[i
].Location
,
1865 type_argument_name
, "method parameter");
1868 snames
[i
] = type_argument_name
;
1871 GenericTypeParameterBuilder
[] gen_params
= m
.MethodBuilder
.DefineGenericParameters (snames
);
1872 for (int i
= 0; i
< TypeParameters
.Length
; i
++)
1873 TypeParameters
[i
].Define (gen_params
[i
]);
1878 for (int i
= 0; i
< TypeParameters
.Length
; i
++) {
1879 if (!TypeParameters
[i
].ResolveType (this))
1887 /// We're called from MethodData.Define() after creating the MethodBuilder.
1889 public bool DefineType (IMemberContext ec
, MethodBuilder mb
,
1890 MethodInfo implementing
, bool is_override
)
1892 for (int i
= 0; i
< TypeParameters
.Length
; i
++)
1893 if (!TypeParameters
[i
].DefineType (
1894 ec
, mb
, implementing
, is_override
))
1897 bool ok
= parameters
.Resolve (ec
);
1899 if ((return_type
!= null) && (return_type
.ResolveAsTypeTerminal (ec
, false) == null))
1905 public void EmitAttributes ()
1907 for (int i
= 0; i
< TypeParameters
.Length
; i
++)
1908 TypeParameters
[i
].Emit ();
1910 if (OptAttributes
!= null)
1911 OptAttributes
.Emit ();
1914 public override MemberList
FindMembers (MemberTypes mt
, BindingFlags bf
,
1915 MemberFilter filter
, object criteria
)
1917 throw new Exception ();
1920 public override string GetSignatureForError ()
1922 return base.GetSignatureForError () + parameters
.GetSignatureForError ();
1925 public override MemberCache MemberCache
{
1931 public override AttributeTargets AttributeTargets
{
1933 return AttributeTargets
.Method
| AttributeTargets
.ReturnValue
;
1937 public override string DocCommentHeader
{
1938 get { return "M:"; }
1941 public new void VerifyClsCompliance ()
1943 foreach (TypeParameter tp
in TypeParameters
) {
1944 if (tp
.Constraints
== null)
1947 tp
.Constraints
.VerifyClsCompliance (Report
);
1952 partial class TypeManager
1954 public static TypeContainer
LookupGenericTypeContainer (Type t
)
1956 t
= DropGenericTypeArguments (t
);
1957 return LookupTypeContainer (t
);
1960 public static Variance
GetTypeParameterVariance (Type type
)
1962 TypeParameter tparam
= LookupTypeParameter (type
);
1964 return tparam
.Variance
;
1966 switch (type
.GenericParameterAttributes
& GenericParameterAttributes
.VarianceMask
) {
1967 case GenericParameterAttributes
.Covariant
:
1968 return Variance
.Covariant
;
1969 case GenericParameterAttributes
.Contravariant
:
1970 return Variance
.Contravariant
;
1972 return Variance
.None
;
1976 public static Variance
CheckTypeVariance (Type t
, Variance expected
, IMemberContext member
)
1978 TypeParameter tp
= LookupTypeParameter (t
);
1980 Variance v
= tp
.Variance
;
1981 if (expected
== Variance
.None
&& v
!= expected
||
1982 expected
== Variance
.Covariant
&& v
== Variance
.Contravariant
||
1983 expected
== Variance
.Contravariant
&& v
== Variance
.Covariant
)
1984 tp
.ErrorInvalidVariance (member
, expected
);
1989 if (t
.IsGenericType
) {
1990 Type
[] targs_definition
= GetTypeArguments (DropGenericTypeArguments (t
));
1991 Type
[] targs
= GetTypeArguments (t
);
1992 for (int i
= 0; i
< targs_definition
.Length
; ++i
) {
1993 Variance v
= GetTypeParameterVariance (targs_definition
[i
]);
1994 CheckTypeVariance (targs
[i
], (Variance
) ((int)v
* (int)expected
), member
);
2001 return CheckTypeVariance (GetElementType (t
), expected
, member
);
2003 return Variance
.None
;
2006 public static bool IsVariantOf (Type type1
, Type type2
)
2008 if (!type1
.IsGenericType
|| !type2
.IsGenericType
)
2011 Type generic_target_type
= DropGenericTypeArguments (type2
);
2012 if (DropGenericTypeArguments (type1
) != generic_target_type
)
2015 Type
[] t1
= GetTypeArguments (type1
);
2016 Type
[] t2
= GetTypeArguments (type2
);
2017 Type
[] targs_definition
= GetTypeArguments (generic_target_type
);
2018 for (int i
= 0; i
< targs_definition
.Length
; ++i
) {
2019 Variance v
= GetTypeParameterVariance (targs_definition
[i
]);
2020 if (v
== Variance
.None
) {
2026 if (v
== Variance
.Covariant
) {
2027 if (!Convert
.ImplicitReferenceConversionExists (new EmptyExpression (t1
[i
]), t2
[i
]))
2029 } else if (!Convert
.ImplicitReferenceConversionExists (new EmptyExpression (t2
[i
]), t1
[i
])) {
2038 /// Check whether `a' and `b' may become equal generic types.
2039 /// The algorithm to do that is a little bit complicated.
2041 public static bool MayBecomeEqualGenericTypes (Type a
, Type b
, Type
[] class_inferred
,
2042 Type
[] method_inferred
)
2044 if (a
.IsGenericParameter
) {
2046 // If a is an array of a's type, they may never
2050 b
= GetElementType (b
);
2056 // If b is a generic parameter or an actual type,
2057 // they may become equal:
2059 // class X<T,U> : I<T>, I<U>
2060 // class X<T> : I<T>, I<float>
2062 if (b
.IsGenericParameter
|| !b
.IsGenericType
) {
2063 int pos
= a
.GenericParameterPosition
;
2064 Type
[] args
= a
.DeclaringMethod
!= null ? method_inferred
: class_inferred
;
2065 if (args
[pos
] == null) {
2070 return args
[pos
] == a
;
2074 // We're now comparing a type parameter with a
2075 // generic instance. They may become equal unless
2076 // the type parameter appears anywhere in the
2077 // generic instance:
2079 // class X<T,U> : I<T>, I<X<U>>
2080 // -> error because you could instanciate it as
2083 // class X<T> : I<T>, I<X<T>> -> ok
2086 Type
[] bargs
= GetTypeArguments (b
);
2087 for (int i
= 0; i
< bargs
.Length
; i
++) {
2088 if (a
.Equals (bargs
[i
]))
2095 if (b
.IsGenericParameter
)
2096 return MayBecomeEqualGenericTypes (b
, a
, class_inferred
, method_inferred
);
2099 // At this point, neither a nor b are a type parameter.
2101 // If one of them is a generic instance, let
2102 // MayBecomeEqualGenericInstances() compare them (if the
2103 // other one is not a generic instance, they can never
2107 if (a
.IsGenericType
|| b
.IsGenericType
)
2108 return MayBecomeEqualGenericInstances (a
, b
, class_inferred
, method_inferred
);
2111 // If both of them are arrays.
2114 if (a
.IsArray
&& b
.IsArray
) {
2115 if (a
.GetArrayRank () != b
.GetArrayRank ())
2118 a
= GetElementType (a
);
2119 b
= GetElementType (b
);
2121 return MayBecomeEqualGenericTypes (a
, b
, class_inferred
, method_inferred
);
2125 // Ok, two ordinary types.
2128 return a
.Equals (b
);
2132 // Checks whether two generic instances may become equal for some
2133 // particular instantiation (26.3.1).
2135 public static bool MayBecomeEqualGenericInstances (Type a
, Type b
,
2136 Type
[] class_inferred
,
2137 Type
[] method_inferred
)
2139 if (!a
.IsGenericType
|| !b
.IsGenericType
)
2141 if (a
.GetGenericTypeDefinition () != b
.GetGenericTypeDefinition ())
2144 return MayBecomeEqualGenericInstances (
2145 GetTypeArguments (a
), GetTypeArguments (b
), class_inferred
, method_inferred
);
2148 public static bool MayBecomeEqualGenericInstances (Type
[] aargs
, Type
[] bargs
,
2149 Type
[] class_inferred
,
2150 Type
[] method_inferred
)
2152 if (aargs
.Length
!= bargs
.Length
)
2155 for (int i
= 0; i
< aargs
.Length
; i
++) {
2156 if (!MayBecomeEqualGenericTypes (aargs
[i
], bargs
[i
], class_inferred
, method_inferred
))
2164 /// Type inference. Try to infer the type arguments from `method',
2165 /// which is invoked with the arguments `arguments'. This is used
2166 /// when resolving an Invocation or a DelegateInvocation and the user
2167 /// did not explicitly specify type arguments.
2169 public static int InferTypeArguments (ResolveContext ec
, Arguments arguments
, ref MethodBase method
)
2171 ATypeInference ti
= ATypeInference
.CreateInstance (arguments
);
2172 Type
[] i_args
= ti
.InferMethodArguments (ec
, method
);
2174 return ti
.InferenceScore
;
2176 if (i_args
.Length
== 0)
2179 method
= ((MethodInfo
) method
).MakeGenericMethod (i_args
);
2184 public static bool InferTypeArguments (ResolveContext ec, AParametersCollection param, ref MethodBase method)
2186 if (!TypeManager.IsGenericMethod (method))
2189 ATypeInference ti = ATypeInference.CreateInstance (DelegateCreation.CreateDelegateMethodArguments (param, Location.Null));
2190 Type[] i_args = ti.InferDelegateArguments (ec, method);
2194 method = ((MethodInfo) method).MakeGenericMethod (i_args);
2200 abstract class ATypeInference
2202 protected readonly Arguments arguments
;
2203 protected readonly int arg_count
;
2205 protected ATypeInference (Arguments arguments
)
2207 this.arguments
= arguments
;
2208 if (arguments
!= null)
2209 arg_count
= arguments
.Count
;
2212 public static ATypeInference
CreateInstance (Arguments arguments
)
2214 return new TypeInference (arguments
);
2217 public virtual int InferenceScore
{
2219 return int.MaxValue
;
2223 public abstract Type
[] InferMethodArguments (ResolveContext ec
, MethodBase method
);
2224 // public abstract Type[] InferDelegateArguments (ResolveContext ec, MethodBase method);
2228 // Implements C# type inference
2230 class TypeInference
: ATypeInference
2233 // Tracks successful rate of type inference
2235 int score
= int.MaxValue
;
2237 public TypeInference (Arguments arguments
)
2242 public override int InferenceScore
{
2249 public override Type[] InferDelegateArguments (ResolveContext ec, MethodBase method)
2251 AParametersCollection pd = TypeManager.GetParameterData (method);
2252 if (arg_count != pd.Count)
2255 Type[] d_gargs = method.GetGenericArguments ();
2256 TypeInferenceContext context = new TypeInferenceContext (d_gargs);
2258 // A lower-bound inference is made from each argument type Uj of D
2259 // to the corresponding parameter type Tj of M
2260 for (int i = 0; i < arg_count; ++i) {
2261 Type t = pd.Types [i];
2262 if (!t.IsGenericParameter)
2265 context.LowerBoundInference (arguments [i].Expr.Type, t);
2268 if (!context.FixAllTypes (ec))
2271 return context.InferredTypeArguments;
2274 public override Type
[] InferMethodArguments (ResolveContext ec
, MethodBase method
)
2276 Type
[] method_generic_args
= method
.GetGenericArguments ();
2277 TypeInferenceContext context
= new TypeInferenceContext (method_generic_args
);
2278 if (!context
.UnfixedVariableExists
)
2279 return Type
.EmptyTypes
;
2281 AParametersCollection pd
= TypeManager
.GetParameterData (method
);
2282 if (!InferInPhases (ec
, context
, pd
))
2285 return context
.InferredTypeArguments
;
2289 // Implements method type arguments inference
2291 bool InferInPhases (ResolveContext ec
, TypeInferenceContext tic
, AParametersCollection methodParameters
)
2293 int params_arguments_start
;
2294 if (methodParameters
.HasParams
) {
2295 params_arguments_start
= methodParameters
.Count
- 1;
2297 params_arguments_start
= arg_count
;
2300 Type
[] ptypes
= methodParameters
.Types
;
2303 // The first inference phase
2305 Type method_parameter
= null;
2306 for (int i
= 0; i
< arg_count
; i
++) {
2307 Argument a
= arguments
[i
];
2311 if (i
< params_arguments_start
) {
2312 method_parameter
= methodParameters
.Types
[i
];
2313 } else if (i
== params_arguments_start
) {
2314 if (arg_count
== params_arguments_start
+ 1 && TypeManager
.HasElementType (a
.Type
))
2315 method_parameter
= methodParameters
.Types
[params_arguments_start
];
2317 method_parameter
= TypeManager
.GetElementType (methodParameters
.Types
[params_arguments_start
]);
2319 ptypes
= (Type
[]) ptypes
.Clone ();
2320 ptypes
[i
] = method_parameter
;
2324 // When a lambda expression, an anonymous method
2325 // is used an explicit argument type inference takes a place
2327 AnonymousMethodExpression am
= a
.Expr
as AnonymousMethodExpression
;
2329 if (am
.ExplicitTypeInference (ec
, tic
, method_parameter
))
2335 score
-= tic
.ExactInference (a
.Type
, method_parameter
);
2339 if (a
.Expr
.Type
== TypeManager
.null_type
)
2342 if (TypeManager
.IsValueType (method_parameter
)) {
2343 score
-= tic
.LowerBoundInference (a
.Type
, method_parameter
);
2348 // Otherwise an output type inference is made
2350 score
-= tic
.OutputTypeInference (ec
, a
.Expr
, method_parameter
);
2354 // Part of the second phase but because it happens only once
2355 // we don't need to call it in cycle
2357 bool fixed_any
= false;
2358 if (!tic
.FixIndependentTypeArguments (ec
, ptypes
, ref fixed_any
))
2361 return DoSecondPhase (ec
, tic
, ptypes
, !fixed_any
);
2364 bool DoSecondPhase (ResolveContext ec
, TypeInferenceContext tic
, Type
[] methodParameters
, bool fixDependent
)
2366 bool fixed_any
= false;
2367 if (fixDependent
&& !tic
.FixDependentTypes (ec
, ref fixed_any
))
2370 // If no further unfixed type variables exist, type inference succeeds
2371 if (!tic
.UnfixedVariableExists
)
2374 if (!fixed_any
&& fixDependent
)
2377 // For all arguments where the corresponding argument output types
2378 // contain unfixed type variables but the input types do not,
2379 // an output type inference is made
2380 for (int i
= 0; i
< arg_count
; i
++) {
2382 // Align params arguments
2383 Type t_i
= methodParameters
[i
>= methodParameters
.Length
? methodParameters
.Length
- 1: i
];
2385 if (!TypeManager
.IsDelegateType (t_i
)) {
2386 if (TypeManager
.DropGenericTypeArguments (t_i
) != TypeManager
.expression_type
)
2389 t_i
= t_i
.GetGenericArguments () [0];
2392 MethodInfo mi
= Delegate
.GetInvokeMethod (ec
.Compiler
, t_i
, t_i
);
2393 Type rtype
= mi
.ReturnType
;
2396 // Blablabla, because reflection does not work with dynamic types
2397 Type
[] g_args
= t_i
.GetGenericArguments ();
2398 rtype
= g_args
[rtype
.GenericParameterPosition
];
2401 if (tic
.IsReturnTypeNonDependent (ec
, mi
, rtype
))
2402 score
-= tic
.OutputTypeInference (ec
, arguments
[i
].Expr
, t_i
);
2406 return DoSecondPhase (ec
, tic
, methodParameters
, true);
2410 public class TypeInferenceContext
2421 public readonly Type Type
;
2422 public readonly BoundKind Kind
;
2424 public BoundInfo (Type type
, BoundKind kind
)
2430 public override int GetHashCode ()
2432 return Type
.GetHashCode ();
2435 public override bool Equals (object obj
)
2437 BoundInfo a
= (BoundInfo
) obj
;
2438 return Type
== a
.Type
&& Kind
== a
.Kind
;
2442 readonly Type
[] unfixed_types
;
2443 readonly Type
[] fixed_types
;
2444 readonly List
<BoundInfo
>[] bounds
;
2447 public TypeInferenceContext (Type
[] typeArguments
)
2449 if (typeArguments
.Length
== 0)
2450 throw new ArgumentException ("Empty generic arguments");
2452 fixed_types
= new Type
[typeArguments
.Length
];
2453 for (int i
= 0; i
< typeArguments
.Length
; ++i
) {
2454 if (typeArguments
[i
].IsGenericParameter
) {
2455 if (bounds
== null) {
2456 bounds
= new List
<BoundInfo
> [typeArguments
.Length
];
2457 unfixed_types
= new Type
[typeArguments
.Length
];
2459 unfixed_types
[i
] = typeArguments
[i
];
2461 fixed_types
[i
] = typeArguments
[i
];
2467 // Used together with AddCommonTypeBound fo implement
2468 // 7.4.2.13 Finding the best common type of a set of expressions
2470 public TypeInferenceContext ()
2472 fixed_types
= new Type
[1];
2473 unfixed_types
= new Type
[1];
2474 unfixed_types
[0] = InternalType
.Arglist
; // it can be any internal type
2475 bounds
= new List
<BoundInfo
> [1];
2478 public Type
[] InferredTypeArguments
{
2484 public void AddCommonTypeBound (Type type
)
2486 AddToBounds (new BoundInfo (type
, BoundKind
.Lower
), 0);
2489 void AddToBounds (BoundInfo bound
, int index
)
2492 // Some types cannot be used as type arguments
2494 if (bound
.Type
== TypeManager
.void_type
|| bound
.Type
.IsPointer
)
2497 var a
= bounds
[index
];
2499 a
= new List
<BoundInfo
> ();
2502 if (a
.Contains (bound
))
2507 // SPEC: does not cover type inference using constraints
2509 //if (TypeManager.IsGenericParameter (t)) {
2510 // GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
2511 // if (constraints != null) {
2512 // //if (constraints.EffectiveBaseClass != null)
2513 // // t = constraints.EffectiveBaseClass;
2519 bool AllTypesAreFixed (Type
[] types
)
2521 foreach (Type t
in types
) {
2522 if (t
.IsGenericParameter
) {
2528 if (t
.IsGenericType
)
2529 return AllTypesAreFixed (t
.GetGenericArguments ());
2536 // 26.3.3.8 Exact Inference
2538 public int ExactInference (Type u
, Type v
)
2540 // If V is an array type
2545 if (u
.GetArrayRank () != v
.GetArrayRank ())
2548 return ExactInference (TypeManager
.GetElementType (u
), TypeManager
.GetElementType (v
));
2551 // If V is constructed type and U is constructed type
2552 if (v
.IsGenericType
&& !v
.IsGenericTypeDefinition
) {
2553 if (!u
.IsGenericType
)
2556 Type
[] ga_u
= u
.GetGenericArguments ();
2557 Type
[] ga_v
= v
.GetGenericArguments ();
2558 if (ga_u
.Length
!= ga_v
.Length
)
2562 for (int i
= 0; i
< ga_u
.Length
; ++i
)
2563 score
+= ExactInference (ga_u
[i
], ga_v
[i
]);
2565 return score
> 0 ? 1 : 0;
2568 // If V is one of the unfixed type arguments
2569 int pos
= IsUnfixed (v
);
2573 AddToBounds (new BoundInfo (u
, BoundKind
.Exact
), pos
);
2577 public bool FixAllTypes (ResolveContext ec
)
2579 for (int i
= 0; i
< unfixed_types
.Length
; ++i
) {
2580 if (!FixType (ec
, i
))
2587 // All unfixed type variables Xi are fixed for which all of the following hold:
2588 // a, There is at least one type variable Xj that depends on Xi
2589 // b, Xi has a non-empty set of bounds
2591 public bool FixDependentTypes (ResolveContext ec
, ref bool fixed_any
)
2593 for (int i
= 0; i
< unfixed_types
.Length
; ++i
) {
2594 if (unfixed_types
[i
] == null)
2597 if (bounds
[i
] == null)
2600 if (!FixType (ec
, i
))
2610 // All unfixed type variables Xi which depend on no Xj are fixed
2612 public bool FixIndependentTypeArguments (ResolveContext ec
, Type
[] methodParameters
, ref bool fixed_any
)
2614 var types_to_fix
= new List
<Type
> (unfixed_types
);
2615 for (int i
= 0; i
< methodParameters
.Length
; ++i
) {
2616 Type t
= methodParameters
[i
];
2618 if (!TypeManager
.IsDelegateType (t
)) {
2619 if (TypeManager
.DropGenericTypeArguments (t
) != TypeManager
.expression_type
)
2622 t
= t
.GetGenericArguments () [0];
2625 if (t
.IsGenericParameter
)
2628 MethodInfo invoke
= Delegate
.GetInvokeMethod (ec
.Compiler
, t
, t
);
2629 Type rtype
= invoke
.ReturnType
;
2630 if (!rtype
.IsGenericParameter
&& !rtype
.IsGenericType
)
2634 // Blablabla, because reflection does not work with dynamic types
2635 if (rtype
.IsGenericParameter
) {
2636 Type
[] g_args
= t
.GetGenericArguments ();
2637 rtype
= g_args
[rtype
.GenericParameterPosition
];
2640 // Remove dependent types, they cannot be fixed yet
2641 RemoveDependentTypes (types_to_fix
, rtype
);
2644 foreach (Type t
in types_to_fix
) {
2648 int idx
= IsUnfixed (t
);
2649 if (idx
>= 0 && !FixType (ec
, idx
)) {
2654 fixed_any
= types_to_fix
.Count
> 0;
2661 public bool FixType (ResolveContext ec
, int i
)
2663 // It's already fixed
2664 if (unfixed_types
[i
] == null)
2665 throw new InternalErrorException ("Type argument has been already fixed");
2670 var candidates
= bounds
[i
];
2671 if (candidates
== null)
2674 if (candidates
.Count
== 1) {
2675 unfixed_types
[i
] = null;
2676 Type t
= candidates
[0].Type
;
2677 if (t
== TypeManager
.null_type
)
2680 fixed_types
[i
] = t
;
2685 // Determines a unique type from which there is
2686 // a standard implicit conversion to all the other
2689 Type best_candidate
= null;
2691 int candidates_count
= candidates
.Count
;
2692 for (int ci
= 0; ci
< candidates_count
; ++ci
) {
2693 BoundInfo bound
= (BoundInfo
)candidates
[ci
];
2694 for (cii
= 0; cii
< candidates_count
; ++cii
) {
2698 BoundInfo cbound
= (BoundInfo
) candidates
[cii
];
2700 // Same type parameters with different bounds
2701 if (cbound
.Type
== bound
.Type
) {
2702 if (bound
.Kind
!= BoundKind
.Exact
)
2708 if (bound
.Kind
== BoundKind
.Exact
|| cbound
.Kind
== BoundKind
.Exact
) {
2709 if (cbound
.Kind
!= BoundKind
.Exact
) {
2710 if (!Convert
.ImplicitConversionExists (ec
, new TypeExpression (cbound
.Type
, Location
.Null
), bound
.Type
)) {
2717 if (bound
.Kind
!= BoundKind
.Exact
) {
2718 if (!Convert
.ImplicitConversionExists (ec
, new TypeExpression (bound
.Type
, Location
.Null
), cbound
.Type
)) {
2729 if (bound
.Kind
== BoundKind
.Lower
) {
2730 if (!Convert
.ImplicitConversionExists (ec
, new TypeExpression (cbound
.Type
, Location
.Null
), bound
.Type
)) {
2734 if (!Convert
.ImplicitConversionExists (ec
, new TypeExpression (bound
.Type
, Location
.Null
), cbound
.Type
)) {
2740 if (cii
!= candidates_count
)
2743 if (best_candidate
!= null && best_candidate
!= bound
.Type
)
2746 best_candidate
= bound
.Type
;
2749 if (best_candidate
== null)
2752 unfixed_types
[i
] = null;
2753 fixed_types
[i
] = best_candidate
;
2758 // Uses inferred types to inflate delegate type argument
2760 public Type
InflateGenericArgument (Type parameter
)
2762 if (parameter
.IsGenericParameter
) {
2764 // Inflate method generic argument (MVAR) only
2766 if (parameter
.DeclaringMethod
== null)
2769 return fixed_types
[parameter
.GenericParameterPosition
];
2772 if (parameter
.IsGenericType
) {
2773 Type
[] parameter_targs
= parameter
.GetGenericArguments ();
2774 for (int ii
= 0; ii
< parameter_targs
.Length
; ++ii
) {
2775 parameter_targs
[ii
] = InflateGenericArgument (parameter_targs
[ii
]);
2777 return parameter
.GetGenericTypeDefinition ().MakeGenericType (parameter_targs
);
2784 // Tests whether all delegate input arguments are fixed and generic output type
2785 // requires output type inference
2787 public bool IsReturnTypeNonDependent (ResolveContext ec
, MethodInfo invoke
, Type returnType
)
2789 if (returnType
.IsGenericParameter
) {
2790 if (IsFixed (returnType
))
2792 } else if (returnType
.IsGenericType
) {
2793 if (TypeManager
.IsDelegateType (returnType
)) {
2794 invoke
= Delegate
.GetInvokeMethod (ec
.Compiler
, returnType
, returnType
);
2795 return IsReturnTypeNonDependent (ec
, invoke
, invoke
.ReturnType
);
2798 Type
[] g_args
= returnType
.GetGenericArguments ();
2800 // At least one unfixed return type has to exist
2801 if (AllTypesAreFixed (g_args
))
2807 // All generic input arguments have to be fixed
2808 AParametersCollection d_parameters
= TypeManager
.GetParameterData (invoke
);
2809 return AllTypesAreFixed (d_parameters
.Types
);
2812 bool IsFixed (Type type
)
2814 return IsUnfixed (type
) == -1;
2817 int IsUnfixed (Type type
)
2819 if (!type
.IsGenericParameter
)
2822 //return unfixed_types[type.GenericParameterPosition] != null;
2823 for (int i
= 0; i
< unfixed_types
.Length
; ++i
) {
2824 if (unfixed_types
[i
] == type
)
2832 // 26.3.3.9 Lower-bound Inference
2834 public int LowerBoundInference (Type u
, Type v
)
2836 return LowerBoundInference (u
, v
, false);
2840 // Lower-bound (false) or Upper-bound (true) inference based on inversed argument
2842 int LowerBoundInference (Type u
, Type v
, bool inversed
)
2844 // If V is one of the unfixed type arguments
2845 int pos
= IsUnfixed (v
);
2847 AddToBounds (new BoundInfo (u
, inversed
? BoundKind
.Upper
: BoundKind
.Lower
), pos
);
2851 // If U is an array type
2853 int u_dim
= u
.GetArrayRank ();
2855 Type u_i
= TypeManager
.GetElementType (u
);
2858 if (u_dim
!= v
.GetArrayRank ())
2861 v_i
= TypeManager
.GetElementType (v
);
2863 if (TypeManager
.IsValueType (u_i
))
2864 return ExactInference (u_i
, v_i
);
2866 return LowerBoundInference (u_i
, v_i
, inversed
);
2872 if (v
.IsGenericType
) {
2873 Type g_v
= v
.GetGenericTypeDefinition ();
2874 if ((g_v
!= TypeManager
.generic_ilist_type
) && (g_v
!= TypeManager
.generic_icollection_type
) &&
2875 (g_v
!= TypeManager
.generic_ienumerable_type
))
2878 v_i
= TypeManager
.TypeToCoreType (TypeManager
.GetTypeArguments (v
) [0]);
2879 if (TypeManager
.IsValueType (u_i
))
2880 return ExactInference (u_i
, v_i
);
2882 return LowerBoundInference (u_i
, v_i
);
2884 } else if (v
.IsGenericType
&& !v
.IsGenericTypeDefinition
) {
2886 // if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
2887 // such that U is identical to, inherits from (directly or indirectly),
2888 // or implements (directly or indirectly) C<U1..Uk>
2890 var u_candidates
= new List
<Type
> ();
2891 if (u
.IsGenericType
)
2892 u_candidates
.Add (u
);
2894 for (Type t
= u
.BaseType
; t
!= null; t
= t
.BaseType
) {
2895 if (t
.IsGenericType
&& !t
.IsGenericTypeDefinition
)
2896 u_candidates
.Add (t
);
2899 // TODO: Implement GetGenericInterfaces only and remove
2900 // the if from foreach
2901 u_candidates
.AddRange (TypeManager
.GetInterfaces (u
));
2903 Type open_v
= v
.GetGenericTypeDefinition ();
2904 Type
[] unique_candidate_targs
= null;
2905 Type
[] ga_v
= v
.GetGenericArguments ();
2906 foreach (Type u_candidate
in u_candidates
) {
2907 if (!u_candidate
.IsGenericType
|| u_candidate
.IsGenericTypeDefinition
)
2910 if (TypeManager
.DropGenericTypeArguments (u_candidate
) != open_v
)
2914 // The unique set of types U1..Uk means that if we have an interface I<T>,
2915 // class U : I<int>, I<long> then no type inference is made when inferring
2916 // type I<T> by applying type U because T could be int or long
2918 if (unique_candidate_targs
!= null) {
2919 Type
[] second_unique_candidate_targs
= u_candidate
.GetGenericArguments ();
2920 if (TypeManager
.IsEqual (unique_candidate_targs
, second_unique_candidate_targs
)) {
2921 unique_candidate_targs
= second_unique_candidate_targs
;
2926 // This should always cause type inference failure
2932 unique_candidate_targs
= u_candidate
.GetGenericArguments ();
2935 if (unique_candidate_targs
!= null) {
2936 Type
[] ga_open_v
= open_v
.GetGenericArguments ();
2938 for (int i
= 0; i
< unique_candidate_targs
.Length
; ++i
) {
2939 Variance variance
= TypeManager
.GetTypeParameterVariance (ga_open_v
[i
]);
2941 Type u_i
= unique_candidate_targs
[i
];
2942 if (variance
== Variance
.None
|| TypeManager
.IsValueType (u_i
)) {
2943 if (ExactInference (u_i
, ga_v
[i
]) == 0)
2946 bool upper_bound
= (variance
== Variance
.Contravariant
&& !inversed
) ||
2947 (variance
== Variance
.Covariant
&& inversed
);
2949 if (LowerBoundInference (u_i
, ga_v
[i
], upper_bound
) == 0)
2961 // 26.3.3.6 Output Type Inference
2963 public int OutputTypeInference (ResolveContext ec
, Expression e
, Type t
)
2965 // If e is a lambda or anonymous method with inferred return type
2966 AnonymousMethodExpression ame
= e
as AnonymousMethodExpression
;
2968 Type rt
= ame
.InferReturnType (ec
, this, t
);
2969 MethodInfo invoke
= Delegate
.GetInvokeMethod (ec
.Compiler
, t
, t
);
2972 AParametersCollection pd
= TypeManager
.GetParameterData (invoke
);
2973 return ame
.Parameters
.Count
== pd
.Count
? 1 : 0;
2976 Type rtype
= invoke
.ReturnType
;
2978 // Blablabla, because reflection does not work with dynamic types
2979 Type
[] g_args
= t
.GetGenericArguments ();
2980 rtype
= g_args
[rtype
.GenericParameterPosition
];
2982 return LowerBoundInference (rt
, rtype
) + 1;
2986 // if E is a method group and T is a delegate type or expression tree type
2987 // return type Tb with parameter types T1..Tk and return type Tb, and overload
2988 // resolution of E with the types T1..Tk yields a single method with return type U,
2989 // then a lower-bound inference is made from U for Tb.
2991 if (e
is MethodGroupExpr
) {
2992 // TODO: Or expression tree
2993 if (!TypeManager
.IsDelegateType (t
))
2996 MethodInfo invoke
= Delegate
.GetInvokeMethod (ec
.Compiler
, t
, t
);
2997 Type rtype
= invoke
.ReturnType
;
2999 // Blablabla, because reflection does not work with dynamic types
3000 Type
[] g_args
= t
.GetGenericArguments ();
3001 rtype
= g_args
[rtype
.GenericParameterPosition
];
3004 if (!TypeManager
.IsGenericType (rtype
))
3007 MethodGroupExpr mg
= (MethodGroupExpr
) e
;
3008 Arguments args
= DelegateCreation
.CreateDelegateMethodArguments (TypeManager
.GetParameterData (invoke
), e
.Location
);
3009 mg
= mg
.OverloadResolve (ec
, ref args
, true, e
.Location
);
3013 // TODO: What should happen when return type is of generic type ?
3014 throw new NotImplementedException ();
3015 // return LowerBoundInference (null, rtype) + 1;
3019 // if e is an expression with type U, then
3020 // a lower-bound inference is made from U for T
3022 return LowerBoundInference (e
.Type
, t
) * 2;
3025 void RemoveDependentTypes (List
<Type
> types
, Type returnType
)
3027 int idx
= IsUnfixed (returnType
);
3033 if (returnType
.IsGenericType
) {
3034 foreach (Type t
in returnType
.GetGenericArguments ()) {
3035 RemoveDependentTypes (types
, t
);
3040 public bool UnfixedVariableExists
{
3042 if (unfixed_types
== null)
3045 foreach (Type ut
in unfixed_types
)