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; }
197 public enum SpecialConstraint
205 /// Tracks the constraints for a type parameter from a generic type definition.
207 public class Constraints
: GenericConstraints
{
209 ArrayList constraints
;
213 // name is the identifier, constraints is an arraylist of
214 // Expressions (with types) or `true' for the constructor constraint.
216 public Constraints (string name
, ArrayList constraints
,
220 this.constraints
= constraints
;
224 public override string TypeParameter
{
230 public Constraints
Clone ()
232 return new Constraints (name
, constraints
, loc
);
235 GenericParameterAttributes attrs
;
236 TypeExpr class_constraint
;
237 ArrayList iface_constraints
;
238 ArrayList type_param_constraints
;
240 Type class_constraint_type
;
241 Type
[] iface_constraint_types
;
242 Type effective_base_type
;
247 /// Resolve the constraints - but only resolve things into Expression's, not
248 /// into actual types.
250 public bool Resolve (IResolveContext ec
)
255 iface_constraints
= new ArrayList (2); // TODO: Too expensive allocation
256 type_param_constraints
= new ArrayList ();
258 foreach (object obj
in constraints
) {
259 if (HasConstructorConstraint
) {
260 Report
.Error (401, loc
,
261 "The new() constraint must be the last constraint specified");
265 if (obj
is SpecialConstraint
) {
266 SpecialConstraint sc
= (SpecialConstraint
) obj
;
268 if (sc
== SpecialConstraint
.Constructor
) {
269 if (!HasValueTypeConstraint
) {
270 attrs
|= GenericParameterAttributes
.DefaultConstructorConstraint
;
274 Report
.Error (451, loc
, "The `new()' constraint " +
275 "cannot be used with the `struct' constraint");
279 if ((num_constraints
> 0) || HasReferenceTypeConstraint
|| HasValueTypeConstraint
) {
280 Report
.Error (449, loc
, "The `class' or `struct' " +
281 "constraint must be the first constraint specified");
285 if (sc
== SpecialConstraint
.ReferenceType
)
286 attrs
|= GenericParameterAttributes
.ReferenceTypeConstraint
;
288 attrs
|= GenericParameterAttributes
.NotNullableValueTypeConstraint
;
292 int errors
= Report
.Errors
;
293 FullNamedExpression fn
= ((Expression
) obj
).ResolveAsTypeStep (ec
, false);
296 if (errors
!= Report
.Errors
)
299 NamespaceEntry
.Error_NamespaceNotFound (loc
, ((Expression
)obj
).GetSignatureForError ());
304 GenericTypeExpr cexpr
= fn
as GenericTypeExpr
;
306 expr
= cexpr
.ResolveAsBaseTerminal (ec
, false);
308 expr
= ((Expression
) obj
).ResolveAsTypeTerminal (ec
, false);
310 if ((expr
== null) || (expr
.Type
== null))
313 if (!ec
.GenericDeclContainer
.IsAccessibleAs (fn
.Type
)) {
314 Report
.SymbolRelatedToPreviousError (fn
.Type
);
315 Report
.Error (703, loc
,
316 "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
317 fn
.GetSignatureForError (), ec
.GenericDeclContainer
.GetSignatureForError ());
321 TypeParameterExpr texpr
= expr
as TypeParameterExpr
;
323 type_param_constraints
.Add (expr
);
324 else if (expr
.IsInterface
)
325 iface_constraints
.Add (expr
);
326 else if (class_constraint
!= null || iface_constraints
.Count
!= 0) {
327 Report
.Error (406, loc
,
328 "The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
329 expr
.GetSignatureForError ());
331 } else if (HasReferenceTypeConstraint
|| HasValueTypeConstraint
) {
332 Report
.Error (450, loc
, "`{0}': cannot specify both " +
333 "a constraint class and the `class' " +
334 "or `struct' constraint", expr
.GetSignatureForError ());
337 class_constraint
= expr
;
342 ArrayList list
= new ArrayList ();
343 foreach (TypeExpr iface_constraint
in iface_constraints
) {
344 foreach (Type type
in list
) {
345 if (!type
.Equals (iface_constraint
.Type
))
348 Report
.Error (405, loc
,
349 "Duplicate constraint `{0}' for type " +
350 "parameter `{1}'.", iface_constraint
.GetSignatureForError (),
355 list
.Add (iface_constraint
.Type
);
358 foreach (TypeParameterExpr expr
in type_param_constraints
) {
359 foreach (Type type
in list
) {
360 if (!type
.Equals (expr
.Type
))
363 Report
.Error (405, loc
,
364 "Duplicate constraint `{0}' for type " +
365 "parameter `{1}'.", expr
.GetSignatureForError (), name
);
369 list
.Add (expr
.Type
);
372 iface_constraint_types
= new Type
[list
.Count
];
373 list
.CopyTo (iface_constraint_types
, 0);
375 if (class_constraint
!= null) {
376 class_constraint_type
= class_constraint
.Type
;
377 if (class_constraint_type
== null)
380 if (class_constraint_type
.IsSealed
) {
381 if (class_constraint_type
.IsAbstract
)
383 Report
.Error (717, loc
, "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
384 TypeManager
.CSharpName (class_constraint_type
));
388 Report
.Error (701, loc
, "`{0}' is not a valid constraint. A constraint must be an interface, " +
389 "a non-sealed class or a type parameter", TypeManager
.CSharpName(class_constraint_type
));
394 if ((class_constraint_type
== TypeManager
.array_type
) ||
395 (class_constraint_type
== TypeManager
.delegate_type
) ||
396 (class_constraint_type
== TypeManager
.enum_type
) ||
397 (class_constraint_type
== TypeManager
.value_type
) ||
398 (class_constraint_type
== TypeManager
.object_type
) ||
399 class_constraint_type
== TypeManager
.multicast_delegate_type
) {
400 Report
.Error (702, loc
,
401 "A constraint cannot be special class `{0}'",
402 TypeManager
.CSharpName (class_constraint_type
));
407 if (class_constraint_type
!= null)
408 effective_base_type
= class_constraint_type
;
409 else if (HasValueTypeConstraint
)
410 effective_base_type
= TypeManager
.value_type
;
412 effective_base_type
= TypeManager
.object_type
;
414 if ((attrs
& GenericParameterAttributes
.NotNullableValueTypeConstraint
) != 0)
415 attrs
|= GenericParameterAttributes
.DefaultConstructorConstraint
;
421 bool CheckTypeParameterConstraints (TypeParameter tparam
, ref TypeExpr prevConstraint
, ArrayList seen
)
425 Constraints constraints
= tparam
.Constraints
;
426 if (constraints
== null)
429 if (constraints
.HasValueTypeConstraint
) {
430 Report
.Error (456, loc
,
431 "Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
437 // Checks whether there are no conflicts between type parameter constraints
441 // where U : A, B // A and B are not convertible
443 if (constraints
.HasClassConstraint
) {
444 if (prevConstraint
!= null) {
445 Type t2
= constraints
.ClassConstraint
;
446 TypeExpr e2
= constraints
.class_constraint
;
448 if (!Convert
.ImplicitReferenceConversionExists (prevConstraint
, t2
) &&
449 !Convert
.ImplicitReferenceConversionExists (e2
, prevConstraint
.Type
)) {
450 Report
.Error (455, loc
,
451 "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
452 name
, TypeManager
.CSharpName (prevConstraint
.Type
), TypeManager
.CSharpName (t2
));
457 prevConstraint
= constraints
.class_constraint
;
460 if (constraints
.type_param_constraints
== null)
463 foreach (TypeParameterExpr expr
in constraints
.type_param_constraints
) {
464 if (seen
.Contains (expr
.TypeParameter
)) {
465 Report
.Error (454, loc
, "Circular constraint " +
466 "dependency involving `{0}' and `{1}'",
467 tparam
.Name
, expr
.GetSignatureForError ());
471 if (!CheckTypeParameterConstraints (expr
.TypeParameter
, ref prevConstraint
, seen
))
479 /// Resolve the constraints into actual types.
481 public bool ResolveTypes (IResolveContext ec
)
486 resolved_types
= true;
488 foreach (object obj
in constraints
) {
489 GenericTypeExpr cexpr
= obj
as GenericTypeExpr
;
493 if (!cexpr
.CheckConstraints (ec
))
497 if (type_param_constraints
.Count
!= 0) {
498 ArrayList seen
= new ArrayList ();
499 TypeExpr prev_constraint
= class_constraint
;
500 foreach (TypeParameterExpr expr
in type_param_constraints
) {
501 if (!CheckTypeParameterConstraints (expr
.TypeParameter
, ref prev_constraint
, seen
))
507 for (int i
= 0; i
< iface_constraints
.Count
; ++i
) {
508 TypeExpr iface_constraint
= (TypeExpr
) iface_constraints
[i
];
509 iface_constraint
= iface_constraint
.ResolveAsTypeTerminal (ec
, false);
510 if (iface_constraint
== null)
512 iface_constraints
[i
] = iface_constraint
;
515 if (class_constraint
!= null) {
516 class_constraint
= class_constraint
.ResolveAsTypeTerminal (ec
, false);
517 if (class_constraint
== null)
524 public override GenericParameterAttributes Attributes
{
525 get { return attrs; }
528 public override bool HasClassConstraint
{
529 get { return class_constraint != null; }
532 public override Type ClassConstraint
{
533 get { return class_constraint_type; }
536 public override Type
[] InterfaceConstraints
{
537 get { return iface_constraint_types; }
540 public override Type EffectiveBaseClass
{
541 get { return effective_base_type; }
544 public bool IsSubclassOf (Type t
)
546 if ((class_constraint_type
!= null) &&
547 class_constraint_type
.IsSubclassOf (t
))
550 if (iface_constraint_types
== null)
553 foreach (Type iface
in iface_constraint_types
) {
554 if (TypeManager
.IsSubclassOf (iface
, t
))
561 public Location Location
{
568 /// This is used when we're implementing a generic interface method.
569 /// Each method type parameter in implementing method must have the same
570 /// constraints than the corresponding type parameter in the interface
571 /// method. To do that, we're called on each of the implementing method's
574 public bool AreEqual (GenericConstraints gc
)
576 if (gc
.Attributes
!= attrs
)
579 if (HasClassConstraint
!= gc
.HasClassConstraint
)
581 if (HasClassConstraint
&& !TypeManager
.IsEqual (gc
.ClassConstraint
, ClassConstraint
))
584 int gc_icount
= gc
.InterfaceConstraints
!= null ?
585 gc
.InterfaceConstraints
.Length
: 0;
586 int icount
= InterfaceConstraints
!= null ?
587 InterfaceConstraints
.Length
: 0;
589 if (gc_icount
!= icount
)
592 for (int i
= 0; i
< gc
.InterfaceConstraints
.Length
; ++i
) {
593 Type iface
= gc
.InterfaceConstraints
[i
];
594 if (iface
.IsGenericType
)
595 iface
= iface
.GetGenericTypeDefinition ();
598 for (int ii
= 0; i
< InterfaceConstraints
.Length
; ++ii
) {
599 Type check
= InterfaceConstraints
[ii
];
600 if (check
.IsGenericType
)
601 check
= check
.GetGenericTypeDefinition ();
603 if (TypeManager
.IsEqual (iface
, check
)) {
616 public void VerifyClsCompliance ()
618 if (class_constraint_type
!= null && !AttributeTester
.IsClsCompliant (class_constraint_type
))
619 Warning_ConstrainIsNotClsCompliant (class_constraint_type
, class_constraint
.Location
);
621 if (iface_constraint_types
!= null) {
622 for (int i
= 0; i
< iface_constraint_types
.Length
; ++i
) {
623 if (!AttributeTester
.IsClsCompliant (iface_constraint_types
[i
]))
624 Warning_ConstrainIsNotClsCompliant (iface_constraint_types
[i
],
625 ((TypeExpr
)iface_constraints
[i
]).Location
);
630 void Warning_ConstrainIsNotClsCompliant (Type t
, Location loc
)
632 Report
.SymbolRelatedToPreviousError (t
);
633 Report
.Warning (3024, 1, loc
, "Constraint type `{0}' is not CLS-compliant",
634 TypeManager
.CSharpName (t
));
639 /// A type parameter from a generic type definition.
641 public class TypeParameter
: MemberCore
, IMemberContainer
643 static readonly string[] attribute_target
= new string [] { "type parameter" }
;
646 GenericConstraints gc
;
647 Constraints constraints
;
648 GenericTypeParameterBuilder type
;
649 MemberCache member_cache
;
652 public TypeParameter (DeclSpace parent
, DeclSpace decl
, string name
,
653 Constraints constraints
, Attributes attrs
, Variance variance
, Location loc
)
654 : base (parent
, new MemberName (name
, loc
), attrs
)
657 this.constraints
= constraints
;
658 this.variance
= variance
;
659 if (variance
!= Variance
.None
&& !(decl
is Interface
) && !(decl
is Delegate
)) {
660 Report
.Error (-36, loc
, "Generic variance can only be used with interfaces and delegates");
664 public GenericConstraints GenericConstraints
{
665 get { return gc != null ? gc : constraints; }
668 public Constraints Constraints
{
669 get { return constraints; }
672 public DeclSpace DeclSpace
{
676 public Variance Variance
{
677 get { return variance; }
685 /// This is the first method which is called during the resolving
686 /// process; we're called immediately after creating the type parameters
687 /// with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
690 /// We're either called from TypeContainer.DefineType() or from
691 /// GenericMethod.Define() (called from Method.Define()).
693 public void Define (GenericTypeParameterBuilder type
)
695 if (this.type
!= null)
696 throw new InvalidOperationException ();
699 TypeManager
.AddTypeParameter (type
, this);
703 /// This is the second method which is called during the resolving
704 /// process - in case of class type parameters, we're called from
705 /// TypeContainer.ResolveType() - after it resolved the class'es
706 /// base class and interfaces. For method type parameters, we're
707 /// called immediately after Define().
709 /// We're just resolving the constraints into expressions here, we
710 /// don't resolve them into actual types.
712 /// Note that in the special case of partial generic classes, we may be
713 /// called _before_ Define() and we may also be called multiple types.
715 public bool Resolve (DeclSpace ds
)
717 if (constraints
!= null) {
718 if (!constraints
.Resolve (ds
)) {
728 /// This is the third method which is called during the resolving
729 /// process. We're called immediately after calling DefineConstraints()
730 /// on all of the current class'es type parameters.
732 /// Our job is to resolve the constraints to actual types.
734 /// Note that we may have circular dependencies on type parameters - this
735 /// is why Resolve() and ResolveType() are separate.
737 public bool ResolveType (IResolveContext ec
)
739 if (constraints
!= null) {
740 if (!constraints
.ResolveTypes (ec
)) {
750 /// This is the fourth and last method which is called during the resolving
751 /// process. We're called after everything is fully resolved and actually
752 /// register the constraints with SRE and the TypeManager.
754 public bool DefineType (IResolveContext ec
)
756 return DefineType (ec
, null, null, false);
760 /// This is the fith and last method which is called during the resolving
761 /// process. We're called after everything is fully resolved and actually
762 /// register the constraints with SRE and the TypeManager.
764 /// The `builder', `implementing' and `is_override' arguments are only
765 /// applicable to method type parameters.
767 public bool DefineType (IResolveContext ec
, MethodBuilder builder
,
768 MethodInfo implementing
, bool is_override
)
770 if (!ResolveType (ec
))
773 if (implementing
!= null) {
774 if (is_override
&& (constraints
!= null)) {
775 Report
.Error (460, Location
,
776 "`{0}': Cannot specify constraints for overrides or explicit interface implementation methods",
777 TypeManager
.CSharpSignature (builder
));
781 MethodBase mb
= TypeManager
.DropGenericMethodArguments (implementing
);
783 int pos
= type
.GenericParameterPosition
;
784 Type mparam
= mb
.GetGenericArguments () [pos
];
785 GenericConstraints temp_gc
= ReflectionConstraints
.GetConstraints (mparam
);
788 gc
= new InflatedConstraints (temp_gc
, implementing
.DeclaringType
);
789 else if (constraints
!= null)
790 gc
= new InflatedConstraints (constraints
, implementing
.DeclaringType
);
793 if (constraints
!= null) {
796 else if (!constraints
.AreEqual (gc
))
799 if (!is_override
&& (temp_gc
!= null))
804 Report
.SymbolRelatedToPreviousError (implementing
);
807 425, Location
, "The constraints for type " +
808 "parameter `{0}' of method `{1}' must match " +
809 "the constraints for type parameter `{2}' " +
810 "of interface method `{3}'. Consider using " +
811 "an explicit interface implementation instead",
812 Name
, TypeManager
.CSharpSignature (builder
),
813 TypeManager
.CSharpName (mparam
), TypeManager
.CSharpSignature (mb
));
816 } else if (DeclSpace
is CompilerGeneratedClass
) {
817 TypeParameter
[] tparams
= DeclSpace
.TypeParameters
;
818 Type
[] types
= new Type
[tparams
.Length
];
819 for (int i
= 0; i
< tparams
.Length
; i
++)
820 types
[i
] = tparams
[i
].Type
;
822 if (constraints
!= null)
823 gc
= new InflatedConstraints (constraints
, types
);
825 gc
= (GenericConstraints
) constraints
;
828 SetConstraints (type
);
832 public void SetConstraints (GenericTypeParameterBuilder type
)
834 GenericParameterAttributes attr
= GenericParameterAttributes
.None
;
835 if (variance
== Variance
.Contravariant
)
836 attr
|= GenericParameterAttributes
.Contravariant
;
837 else if (variance
== Variance
.Covariant
)
838 attr
|= GenericParameterAttributes
.Covariant
;
841 if (gc
.HasClassConstraint
|| gc
.HasValueTypeConstraint
)
842 type
.SetBaseTypeConstraint (gc
.EffectiveBaseClass
);
844 attr
|= gc
.Attributes
;
845 type
.SetInterfaceConstraints (gc
.InterfaceConstraints
);
846 TypeManager
.RegisterBuilder (type
, gc
.InterfaceConstraints
);
849 type
.SetGenericParameterAttributes (attr
);
853 /// This is called for each part of a partial generic type definition.
855 /// If `new_constraints' is not null and we don't already have constraints,
856 /// they become our constraints. If we already have constraints, we must
857 /// check that they're the same.
860 public bool UpdateConstraints (IResolveContext ec
, Constraints new_constraints
)
863 throw new InvalidOperationException ();
865 if (new_constraints
== null)
868 if (!new_constraints
.Resolve (ec
))
870 if (!new_constraints
.ResolveTypes (ec
))
873 if (constraints
!= null)
874 return constraints
.AreEqual (new_constraints
);
876 constraints
= new_constraints
;
880 public override void Emit ()
882 if (OptAttributes
!= null)
883 OptAttributes
.Emit ();
888 public override string DocCommentHeader
{
890 throw new InvalidOperationException (
891 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
899 public override bool Define ()
904 public override void ApplyAttributeBuilder (Attribute a
, CustomAttributeBuilder cb
, PredefinedAttributes pa
)
906 type
.SetCustomAttribute (cb
);
909 public override AttributeTargets AttributeTargets
{
911 return AttributeTargets
.GenericParameter
;
915 public override string[] ValidAttributeTargets
{
917 return attribute_target
;
925 string IMemberContainer
.Name
{
929 MemberCache IMemberContainer
.BaseCache
{
934 if (gc
.EffectiveBaseClass
.BaseType
== null)
937 return TypeManager
.LookupMemberCache (gc
.EffectiveBaseClass
.BaseType
);
941 bool IMemberContainer
.IsInterface
{
942 get { return false; }
945 MemberList IMemberContainer
.GetMembers (MemberTypes mt
, BindingFlags bf
)
947 throw new NotSupportedException ();
950 public MemberCache MemberCache
{
952 if (member_cache
!= null)
958 Type
[] ifaces
= TypeManager
.ExpandInterfaces (gc
.InterfaceConstraints
);
959 member_cache
= new MemberCache (this, gc
.EffectiveBaseClass
, ifaces
);
965 public MemberList
FindMembers (MemberTypes mt
, BindingFlags bf
,
966 MemberFilter filter
, object criteria
)
969 return MemberList
.Empty
;
971 ArrayList members
= new ArrayList ();
973 if (gc
.HasClassConstraint
) {
974 MemberList list
= TypeManager
.FindMembers (
975 gc
.ClassConstraint
, mt
, bf
, filter
, criteria
);
977 members
.AddRange (list
);
980 Type
[] ifaces
= TypeManager
.ExpandInterfaces (gc
.InterfaceConstraints
);
981 foreach (Type t
in ifaces
) {
982 MemberList list
= TypeManager
.FindMembers (
983 t
, mt
, bf
, filter
, criteria
);
985 members
.AddRange (list
);
988 return new MemberList (members
);
991 public bool IsSubclassOf (Type t
)
996 if (constraints
!= null)
997 return constraints
.IsSubclassOf (t
);
1002 public void InflateConstraints (Type declaring
)
1004 if (constraints
!= null)
1005 gc
= new InflatedConstraints (constraints
, declaring
);
1008 public override bool IsClsComplianceRequired ()
1013 protected class InflatedConstraints
: GenericConstraints
1015 GenericConstraints gc
;
1017 Type class_constraint
;
1018 Type
[] iface_constraints
;
1021 public InflatedConstraints (GenericConstraints gc
, Type declaring
)
1022 : this (gc
, TypeManager
.GetTypeArguments (declaring
))
1025 public InflatedConstraints (GenericConstraints gc
, Type
[] dargs
)
1030 ArrayList list
= new ArrayList ();
1031 if (gc
.HasClassConstraint
)
1032 list
.Add (inflate (gc
.ClassConstraint
));
1033 foreach (Type iface
in gc
.InterfaceConstraints
)
1034 list
.Add (inflate (iface
));
1036 bool has_class_constr
= false;
1037 if (list
.Count
> 0) {
1038 Type first
= (Type
) list
[0];
1039 has_class_constr
= !first
.IsGenericParameter
&& !first
.IsInterface
;
1042 if ((list
.Count
> 0) && has_class_constr
) {
1043 class_constraint
= (Type
) list
[0];
1044 iface_constraints
= new Type
[list
.Count
- 1];
1045 list
.CopyTo (1, iface_constraints
, 0, list
.Count
- 1);
1047 iface_constraints
= new Type
[list
.Count
];
1048 list
.CopyTo (iface_constraints
, 0);
1051 if (HasValueTypeConstraint
)
1052 base_type
= TypeManager
.value_type
;
1053 else if (class_constraint
!= null)
1054 base_type
= class_constraint
;
1056 base_type
= TypeManager
.object_type
;
1059 Type
inflate (Type t
)
1063 if (t
.IsGenericParameter
)
1064 return t
.GenericParameterPosition
< dargs
.Length
? dargs
[t
.GenericParameterPosition
] : t
;
1065 if (t
.IsGenericType
) {
1066 Type
[] args
= t
.GetGenericArguments ();
1067 Type
[] inflated
= new Type
[args
.Length
];
1069 for (int i
= 0; i
< args
.Length
; i
++)
1070 inflated
[i
] = inflate (args
[i
]);
1072 t
= t
.GetGenericTypeDefinition ();
1073 t
= t
.MakeGenericType (inflated
);
1079 public override string TypeParameter
{
1080 get { return gc.TypeParameter; }
1083 public override GenericParameterAttributes Attributes
{
1084 get { return gc.Attributes; }
1087 public override Type ClassConstraint
{
1088 get { return class_constraint; }
1091 public override Type EffectiveBaseClass
{
1092 get { return base_type; }
1095 public override Type
[] InterfaceConstraints
{
1096 get { return iface_constraints; }
1102 /// A TypeExpr which already resolved to a type parameter.
1104 public class TypeParameterExpr
: TypeExpr
{
1105 TypeParameter type_parameter
;
1107 public TypeParameter TypeParameter
{
1109 return type_parameter
;
1113 public TypeParameterExpr (TypeParameter type_parameter
, Location loc
)
1115 this.type_parameter
= type_parameter
;
1119 protected override TypeExpr
DoResolveAsTypeStep (IResolveContext ec
)
1121 throw new NotSupportedException ();
1124 public override FullNamedExpression
ResolveAsTypeStep (IResolveContext ec
, bool silent
)
1126 type
= type_parameter
.Type
;
1127 eclass
= ExprClass
.TypeParameter
;
1131 public override bool IsInterface
{
1132 get { return false; }
1135 public override bool CheckAccessLevel (DeclSpace ds
)
1142 // Tracks the type arguments when instantiating a generic type. It's used
1143 // by both type arguments and type parameters
1145 public class TypeArguments
{
1149 public TypeArguments ()
1151 args
= new ArrayList ();
1154 public TypeArguments (params FullNamedExpression
[] types
)
1156 this.args
= new ArrayList (types
);
1159 public void Add (FullNamedExpression type
)
1164 public void Add (TypeArguments new_args
)
1166 args
.AddRange (new_args
.args
);
1169 // TODO: Should be deleted
1170 public TypeParameterName
[] GetDeclarations ()
1172 return (TypeParameterName
[]) args
.ToArray (typeof (TypeParameterName
));
1176 /// We may only be used after Resolve() is called and return the fully
1179 public Type
[] Arguments
{
1191 public string GetSignatureForError()
1193 StringBuilder sb
= new StringBuilder();
1194 for (int i
= 0; i
< Count
; ++i
)
1196 Expression expr
= (Expression
)args
[i
];
1197 sb
.Append(expr
.GetSignatureForError());
1201 return sb
.ToString();
1205 /// Resolve the type arguments.
1207 public bool Resolve (IResolveContext ec
)
1210 return atypes
.Length
!= 0;
1212 int count
= args
.Count
;
1215 atypes
= new Type
[count
];
1217 for (int i
= 0; i
< count
; i
++){
1218 TypeExpr te
= ((FullNamedExpression
) args
[i
]).ResolveAsTypeTerminal (ec
, false);
1224 atypes
[i
] = te
.Type
;
1226 if (te
.Type
.IsSealed
&& te
.Type
.IsAbstract
) {
1227 Report
.Error (718, te
.Location
, "`{0}': static classes cannot be used as generic arguments",
1228 te
.GetSignatureForError ());
1232 if (te
.Type
.IsPointer
|| TypeManager
.IsSpecialType (te
.Type
)) {
1233 Report
.Error (306, te
.Location
,
1234 "The type `{0}' may not be used as a type argument",
1235 te
.GetSignatureForError ());
1241 atypes
= Type
.EmptyTypes
;
1246 public TypeArguments
Clone ()
1248 TypeArguments copy
= new TypeArguments ();
1249 foreach (Expression ta
in args
)
1256 public class TypeParameterName
: SimpleName
1258 Attributes attributes
;
1261 public TypeParameterName (string name
, Attributes attrs
, Location loc
)
1262 : this (name
, attrs
, Variance
.None
, loc
)
1266 public TypeParameterName (string name
, Attributes attrs
, Variance variance
, Location loc
)
1270 this.variance
= variance
;
1273 public Attributes OptAttributes
{
1279 public Variance Variance
{
1287 /// A reference expression to generic type
1289 class GenericTypeExpr
: TypeExpr
1292 Type
[] gen_params
; // TODO: Waiting for constrains check cleanup
1296 // Should be carefully used only with defined generic containers. Type parameters
1297 // can be used as type arguments in this case.
1299 // TODO: This could be GenericTypeExpr specialization
1301 public GenericTypeExpr (DeclSpace gType
, Location l
)
1303 open_type
= gType
.TypeBuilder
.GetGenericTypeDefinition ();
1305 args
= new TypeArguments ();
1306 foreach (TypeParameter type_param
in gType
.TypeParameters
)
1307 args
.Add (new TypeParameterExpr (type_param
, l
));
1313 /// Instantiate the generic type `t' with the type arguments `args'.
1314 /// Use this constructor if you already know the fully resolved
1317 public GenericTypeExpr (Type t
, TypeArguments args
, Location l
)
1319 open_type
= t
.GetGenericTypeDefinition ();
1325 public TypeArguments TypeArguments
{
1326 get { return args; }
1329 public override string GetSignatureForError ()
1331 return TypeManager
.CSharpName (type
);
1334 protected override TypeExpr
DoResolveAsTypeStep (IResolveContext ec
)
1336 if (eclass
!= ExprClass
.Invalid
)
1339 eclass
= ExprClass
.Type
;
1341 if (!args
.Resolve (ec
))
1344 gen_params
= open_type
.GetGenericArguments ();
1345 Type
[] atypes
= args
.Arguments
;
1347 if (atypes
.Length
!= gen_params
.Length
) {
1348 Namespace
.Error_InvalidNumberOfTypeArguments (open_type
, loc
);
1353 // Now bind the parameters
1355 type
= open_type
.MakeGenericType (atypes
);
1360 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1361 /// after fully resolving the constructed type.
1363 public bool CheckConstraints (IResolveContext ec
)
1365 return ConstraintChecker
.CheckConstraints (ec
, open_type
, gen_params
, args
.Arguments
, loc
);
1368 static bool IsVariant (Type type
)
1370 return (type
.GenericParameterAttributes
& GenericParameterAttributes
.VarianceMask
) != 0;
1373 static bool IsCovariant (Type type
)
1375 return (type
.GenericParameterAttributes
& GenericParameterAttributes
.Covariant
) != 0;
1378 static bool IsContravariant (Type type
)
1380 return (type
.GenericParameterAttributes
& GenericParameterAttributes
.Contravariant
) != 0;
1383 public bool VerifyVariantTypeParameters ()
1385 for (int i
= 0; i
< args
.Count
; i
++) {
1386 Type argument
= args
.Arguments
[i
];
1387 if (argument
.IsGenericParameter
&& IsVariant (argument
)) {
1388 if (IsContravariant (argument
) && !IsContravariant (gen_params
[i
])) {
1389 Report
.Error (-34, loc
, "Contravariant type parameters can only be used " +
1390 "as type arguments in contravariant positions");
1393 else if (IsCovariant (argument
) && !IsCovariant (gen_params
[i
])) {
1394 Report
.Error (-35, loc
, "Covariant type parameters can only be used " +
1395 "as type arguments in covariant positions");
1404 public override bool CheckAccessLevel (DeclSpace ds
)
1406 return ds
.CheckAccessLevel (open_type
);
1409 public override bool IsClass
{
1410 get { return open_type.IsClass; }
1413 public override bool IsValueType
{
1414 get { return TypeManager.IsStruct (open_type); }
1417 public override bool IsInterface
{
1418 get { return open_type.IsInterface; }
1421 public override bool IsSealed
{
1422 get { return open_type.IsSealed; }
1425 public override bool Equals (object obj
)
1427 GenericTypeExpr cobj
= obj
as GenericTypeExpr
;
1431 if ((type
== null) || (cobj
.type
== null))
1434 return type
== cobj
.type
;
1437 public override int GetHashCode ()
1439 return base.GetHashCode ();
1443 public abstract class ConstraintChecker
1445 protected readonly Type
[] gen_params
;
1446 protected readonly Type
[] atypes
;
1447 protected readonly Location loc
;
1449 protected ConstraintChecker (Type
[] gen_params
, Type
[] atypes
, Location loc
)
1451 this.gen_params
= gen_params
;
1452 this.atypes
= atypes
;
1457 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1458 /// after fully resolving the constructed type.
1460 public bool CheckConstraints (IResolveContext ec
)
1462 for (int i
= 0; i
< gen_params
.Length
; i
++) {
1463 if (!CheckConstraints (ec
, i
))
1470 protected bool CheckConstraints (IResolveContext ec
, int index
)
1472 Type atype
= atypes
[index
];
1473 Type ptype
= gen_params
[index
];
1478 Expression aexpr
= new EmptyExpression (atype
);
1480 GenericConstraints gc
= TypeManager
.GetTypeParameterConstraints (ptype
);
1484 bool is_class
, is_struct
;
1485 if (atype
.IsGenericParameter
) {
1486 GenericConstraints agc
= TypeManager
.GetTypeParameterConstraints (atype
);
1488 if (agc
is Constraints
)
1489 ((Constraints
) agc
).Resolve (ec
);
1490 is_class
= agc
.IsReferenceType
;
1491 is_struct
= agc
.IsValueType
;
1493 is_class
= is_struct
= false;
1498 if (!atype
.IsGenericType
)
1500 is_class
= atype
.IsClass
|| atype
.IsInterface
;
1501 is_struct
= TypeManager
.IsValueType (atype
) && !TypeManager
.IsNullableType (atype
);
1505 // First, check the `class' and `struct' constraints.
1507 if (gc
.HasReferenceTypeConstraint
&& !is_class
) {
1508 Report
.Error (452, loc
, "The type `{0}' must be " +
1509 "a reference type in order to use it " +
1510 "as type parameter `{1}' in the " +
1511 "generic type or method `{2}'.",
1512 TypeManager
.CSharpName (atype
),
1513 TypeManager
.CSharpName (ptype
),
1514 GetSignatureForError ());
1516 } else if (gc
.HasValueTypeConstraint
&& !is_struct
) {
1517 Report
.Error (453, loc
, "The type `{0}' must be a " +
1518 "non-nullable value type in order to use it " +
1519 "as type parameter `{1}' in the " +
1520 "generic type or method `{2}'.",
1521 TypeManager
.CSharpName (atype
),
1522 TypeManager
.CSharpName (ptype
),
1523 GetSignatureForError ());
1528 // The class constraint comes next.
1530 if (gc
.HasClassConstraint
) {
1531 if (!CheckConstraint (ec
, ptype
, aexpr
, gc
.ClassConstraint
))
1536 // Now, check the interface constraints.
1538 if (gc
.InterfaceConstraints
!= null) {
1539 foreach (Type it
in gc
.InterfaceConstraints
) {
1540 if (!CheckConstraint (ec
, ptype
, aexpr
, it
))
1546 // Finally, check the constructor constraint.
1549 if (!gc
.HasConstructorConstraint
)
1552 if (TypeManager
.IsBuiltinType (atype
) || TypeManager
.IsValueType (atype
))
1555 if (HasDefaultConstructor (atype
))
1558 Report_SymbolRelatedToPreviousError ();
1559 Report
.SymbolRelatedToPreviousError (atype
);
1560 Report
.Error (310, loc
, "The type `{0}' must have a public " +
1561 "parameterless constructor in order to use it " +
1562 "as parameter `{1}' in the generic type or " +
1564 TypeManager
.CSharpName (atype
),
1565 TypeManager
.CSharpName (ptype
),
1566 GetSignatureForError ());
1570 protected bool CheckConstraint (IResolveContext ec
, Type ptype
, Expression expr
,
1573 if (TypeManager
.HasGenericArguments (ctype
)) {
1574 Type
[] types
= TypeManager
.GetTypeArguments (ctype
);
1576 TypeArguments new_args
= new TypeArguments ();
1578 for (int i
= 0; i
< types
.Length
; i
++) {
1581 if (t
.IsGenericParameter
) {
1582 int pos
= t
.GenericParameterPosition
;
1585 new_args
.Add (new TypeExpression (t
, loc
));
1588 TypeExpr ct
= new GenericTypeExpr (ctype
, new_args
, loc
);
1589 if (ct
.ResolveAsTypeStep (ec
, false) == null)
1592 } else if (ctype
.IsGenericParameter
) {
1593 int pos
= ctype
.GenericParameterPosition
;
1594 if (ctype
.DeclaringMethod
== null) {
1598 ctype
= atypes
[pos
];
1602 if (Convert
.ImplicitStandardConversionExists (expr
, ctype
))
1605 Report_SymbolRelatedToPreviousError ();
1606 Report
.SymbolRelatedToPreviousError (expr
.Type
);
1608 if (TypeManager
.IsNullableType (expr
.Type
) && ctype
.IsInterface
) {
1609 Report
.Error (313, loc
,
1610 "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. " +
1611 "The nullable type `{0}' never satisfies interface constraint of type `{3}'",
1612 TypeManager
.CSharpName (expr
.Type
), TypeManager
.CSharpName (ptype
),
1613 GetSignatureForError (), TypeManager
.CSharpName (ctype
));
1615 Report
.Error (309, loc
,
1616 "The type `{0}' must be convertible to `{1}' in order to " +
1617 "use it as parameter `{2}' in the generic type or method `{3}'",
1618 TypeManager
.CSharpName (expr
.Type
), TypeManager
.CSharpName (ctype
),
1619 TypeManager
.CSharpName (ptype
), GetSignatureForError ());
1624 static bool HasDefaultConstructor (Type atype
)
1626 TypeParameter tparam
= TypeManager
.LookupTypeParameter (atype
);
1627 if (tparam
!= null) {
1628 if (tparam
.GenericConstraints
== null)
1631 return tparam
.GenericConstraints
.HasConstructorConstraint
||
1632 tparam
.GenericConstraints
.HasValueTypeConstraint
;
1635 if (atype
.IsAbstract
)
1639 atype
= TypeManager
.DropGenericTypeArguments (atype
);
1640 if (atype
is TypeBuilder
) {
1641 TypeContainer tc
= TypeManager
.LookupTypeContainer (atype
);
1642 if (tc
.InstanceConstructors
== null) {
1643 atype
= atype
.BaseType
;
1647 foreach (Constructor c
in tc
.InstanceConstructors
) {
1648 if ((c
.ModFlags
& Modifiers
.PUBLIC
) == 0)
1650 if ((c
.Parameters
.FixedParameters
!= null) &&
1651 (c
.Parameters
.FixedParameters
.Length
!= 0))
1653 if (c
.Parameters
.HasArglist
|| c
.Parameters
.HasParams
)
1660 MemberInfo
[] list
= TypeManager
.MemberLookup (null, null, atype
, MemberTypes
.Constructor
,
1661 BindingFlags
.Public
| BindingFlags
.Instance
| BindingFlags
.DeclaredOnly
,
1662 ConstructorInfo
.ConstructorName
, null);
1667 foreach (MethodBase mb
in list
) {
1668 AParametersCollection pd
= TypeManager
.GetParameterData (mb
);
1676 protected abstract string GetSignatureForError ();
1677 protected abstract void Report_SymbolRelatedToPreviousError ();
1679 public static bool CheckConstraints (EmitContext ec
, MethodBase definition
,
1680 MethodBase instantiated
, Location loc
)
1682 MethodConstraintChecker checker
= new MethodConstraintChecker (
1683 definition
, definition
.GetGenericArguments (),
1684 instantiated
.GetGenericArguments (), loc
);
1686 return checker
.CheckConstraints (ec
);
1689 public static bool CheckConstraints (IResolveContext ec
, Type gt
, Type
[] gen_params
,
1690 Type
[] atypes
, Location loc
)
1692 TypeConstraintChecker checker
= new TypeConstraintChecker (
1693 gt
, gen_params
, atypes
, loc
);
1695 return checker
.CheckConstraints (ec
);
1698 protected class MethodConstraintChecker
: ConstraintChecker
1700 MethodBase definition
;
1702 public MethodConstraintChecker (MethodBase definition
, Type
[] gen_params
,
1703 Type
[] atypes
, Location loc
)
1704 : base (gen_params
, atypes
, loc
)
1706 this.definition
= definition
;
1709 protected override string GetSignatureForError ()
1711 return TypeManager
.CSharpSignature (definition
);
1714 protected override void Report_SymbolRelatedToPreviousError ()
1716 Report
.SymbolRelatedToPreviousError (definition
);
1720 protected class TypeConstraintChecker
: ConstraintChecker
1724 public TypeConstraintChecker (Type gt
, Type
[] gen_params
, Type
[] atypes
,
1726 : base (gen_params
, atypes
, loc
)
1731 protected override string GetSignatureForError ()
1733 return TypeManager
.CSharpName (gt
);
1736 protected override void Report_SymbolRelatedToPreviousError ()
1738 Report
.SymbolRelatedToPreviousError (gt
);
1744 /// A generic method definition.
1746 public class GenericMethod
: DeclSpace
1748 FullNamedExpression return_type
;
1749 ParametersCompiled parameters
;
1751 public GenericMethod (NamespaceEntry ns
, DeclSpace parent
, MemberName name
,
1752 FullNamedExpression return_type
, ParametersCompiled parameters
)
1753 : base (ns
, parent
, name
, null)
1755 this.return_type
= return_type
;
1756 this.parameters
= parameters
;
1759 public override TypeBuilder
DefineType ()
1761 throw new Exception ();
1764 public override bool Define ()
1766 for (int i
= 0; i
< TypeParameters
.Length
; i
++)
1767 if (!TypeParameters
[i
].Resolve (this))
1774 /// Define and resolve the type parameters.
1775 /// We're called from Method.Define().
1777 public bool Define (MethodOrOperator m
)
1779 TypeParameterName
[] names
= MemberName
.TypeArguments
.GetDeclarations ();
1780 string[] snames
= new string [names
.Length
];
1781 for (int i
= 0; i
< names
.Length
; i
++) {
1782 string type_argument_name
= names
[i
].Name
;
1783 int idx
= parameters
.GetParameterIndexByName (type_argument_name
);
1787 b
= new Block (null);
1789 b
.Error_AlreadyDeclaredTypeParameter (parameters
[i
].Location
,
1790 type_argument_name
, "method parameter");
1793 snames
[i
] = type_argument_name
;
1796 GenericTypeParameterBuilder
[] gen_params
= m
.MethodBuilder
.DefineGenericParameters (snames
);
1797 for (int i
= 0; i
< TypeParameters
.Length
; i
++)
1798 TypeParameters
[i
].Define (gen_params
[i
]);
1803 for (int i
= 0; i
< TypeParameters
.Length
; i
++) {
1804 if (!TypeParameters
[i
].ResolveType (this))
1812 /// We're called from MethodData.Define() after creating the MethodBuilder.
1814 public bool DefineType (EmitContext ec
, MethodBuilder mb
,
1815 MethodInfo implementing
, bool is_override
)
1817 for (int i
= 0; i
< TypeParameters
.Length
; i
++)
1818 if (!TypeParameters
[i
].DefineType (
1819 ec
, mb
, implementing
, is_override
))
1822 bool ok
= parameters
.Resolve (ec
);
1824 if ((return_type
!= null) && (return_type
.ResolveAsTypeTerminal (ec
, false) == null))
1830 public void EmitAttributes ()
1832 for (int i
= 0; i
< TypeParameters
.Length
; i
++)
1833 TypeParameters
[i
].Emit ();
1835 if (OptAttributes
!= null)
1836 OptAttributes
.Emit ();
1839 public override MemberList
FindMembers (MemberTypes mt
, BindingFlags bf
,
1840 MemberFilter filter
, object criteria
)
1842 throw new Exception ();
1845 public override MemberCache MemberCache
{
1851 public override AttributeTargets AttributeTargets
{
1853 return AttributeTargets
.Method
| AttributeTargets
.ReturnValue
;
1857 public override string DocCommentHeader
{
1858 get { return "M:"; }
1861 public new void VerifyClsCompliance ()
1863 foreach (TypeParameter tp
in TypeParameters
) {
1864 if (tp
.Constraints
== null)
1867 tp
.Constraints
.VerifyClsCompliance ();
1872 public partial class TypeManager
1874 static public Type activator_type
;
1876 public static TypeContainer
LookupGenericTypeContainer (Type t
)
1878 t
= DropGenericTypeArguments (t
);
1879 return LookupTypeContainer (t
);
1883 /// Check whether `a' and `b' may become equal generic types.
1884 /// The algorithm to do that is a little bit complicated.
1886 public static bool MayBecomeEqualGenericTypes (Type a
, Type b
, Type
[] class_inferred
,
1887 Type
[] method_inferred
)
1889 if (a
.IsGenericParameter
) {
1891 // If a is an array of a's type, they may never
1895 b
= GetElementType (b
);
1901 // If b is a generic parameter or an actual type,
1902 // they may become equal:
1904 // class X<T,U> : I<T>, I<U>
1905 // class X<T> : I<T>, I<float>
1907 if (b
.IsGenericParameter
|| !b
.IsGenericType
) {
1908 int pos
= a
.GenericParameterPosition
;
1909 Type
[] args
= a
.DeclaringMethod
!= null ? method_inferred
: class_inferred
;
1910 if (args
[pos
] == null) {
1915 return args
[pos
] == a
;
1919 // We're now comparing a type parameter with a
1920 // generic instance. They may become equal unless
1921 // the type parameter appears anywhere in the
1922 // generic instance:
1924 // class X<T,U> : I<T>, I<X<U>>
1925 // -> error because you could instanciate it as
1928 // class X<T> : I<T>, I<X<T>> -> ok
1931 Type
[] bargs
= GetTypeArguments (b
);
1932 for (int i
= 0; i
< bargs
.Length
; i
++) {
1933 if (a
.Equals (bargs
[i
]))
1940 if (b
.IsGenericParameter
)
1941 return MayBecomeEqualGenericTypes (b
, a
, class_inferred
, method_inferred
);
1944 // At this point, neither a nor b are a type parameter.
1946 // If one of them is a generic instance, let
1947 // MayBecomeEqualGenericInstances() compare them (if the
1948 // other one is not a generic instance, they can never
1952 if (a
.IsGenericType
|| b
.IsGenericType
)
1953 return MayBecomeEqualGenericInstances (a
, b
, class_inferred
, method_inferred
);
1956 // If both of them are arrays.
1959 if (a
.IsArray
&& b
.IsArray
) {
1960 if (a
.GetArrayRank () != b
.GetArrayRank ())
1963 a
= GetElementType (a
);
1964 b
= GetElementType (b
);
1966 return MayBecomeEqualGenericTypes (a
, b
, class_inferred
, method_inferred
);
1970 // Ok, two ordinary types.
1973 return a
.Equals (b
);
1977 // Checks whether two generic instances may become equal for some
1978 // particular instantiation (26.3.1).
1980 public static bool MayBecomeEqualGenericInstances (Type a
, Type b
,
1981 Type
[] class_inferred
,
1982 Type
[] method_inferred
)
1984 if (!a
.IsGenericType
|| !b
.IsGenericType
)
1986 if (a
.GetGenericTypeDefinition () != b
.GetGenericTypeDefinition ())
1989 return MayBecomeEqualGenericInstances (
1990 GetTypeArguments (a
), GetTypeArguments (b
), class_inferred
, method_inferred
);
1993 public static bool MayBecomeEqualGenericInstances (Type
[] aargs
, Type
[] bargs
,
1994 Type
[] class_inferred
,
1995 Type
[] method_inferred
)
1997 if (aargs
.Length
!= bargs
.Length
)
2000 for (int i
= 0; i
< aargs
.Length
; i
++) {
2001 if (!MayBecomeEqualGenericTypes (aargs
[i
], bargs
[i
], class_inferred
, method_inferred
))
2009 /// Type inference. Try to infer the type arguments from `method',
2010 /// which is invoked with the arguments `arguments'. This is used
2011 /// when resolving an Invocation or a DelegateInvocation and the user
2012 /// did not explicitly specify type arguments.
2014 public static int InferTypeArguments (EmitContext ec
,
2015 ArrayList arguments
,
2016 ref MethodBase method
)
2018 ATypeInference ti
= ATypeInference
.CreateInstance (arguments
);
2019 Type
[] i_args
= ti
.InferMethodArguments (ec
, method
);
2021 return ti
.InferenceScore
;
2023 if (i_args
.Length
== 0)
2026 method
= ((MethodInfo
) method
).MakeGenericMethod (i_args
);
2033 public static bool InferTypeArguments (AParametersCollection apd
,
2034 ref MethodBase method
)
2036 if (!TypeManager
.IsGenericMethod (method
))
2039 ATypeInference ti
= ATypeInference
.CreateInstance (ArrayList
.Adapter (apd
.Types
));
2040 Type
[] i_args
= ti
.InferDelegateArguments (method
);
2044 method
= ((MethodInfo
) method
).MakeGenericMethod (i_args
);
2049 abstract class ATypeInference
2051 protected readonly ArrayList arguments
;
2052 protected readonly int arg_count
;
2054 protected ATypeInference (ArrayList arguments
)
2056 this.arguments
= arguments
;
2057 if (arguments
!= null)
2058 arg_count
= arguments
.Count
;
2061 public static ATypeInference
CreateInstance (ArrayList arguments
)
2063 return new TypeInferenceV3 (arguments
);
2066 public virtual int InferenceScore
{
2068 return int.MaxValue
;
2072 public abstract Type
[] InferMethodArguments (EmitContext ec
, MethodBase method
);
2073 public abstract Type
[] InferDelegateArguments (MethodBase method
);
2077 // Implements C# 3.0 type inference
2079 class TypeInferenceV3
: ATypeInference
2082 // Tracks successful rate of type inference
2084 int score
= int.MaxValue
;
2086 public TypeInferenceV3 (ArrayList arguments
)
2091 public override int InferenceScore
{
2097 public override Type
[] InferDelegateArguments (MethodBase method
)
2099 AParametersCollection pd
= TypeManager
.GetParameterData (method
);
2100 if (arg_count
!= pd
.Count
)
2103 Type
[] d_gargs
= method
.GetGenericArguments ();
2104 TypeInferenceContext context
= new TypeInferenceContext (d_gargs
);
2106 // A lower-bound inference is made from each argument type Uj of D
2107 // to the corresponding parameter type Tj of M
2108 for (int i
= 0; i
< arg_count
; ++i
) {
2109 Type t
= pd
.Types
[i
];
2110 if (!t
.IsGenericParameter
)
2113 context
.LowerBoundInference ((Type
)arguments
[i
], t
);
2116 if (!context
.FixAllTypes ())
2119 return context
.InferredTypeArguments
;
2122 public override Type
[] InferMethodArguments (EmitContext ec
, MethodBase method
)
2124 Type
[] method_generic_args
= method
.GetGenericArguments ();
2125 TypeInferenceContext context
= new TypeInferenceContext (method_generic_args
);
2126 if (!context
.UnfixedVariableExists
)
2127 return Type
.EmptyTypes
;
2129 AParametersCollection pd
= TypeManager
.GetParameterData (method
);
2130 if (!InferInPhases (ec
, context
, pd
))
2133 return context
.InferredTypeArguments
;
2137 // Implements method type arguments inference
2139 bool InferInPhases (EmitContext ec
, TypeInferenceContext tic
, AParametersCollection methodParameters
)
2141 int params_arguments_start
;
2142 if (methodParameters
.HasParams
) {
2143 params_arguments_start
= methodParameters
.Count
- 1;
2145 params_arguments_start
= arg_count
;
2148 Type
[] ptypes
= methodParameters
.Types
;
2151 // The first inference phase
2153 Type method_parameter
= null;
2154 for (int i
= 0; i
< arg_count
; i
++) {
2155 Argument a
= (Argument
) arguments
[i
];
2157 if (i
< params_arguments_start
) {
2158 method_parameter
= methodParameters
.Types
[i
];
2159 } else if (i
== params_arguments_start
) {
2160 if (arg_count
== params_arguments_start
+ 1 && TypeManager
.HasElementType (a
.Type
))
2161 method_parameter
= methodParameters
.Types
[params_arguments_start
];
2163 method_parameter
= TypeManager
.GetElementType (methodParameters
.Types
[params_arguments_start
]);
2165 ptypes
= (Type
[]) ptypes
.Clone ();
2166 ptypes
[i
] = method_parameter
;
2170 // When a lambda expression, an anonymous method
2171 // is used an explicit argument type inference takes a place
2173 AnonymousMethodExpression am
= a
.Expr
as AnonymousMethodExpression
;
2175 if (am
.ExplicitTypeInference (tic
, method_parameter
))
2180 if (a
.Expr
.Type
== TypeManager
.null_type
)
2184 // Otherwise an output type inference is made
2186 score
-= tic
.OutputTypeInference (ec
, a
.Expr
, method_parameter
);
2190 // Part of the second phase but because it happens only once
2191 // we don't need to call it in cycle
2193 bool fixed_any
= false;
2194 if (!tic
.FixIndependentTypeArguments (ptypes
, ref fixed_any
))
2197 return DoSecondPhase (ec
, tic
, ptypes
, !fixed_any
);
2200 bool DoSecondPhase (EmitContext ec
, TypeInferenceContext tic
, Type
[] methodParameters
, bool fixDependent
)
2202 bool fixed_any
= false;
2203 if (fixDependent
&& !tic
.FixDependentTypes (ref fixed_any
))
2206 // If no further unfixed type variables exist, type inference succeeds
2207 if (!tic
.UnfixedVariableExists
)
2210 if (!fixed_any
&& fixDependent
)
2213 // For all arguments where the corresponding argument output types
2214 // contain unfixed type variables but the input types do not,
2215 // an output type inference is made
2216 for (int i
= 0; i
< arg_count
; i
++) {
2218 // Align params arguments
2219 Type t_i
= methodParameters
[i
>= methodParameters
.Length
? methodParameters
.Length
- 1: i
];
2221 if (!TypeManager
.IsDelegateType (t_i
)) {
2222 if (TypeManager
.DropGenericTypeArguments (t_i
) != TypeManager
.expression_type
)
2225 t_i
= t_i
.GetGenericArguments () [0];
2228 MethodInfo mi
= Delegate
.GetInvokeMethod (t_i
, t_i
);
2229 Type rtype
= mi
.ReturnType
;
2232 // Blablabla, because reflection does not work with dynamic types
2233 Type
[] g_args
= t_i
.GetGenericArguments ();
2234 rtype
= g_args
[rtype
.GenericParameterPosition
];
2237 if (tic
.IsReturnTypeNonDependent (mi
, rtype
))
2238 score
-= tic
.OutputTypeInference (ec
, ((Argument
) arguments
[i
]).Expr
, t_i
);
2242 return DoSecondPhase (ec
, tic
, methodParameters
, true);
2246 public class TypeInferenceContext
2248 readonly Type
[] unfixed_types
;
2249 readonly Type
[] fixed_types
;
2250 readonly ArrayList
[] bounds
;
2253 public TypeInferenceContext (Type
[] typeArguments
)
2255 if (typeArguments
.Length
== 0)
2256 throw new ArgumentException ("Empty generic arguments");
2258 fixed_types
= new Type
[typeArguments
.Length
];
2259 for (int i
= 0; i
< typeArguments
.Length
; ++i
) {
2260 if (typeArguments
[i
].IsGenericParameter
) {
2261 if (bounds
== null) {
2262 bounds
= new ArrayList
[typeArguments
.Length
];
2263 unfixed_types
= new Type
[typeArguments
.Length
];
2265 unfixed_types
[i
] = typeArguments
[i
];
2267 fixed_types
[i
] = typeArguments
[i
];
2272 public Type
[] InferredTypeArguments
{
2278 void AddToBounds (Type t
, int index
)
2281 // Some types cannot be used as type arguments
2283 if (t
== TypeManager
.void_type
|| t
.IsPointer
)
2286 ArrayList a
= bounds
[index
];
2288 a
= new ArrayList ();
2296 // SPEC: does not cover type inference using constraints
2298 //if (TypeManager.IsGenericParameter (t)) {
2299 // GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
2300 // if (constraints != null) {
2301 // //if (constraints.EffectiveBaseClass != null)
2302 // // t = constraints.EffectiveBaseClass;
2308 bool AllTypesAreFixed (Type
[] types
)
2310 foreach (Type t
in types
) {
2311 if (t
.IsGenericParameter
) {
2317 if (t
.IsGenericType
)
2318 return AllTypesAreFixed (t
.GetGenericArguments ());
2325 // 26.3.3.8 Exact Inference
2327 public int ExactInference (Type u
, Type v
)
2329 // If V is an array type
2334 if (u
.GetArrayRank () != v
.GetArrayRank ())
2337 return ExactInference (TypeManager
.GetElementType (u
), TypeManager
.GetElementType (v
));
2340 // If V is constructed type and U is constructed type
2341 if (v
.IsGenericType
&& !v
.IsGenericTypeDefinition
) {
2342 if (!u
.IsGenericType
)
2345 Type
[] ga_u
= u
.GetGenericArguments ();
2346 Type
[] ga_v
= v
.GetGenericArguments ();
2347 if (ga_u
.Length
!= ga_v
.Length
)
2351 for (int i
= 0; i
< ga_u
.Length
; ++i
)
2352 score
+= ExactInference (ga_u
[i
], ga_v
[i
]);
2354 return score
> 0 ? 1 : 0;
2357 // If V is one of the unfixed type arguments
2358 int pos
= IsUnfixed (v
);
2362 AddToBounds (u
, pos
);
2366 public bool FixAllTypes ()
2368 for (int i
= 0; i
< unfixed_types
.Length
; ++i
) {
2376 // All unfixed type variables Xi are fixed for which all of the following hold:
2377 // a, There is at least one type variable Xj that depends on Xi
2378 // b, Xi has a non-empty set of bounds
2380 public bool FixDependentTypes (ref bool fixed_any
)
2382 for (int i
= 0; i
< unfixed_types
.Length
; ++i
) {
2383 if (unfixed_types
[i
] == null)
2386 if (bounds
[i
] == null)
2399 // All unfixed type variables Xi which depend on no Xj are fixed
2401 public bool FixIndependentTypeArguments (Type
[] methodParameters
, ref bool fixed_any
)
2403 ArrayList types_to_fix
= new ArrayList (unfixed_types
);
2404 for (int i
= 0; i
< methodParameters
.Length
; ++i
) {
2405 Type t
= methodParameters
[i
];
2407 if (!TypeManager
.IsDelegateType (t
)) {
2408 if (TypeManager
.DropGenericTypeArguments (t
) != TypeManager
.expression_type
)
2411 t
= t
.GetGenericArguments () [0];
2414 if (t
.IsGenericParameter
)
2417 MethodInfo invoke
= Delegate
.GetInvokeMethod (t
, t
);
2418 Type rtype
= invoke
.ReturnType
;
2419 if (!rtype
.IsGenericParameter
&& !rtype
.IsGenericType
)
2423 // Blablabla, because reflection does not work with dynamic types
2424 if (rtype
.IsGenericParameter
) {
2425 Type
[] g_args
= t
.GetGenericArguments ();
2426 rtype
= g_args
[rtype
.GenericParameterPosition
];
2429 // Remove dependent types, they cannot be fixed yet
2430 RemoveDependentTypes (types_to_fix
, rtype
);
2433 foreach (Type t
in types_to_fix
) {
2437 int idx
= IsUnfixed (t
);
2438 if (idx
>= 0 && !FixType (idx
)) {
2443 fixed_any
= types_to_fix
.Count
> 0;
2450 public bool FixType (int i
)
2452 // It's already fixed
2453 if (unfixed_types
[i
] == null)
2454 throw new InternalErrorException ("Type argument has been already fixed");
2459 ArrayList candidates
= (ArrayList
)bounds
[i
];
2460 if (candidates
== null)
2463 if (candidates
.Count
== 1) {
2464 unfixed_types
[i
] = null;
2465 fixed_types
[i
] = (Type
)candidates
[0];
2470 // Determines a unique type from which there is
2471 // a standard implicit conversion to all the other
2474 Type best_candidate
= null;
2476 int candidates_count
= candidates
.Count
;
2477 for (int ci
= 0; ci
< candidates_count
; ++ci
) {
2478 Type candidate
= (Type
)candidates
[ci
];
2479 for (cii
= 0; cii
< candidates_count
; ++cii
) {
2483 if (!Convert
.ImplicitConversionExists (null,
2484 new TypeExpression ((Type
)candidates
[cii
], Location
.Null
), candidate
)) {
2489 if (cii
!= candidates_count
)
2492 if (best_candidate
!= null)
2495 best_candidate
= candidate
;
2498 if (best_candidate
== null)
2501 unfixed_types
[i
] = null;
2502 fixed_types
[i
] = best_candidate
;
2507 // Uses inferred types to inflate delegate type argument
2509 public Type
InflateGenericArgument (Type parameter
)
2511 if (parameter
.IsGenericParameter
) {
2513 // Inflate method generic argument (MVAR) only
2515 if (parameter
.DeclaringMethod
== null)
2518 return fixed_types
[parameter
.GenericParameterPosition
];
2521 if (parameter
.IsGenericType
) {
2522 Type
[] parameter_targs
= parameter
.GetGenericArguments ();
2523 for (int ii
= 0; ii
< parameter_targs
.Length
; ++ii
) {
2524 parameter_targs
[ii
] = InflateGenericArgument (parameter_targs
[ii
]);
2526 return parameter
.GetGenericTypeDefinition ().MakeGenericType (parameter_targs
);
2533 // Tests whether all delegate input arguments are fixed and generic output type
2534 // requires output type inference
2536 public bool IsReturnTypeNonDependent (MethodInfo invoke
, Type returnType
)
2538 if (returnType
.IsGenericParameter
) {
2539 if (IsFixed (returnType
))
2541 } else if (returnType
.IsGenericType
) {
2542 if (TypeManager
.IsDelegateType (returnType
)) {
2543 invoke
= Delegate
.GetInvokeMethod (returnType
, returnType
);
2544 return IsReturnTypeNonDependent (invoke
, invoke
.ReturnType
);
2547 Type
[] g_args
= returnType
.GetGenericArguments ();
2549 // At least one unfixed return type has to exist
2550 if (AllTypesAreFixed (g_args
))
2556 // All generic input arguments have to be fixed
2557 AParametersCollection d_parameters
= TypeManager
.GetParameterData (invoke
);
2558 return AllTypesAreFixed (d_parameters
.Types
);
2561 bool IsFixed (Type type
)
2563 return IsUnfixed (type
) == -1;
2566 int IsUnfixed (Type type
)
2568 if (!type
.IsGenericParameter
)
2571 //return unfixed_types[type.GenericParameterPosition] != null;
2572 for (int i
= 0; i
< unfixed_types
.Length
; ++i
) {
2573 if (unfixed_types
[i
] == type
)
2581 // 26.3.3.9 Lower-bound Inference
2583 public int LowerBoundInference (Type u
, Type v
)
2585 // If V is one of the unfixed type arguments
2586 int pos
= IsUnfixed (v
);
2588 AddToBounds (u
, pos
);
2592 // If U is an array type
2594 int u_dim
= u
.GetArrayRank ();
2596 Type u_e
= TypeManager
.GetElementType (u
);
2599 if (u_dim
!= v
.GetArrayRank ())
2602 v_e
= TypeManager
.GetElementType (v
);
2605 return LowerBoundInference (u_e
, v_e
);
2608 return ExactInference (u_e
, v_e
);
2614 if (v
.IsGenericType
) {
2615 Type g_v
= v
.GetGenericTypeDefinition ();
2616 if ((g_v
!= TypeManager
.generic_ilist_type
) && (g_v
!= TypeManager
.generic_icollection_type
) &&
2617 (g_v
!= TypeManager
.generic_ienumerable_type
))
2620 v_e
= TypeManager
.GetTypeArguments (v
)[0];
2623 return LowerBoundInference (u_e
, v_e
);
2626 return ExactInference (u_e
, v_e
);
2628 } else if (v
.IsGenericType
&& !v
.IsGenericTypeDefinition
) {
2630 // if V is a constructed type C<V1..Vk> and there is a unique set of types U1..Uk
2631 // such that a standard implicit conversion exists from U to C<U1..Uk> then an exact
2632 // inference is made from each Ui for the corresponding Vi
2634 ArrayList u_candidates
= new ArrayList ();
2635 if (u
.IsGenericType
)
2636 u_candidates
.Add (u
);
2638 for (Type t
= u
.BaseType
; t
!= null; t
= t
.BaseType
) {
2639 if (t
.IsGenericType
&& !t
.IsGenericTypeDefinition
)
2640 u_candidates
.Add (t
);
2643 // TODO: Implement GetGenericInterfaces only and remove
2644 // the if from foreach
2645 u_candidates
.AddRange (TypeManager
.GetInterfaces (u
));
2647 Type open_v
= v
.GetGenericTypeDefinition ();
2648 Type
[] unique_candidate_targs
= null;
2649 Type
[] ga_v
= v
.GetGenericArguments ();
2650 foreach (Type u_candidate
in u_candidates
) {
2651 if (!u_candidate
.IsGenericType
|| u_candidate
.IsGenericTypeDefinition
)
2654 if (TypeManager
.DropGenericTypeArguments (u_candidate
) != open_v
)
2658 // The unique set of types U1..Uk means that if we have an interface C<T>,
2659 // class U: C<int>, C<long> then no type inference is made when inferring
2660 // from U to C<T> because T could be int or long
2662 if (unique_candidate_targs
!= null) {
2663 Type
[] second_unique_candidate_targs
= u_candidate
.GetGenericArguments ();
2664 if (TypeManager
.IsEqual (unique_candidate_targs
, second_unique_candidate_targs
)) {
2665 unique_candidate_targs
= second_unique_candidate_targs
;
2670 // This should always cause type inference failure
2676 unique_candidate_targs
= u_candidate
.GetGenericArguments ();
2679 if (unique_candidate_targs
!= null) {
2681 for (int i
= 0; i
< unique_candidate_targs
.Length
; ++i
)
2682 if (ExactInference (unique_candidate_targs
[i
], ga_v
[i
]) == 0)
2692 // 26.3.3.6 Output Type Inference
2694 public int OutputTypeInference (EmitContext ec
, Expression e
, Type t
)
2696 // If e is a lambda or anonymous method with inferred return type
2697 AnonymousMethodExpression ame
= e
as AnonymousMethodExpression
;
2699 Type rt
= ame
.InferReturnType (ec
, this, t
);
2700 MethodInfo invoke
= Delegate
.GetInvokeMethod (t
, t
);
2703 AParametersCollection pd
= TypeManager
.GetParameterData (invoke
);
2704 return ame
.Parameters
.Count
== pd
.Count
? 1 : 0;
2707 Type rtype
= invoke
.ReturnType
;
2709 // Blablabla, because reflection does not work with dynamic types
2710 Type
[] g_args
= t
.GetGenericArguments ();
2711 rtype
= g_args
[rtype
.GenericParameterPosition
];
2713 return LowerBoundInference (rt
, rtype
) + 1;
2717 // if E is a method group and T is a delegate type or expression tree type
2718 // return type Tb with parameter types T1..Tk and return type Tb, and overload
2719 // resolution of E with the types T1..Tk yields a single method with return type U,
2720 // then a lower-bound inference is made from U for Tb.
2722 if (e
is MethodGroupExpr
) {
2723 // TODO: Or expression tree
2724 if (!TypeManager
.IsDelegateType (t
))
2727 MethodInfo invoke
= Delegate
.GetInvokeMethod (t
, t
);
2728 Type rtype
= invoke
.ReturnType
;
2730 // Blablabla, because reflection does not work with dynamic types
2731 Type
[] g_args
= t
.GetGenericArguments ();
2732 rtype
= g_args
[rtype
.GenericParameterPosition
];
2735 if (!TypeManager
.IsGenericType (rtype
))
2738 MethodGroupExpr mg
= (MethodGroupExpr
) e
;
2739 ArrayList args
= DelegateCreation
.CreateDelegateMethodArguments (invoke
, e
.Location
);
2740 mg
= mg
.OverloadResolve (ec
, ref args
, true, e
.Location
);
2744 // TODO: What should happen when return type is of generic type ?
2745 throw new NotImplementedException ();
2746 // return LowerBoundInference (null, rtype) + 1;
2750 // if e is an expression with type U, then
2751 // a lower-bound inference is made from U for T
2753 return LowerBoundInference (e
.Type
, t
) * 2;
2756 void RemoveDependentTypes (ArrayList types
, Type returnType
)
2758 int idx
= IsUnfixed (returnType
);
2764 if (returnType
.IsGenericType
) {
2765 foreach (Type t
in returnType
.GetGenericArguments ()) {
2766 RemoveDependentTypes (types
, t
);
2771 public bool UnfixedVariableExists
{
2773 if (unfixed_types
== null)
2776 foreach (Type ut
in unfixed_types
)