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 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 ArrayList 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
, ArrayList constraints
,
235 this.constraints
= constraints
;
239 public override string TypeParameter
{
245 public Constraints
Clone ()
247 return new Constraints (name
, constraints
, loc
);
250 GenericParameterAttributes attrs
;
251 TypeExpr class_constraint
;
252 ArrayList iface_constraints
;
253 ArrayList type_param_constraints
;
255 Type class_constraint_type
;
256 Type
[] iface_constraint_types
;
257 Type effective_base_type
;
262 /// Resolve the constraints - but only resolve things into Expression's, not
263 /// into actual types.
265 public bool Resolve (MemberCore ec
, TypeParameter tp
, Report Report
)
273 iface_constraints
= new ArrayList (2); // TODO: Too expensive allocation
274 type_param_constraints
= new ArrayList ();
276 foreach (object obj
in constraints
) {
277 if (HasConstructorConstraint
) {
278 Report
.Error (401, loc
,
279 "The new() constraint must be the last constraint specified");
283 if (obj
is SpecialConstraint
) {
284 SpecialConstraint sc
= (SpecialConstraint
) obj
;
286 if (sc
== SpecialConstraint
.Constructor
) {
287 if (!HasValueTypeConstraint
) {
288 attrs
|= GenericParameterAttributes
.DefaultConstructorConstraint
;
292 Report
.Error (451, loc
, "The `new()' constraint " +
293 "cannot be used with the `struct' constraint");
297 if ((num_constraints
> 0) || HasReferenceTypeConstraint
|| HasValueTypeConstraint
) {
298 Report
.Error (449, loc
, "The `class' or `struct' " +
299 "constraint must be the first constraint specified");
303 if (sc
== SpecialConstraint
.ReferenceType
)
304 attrs
|= GenericParameterAttributes
.ReferenceTypeConstraint
;
306 attrs
|= GenericParameterAttributes
.NotNullableValueTypeConstraint
;
310 int errors
= Report
.Errors
;
311 FullNamedExpression fn
= ((Expression
) obj
).ResolveAsTypeStep (ec
, false);
314 if (errors
!= Report
.Errors
)
317 NamespaceEntry
.Error_NamespaceNotFound (loc
, ((Expression
)obj
).GetSignatureForError (), Report
);
322 GenericTypeExpr cexpr
= fn
as GenericTypeExpr
;
324 expr
= cexpr
.ResolveAsBaseTerminal (ec
, false);
326 expr
= ((Expression
) obj
).ResolveAsTypeTerminal (ec
, false);
328 if ((expr
== null) || (expr
.Type
== null))
331 if (!ec
.IsAccessibleAs (fn
.Type
)) {
332 Report
.SymbolRelatedToPreviousError (fn
.Type
);
333 Report
.Error (703, loc
,
334 "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
335 fn
.GetSignatureForError (), ec
.GetSignatureForError ());
339 if (TypeManager
.IsGenericParameter (expr
.Type
))
340 type_param_constraints
.Add (expr
);
341 else if (expr
.IsInterface
)
342 iface_constraints
.Add (expr
);
343 else if (class_constraint
!= null || iface_constraints
.Count
!= 0) {
344 Report
.Error (406, loc
,
345 "The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
346 expr
.GetSignatureForError ());
348 } else if (HasReferenceTypeConstraint
|| HasValueTypeConstraint
) {
349 Report
.Error (450, loc
, "`{0}': cannot specify both " +
350 "a constraint class and the `class' " +
351 "or `struct' constraint", expr
.GetSignatureForError ());
354 class_constraint
= expr
;
358 // Checks whether each generic method parameter constraint type
359 // is valid with respect to T
361 if (tp
!= null && tp
.Type
.DeclaringMethod
!= null) {
362 TypeManager
.CheckTypeVariance (expr
.Type
, Variance
.Contravariant
, ec
as MemberCore
);
368 ArrayList list
= new ArrayList ();
369 foreach (TypeExpr iface_constraint
in iface_constraints
) {
370 foreach (Type type
in list
) {
371 if (!type
.Equals (iface_constraint
.Type
))
374 Report
.Error (405, loc
,
375 "Duplicate constraint `{0}' for type " +
376 "parameter `{1}'.", iface_constraint
.GetSignatureForError (),
381 list
.Add (iface_constraint
.Type
);
384 foreach (TypeExpr expr
in type_param_constraints
) {
385 foreach (Type type
in list
) {
386 if (!type
.Equals (expr
.Type
))
389 Report
.Error (405, loc
,
390 "Duplicate constraint `{0}' for type " +
391 "parameter `{1}'.", expr
.GetSignatureForError (), name
);
395 list
.Add (expr
.Type
);
398 iface_constraint_types
= new Type
[list
.Count
];
399 list
.CopyTo (iface_constraint_types
, 0);
401 if (class_constraint
!= null) {
402 class_constraint_type
= class_constraint
.Type
;
403 if (class_constraint_type
== null)
406 if (class_constraint_type
.IsSealed
) {
407 if (class_constraint_type
.IsAbstract
)
409 Report
.Error (717, loc
, "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
410 TypeManager
.CSharpName (class_constraint_type
));
414 Report
.Error (701, loc
, "`{0}' is not a valid constraint. A constraint must be an interface, " +
415 "a non-sealed class or a type parameter", TypeManager
.CSharpName(class_constraint_type
));
420 if ((class_constraint_type
== TypeManager
.array_type
) ||
421 (class_constraint_type
== TypeManager
.delegate_type
) ||
422 (class_constraint_type
== TypeManager
.enum_type
) ||
423 (class_constraint_type
== TypeManager
.value_type
) ||
424 (class_constraint_type
== TypeManager
.object_type
) ||
425 class_constraint_type
== TypeManager
.multicast_delegate_type
) {
426 Report
.Error (702, loc
,
427 "A constraint cannot be special class `{0}'",
428 TypeManager
.CSharpName (class_constraint_type
));
432 if (TypeManager
.IsDynamicType (class_constraint_type
)) {
433 Report
.Error (1967, loc
, "A constraint cannot be the dynamic type");
438 if (class_constraint_type
!= null)
439 effective_base_type
= class_constraint_type
;
440 else if (HasValueTypeConstraint
)
441 effective_base_type
= TypeManager
.value_type
;
443 effective_base_type
= TypeManager
.object_type
;
445 if ((attrs
& GenericParameterAttributes
.NotNullableValueTypeConstraint
) != 0)
446 attrs
|= GenericParameterAttributes
.DefaultConstructorConstraint
;
452 bool CheckTypeParameterConstraints (Type tparam
, ref TypeExpr prevConstraint
, ArrayList seen
, Report Report
)
456 Constraints constraints
= TypeManager
.LookupTypeParameter (tparam
).Constraints
;
457 if (constraints
== null)
460 if (constraints
.HasValueTypeConstraint
) {
461 Report
.Error (456, loc
,
462 "Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
468 // Checks whether there are no conflicts between type parameter constraints
472 // where U : A, B // A and B are not convertible
474 if (constraints
.HasClassConstraint
) {
475 if (prevConstraint
!= null) {
476 Type t2
= constraints
.ClassConstraint
;
477 TypeExpr e2
= constraints
.class_constraint
;
479 if (!Convert
.ImplicitReferenceConversionExists (prevConstraint
, t2
) &&
480 !Convert
.ImplicitReferenceConversionExists (e2
, prevConstraint
.Type
)) {
481 Report
.Error (455, loc
,
482 "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
483 name
, TypeManager
.CSharpName (prevConstraint
.Type
), TypeManager
.CSharpName (t2
));
488 prevConstraint
= constraints
.class_constraint
;
491 if (constraints
.type_param_constraints
== null)
494 foreach (TypeExpr expr
in constraints
.type_param_constraints
) {
495 if (seen
.Contains (expr
.Type
)) {
496 Report
.Error (454, loc
, "Circular constraint " +
497 "dependency involving `{0}' and `{1}'",
498 tparam
.Name
, expr
.GetSignatureForError ());
502 if (!CheckTypeParameterConstraints (expr
.Type
, ref prevConstraint
, seen
, Report
))
510 /// Resolve the constraints into actual types.
512 public bool ResolveTypes (IMemberContext ec
, Report r
)
517 resolved_types
= true;
519 foreach (object obj
in constraints
) {
520 GenericTypeExpr cexpr
= obj
as GenericTypeExpr
;
524 if (!cexpr
.CheckConstraints (ec
))
528 if (type_param_constraints
.Count
!= 0) {
529 ArrayList seen
= new ArrayList ();
530 TypeExpr prev_constraint
= class_constraint
;
531 foreach (TypeExpr expr
in type_param_constraints
) {
532 if (!CheckTypeParameterConstraints (expr
.Type
, ref prev_constraint
, seen
, r
))
538 for (int i
= 0; i
< iface_constraints
.Count
; ++i
) {
539 TypeExpr iface_constraint
= (TypeExpr
) iface_constraints
[i
];
540 iface_constraint
= iface_constraint
.ResolveAsTypeTerminal (ec
, false);
541 if (iface_constraint
== null)
543 iface_constraints
[i
] = iface_constraint
;
546 if (class_constraint
!= null) {
547 class_constraint
= class_constraint
.ResolveAsTypeTerminal (ec
, false);
548 if (class_constraint
== null)
555 public override GenericParameterAttributes Attributes
{
556 get { return attrs; }
559 public override bool HasClassConstraint
{
560 get { return class_constraint != null; }
563 public override Type ClassConstraint
{
564 get { return class_constraint_type; }
567 public override Type
[] InterfaceConstraints
{
568 get { return iface_constraint_types; }
571 public override Type EffectiveBaseClass
{
572 get { return effective_base_type; }
575 public bool IsSubclassOf (Type t
)
577 if ((class_constraint_type
!= null) &&
578 class_constraint_type
.IsSubclassOf (t
))
581 if (iface_constraint_types
== null)
584 foreach (Type iface
in iface_constraint_types
) {
585 if (TypeManager
.IsSubclassOf (iface
, t
))
592 public Location Location
{
599 /// This is used when we're implementing a generic interface method.
600 /// Each method type parameter in implementing method must have the same
601 /// constraints than the corresponding type parameter in the interface
602 /// method. To do that, we're called on each of the implementing method's
605 public bool AreEqual (GenericConstraints gc
)
607 if (gc
.Attributes
!= attrs
)
610 if (HasClassConstraint
!= gc
.HasClassConstraint
)
612 if (HasClassConstraint
&& !TypeManager
.IsEqual (gc
.ClassConstraint
, ClassConstraint
))
615 int gc_icount
= gc
.InterfaceConstraints
!= null ?
616 gc
.InterfaceConstraints
.Length
: 0;
617 int icount
= InterfaceConstraints
!= null ?
618 InterfaceConstraints
.Length
: 0;
620 if (gc_icount
!= icount
)
623 for (int i
= 0; i
< gc
.InterfaceConstraints
.Length
; ++i
) {
624 Type iface
= gc
.InterfaceConstraints
[i
];
625 if (iface
.IsGenericType
)
626 iface
= iface
.GetGenericTypeDefinition ();
629 for (int ii
= 0; ii
< InterfaceConstraints
.Length
; ii
++) {
630 Type check
= InterfaceConstraints
[ii
];
631 if (check
.IsGenericType
)
632 check
= check
.GetGenericTypeDefinition ();
634 if (TypeManager
.IsEqual (iface
, check
)) {
647 public void VerifyClsCompliance (Report r
)
649 if (class_constraint_type
!= null && !AttributeTester
.IsClsCompliant (class_constraint_type
))
650 Warning_ConstrainIsNotClsCompliant (class_constraint_type
, class_constraint
.Location
, r
);
652 if (iface_constraint_types
!= null) {
653 for (int i
= 0; i
< iface_constraint_types
.Length
; ++i
) {
654 if (!AttributeTester
.IsClsCompliant (iface_constraint_types
[i
]))
655 Warning_ConstrainIsNotClsCompliant (iface_constraint_types
[i
],
656 ((TypeExpr
)iface_constraints
[i
]).Location
, r
);
661 void Warning_ConstrainIsNotClsCompliant (Type t
, Location loc
, Report Report
)
663 Report
.SymbolRelatedToPreviousError (t
);
664 Report
.Warning (3024, 1, loc
, "Constraint type `{0}' is not CLS-compliant",
665 TypeManager
.CSharpName (t
));
670 /// A type parameter from a generic type definition.
672 public class TypeParameter
: MemberCore
, IMemberContainer
674 static readonly string[] attribute_target
= new string [] { "type parameter" }
;
677 GenericConstraints gc
;
678 Constraints constraints
;
679 GenericTypeParameterBuilder type
;
680 MemberCache member_cache
;
683 public TypeParameter (DeclSpace parent
, DeclSpace decl
, string name
,
684 Constraints constraints
, Attributes attrs
, Variance variance
, Location loc
)
685 : base (parent
, new MemberName (name
, loc
), attrs
)
688 this.constraints
= constraints
;
689 this.variance
= variance
;
692 public GenericConstraints GenericConstraints
{
693 get { return gc != null ? gc : constraints; }
696 public Constraints Constraints
{
697 get { return constraints; }
700 public DeclSpace DeclSpace
{
704 public Variance Variance
{
705 get { return variance; }
713 /// This is the first method which is called during the resolving
714 /// process; we're called immediately after creating the type parameters
715 /// with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
718 /// We're either called from TypeContainer.DefineType() or from
719 /// GenericMethod.Define() (called from Method.Define()).
721 public void Define (GenericTypeParameterBuilder type
)
723 if (this.type
!= null)
724 throw new InvalidOperationException ();
727 TypeManager
.AddTypeParameter (type
, this);
730 public void ErrorInvalidVariance (IMemberContext mc
, Variance expected
)
732 // TODO: Report.SymbolRelatedToPreviousError (mc);
733 string input_variance
= Variance
== Variance
.Contravariant
? "contravariant" : "covariant";
734 string gtype_variance
;
736 case Variance
.Contravariant
: gtype_variance
= "contravariantly"; break;
737 case Variance
.Covariant
: gtype_variance
= "covariantly"; break;
738 default: gtype_variance
= "invariantly"; break;
741 Delegate d
= mc
as Delegate
;
742 string parameters
= d
!= null ? d
.Parameters
.GetSignatureForError () : "";
744 Report
.Error (1961, Location
,
745 "The {2} type parameter `{0}' must be {3} valid on `{1}{4}'",
746 GetSignatureForError (), mc
.GetSignatureForError (), input_variance
, gtype_variance
, parameters
);
750 /// This is the second method which is called during the resolving
751 /// process - in case of class type parameters, we're called from
752 /// TypeContainer.ResolveType() - after it resolved the class'es
753 /// base class and interfaces. For method type parameters, we're
754 /// called immediately after Define().
756 /// We're just resolving the constraints into expressions here, we
757 /// don't resolve them into actual types.
759 /// Note that in the special case of partial generic classes, we may be
760 /// called _before_ Define() and we may also be called multiple types.
762 public bool Resolve (DeclSpace ds
)
764 if (constraints
!= null) {
765 if (!constraints
.Resolve (ds
, this, Report
)) {
775 /// This is the third method which is called during the resolving
776 /// process. We're called immediately after calling DefineConstraints()
777 /// on all of the current class'es type parameters.
779 /// Our job is to resolve the constraints to actual types.
781 /// Note that we may have circular dependencies on type parameters - this
782 /// is why Resolve() and ResolveType() are separate.
784 public bool ResolveType (IMemberContext ec
)
786 if (constraints
!= null) {
787 if (!constraints
.ResolveTypes (ec
, Report
)) {
797 /// This is the fourth and last method which is called during the resolving
798 /// process. We're called after everything is fully resolved and actually
799 /// register the constraints with SRE and the TypeManager.
801 public bool DefineType (IMemberContext ec
)
803 return DefineType (ec
, null, null, false);
807 /// This is the fith and last method which is called during the resolving
808 /// process. We're called after everything is fully resolved and actually
809 /// register the constraints with SRE and the TypeManager.
811 /// The `builder', `implementing' and `is_override' arguments are only
812 /// applicable to method type parameters.
814 public bool DefineType (IMemberContext ec
, MethodBuilder builder
,
815 MethodInfo implementing
, bool is_override
)
817 if (!ResolveType (ec
))
820 if (implementing
!= null) {
821 if (is_override
&& (constraints
!= null)) {
822 Report
.Error (460, Location
,
823 "`{0}': Cannot specify constraints for overrides or explicit interface implementation methods",
824 TypeManager
.CSharpSignature (builder
));
828 MethodBase mb
= TypeManager
.DropGenericMethodArguments (implementing
);
830 int pos
= type
.GenericParameterPosition
;
831 Type mparam
= mb
.GetGenericArguments () [pos
];
832 GenericConstraints temp_gc
= ReflectionConstraints
.GetConstraints (mparam
);
835 gc
= new InflatedConstraints (temp_gc
, implementing
.DeclaringType
);
836 else if (constraints
!= null)
837 gc
= new InflatedConstraints (constraints
, implementing
.DeclaringType
);
840 if (constraints
!= null) {
843 else if (!constraints
.AreEqual (gc
))
846 if (!is_override
&& (temp_gc
!= null))
851 Report
.SymbolRelatedToPreviousError (implementing
);
854 425, Location
, "The constraints for type " +
855 "parameter `{0}' of method `{1}' must match " +
856 "the constraints for type parameter `{2}' " +
857 "of interface method `{3}'. Consider using " +
858 "an explicit interface implementation instead",
859 Name
, TypeManager
.CSharpSignature (builder
),
860 TypeManager
.CSharpName (mparam
), TypeManager
.CSharpSignature (mb
));
863 } else if (DeclSpace
is CompilerGeneratedClass
) {
864 TypeParameter
[] tparams
= DeclSpace
.TypeParameters
;
865 Type
[] types
= new Type
[tparams
.Length
];
866 for (int i
= 0; i
< tparams
.Length
; i
++)
867 types
[i
] = tparams
[i
].Type
;
869 if (constraints
!= null)
870 gc
= new InflatedConstraints (constraints
, types
);
872 gc
= (GenericConstraints
) constraints
;
875 SetConstraints (type
);
879 public static TypeParameter
FindTypeParameter (TypeParameter
[] tparams
, string name
)
881 foreach (var tp
in tparams
) {
889 public void SetConstraints (GenericTypeParameterBuilder type
)
891 GenericParameterAttributes attr
= GenericParameterAttributes
.None
;
892 if (variance
== Variance
.Contravariant
)
893 attr
|= GenericParameterAttributes
.Contravariant
;
894 else if (variance
== Variance
.Covariant
)
895 attr
|= GenericParameterAttributes
.Covariant
;
898 if (gc
.HasClassConstraint
|| gc
.HasValueTypeConstraint
)
899 type
.SetBaseTypeConstraint (gc
.EffectiveBaseClass
);
901 attr
|= gc
.Attributes
;
902 type
.SetInterfaceConstraints (gc
.InterfaceConstraints
);
903 TypeManager
.RegisterBuilder (type
, gc
.InterfaceConstraints
);
906 type
.SetGenericParameterAttributes (attr
);
910 /// This is called for each part of a partial generic type definition.
912 /// If `new_constraints' is not null and we don't already have constraints,
913 /// they become our constraints. If we already have constraints, we must
914 /// check that they're the same.
917 public bool UpdateConstraints (MemberCore ec
, Constraints new_constraints
)
920 throw new InvalidOperationException ();
922 if (new_constraints
== null)
925 if (!new_constraints
.Resolve (ec
, this, Report
))
927 if (!new_constraints
.ResolveTypes (ec
, Report
))
930 if (constraints
!= null)
931 return constraints
.AreEqual (new_constraints
);
933 constraints
= new_constraints
;
937 public override void Emit ()
939 if (OptAttributes
!= null)
940 OptAttributes
.Emit ();
945 public override string DocCommentHeader
{
947 throw new InvalidOperationException (
948 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
956 public override bool Define ()
961 public override void ApplyAttributeBuilder (Attribute a
, CustomAttributeBuilder cb
, PredefinedAttributes pa
)
963 type
.SetCustomAttribute (cb
);
966 public override AttributeTargets AttributeTargets
{
968 return AttributeTargets
.GenericParameter
;
972 public override string[] ValidAttributeTargets
{
974 return attribute_target
;
982 string IMemberContainer
.Name
{
986 MemberCache IMemberContainer
.BaseCache
{
991 if (gc
.EffectiveBaseClass
.BaseType
== null)
994 return TypeManager
.LookupMemberCache (gc
.EffectiveBaseClass
.BaseType
);
998 bool IMemberContainer
.IsInterface
{
999 get { return false; }
1002 MemberList IMemberContainer
.GetMembers (MemberTypes mt
, BindingFlags bf
)
1004 throw new NotSupportedException ();
1007 public MemberCache MemberCache
{
1009 if (member_cache
!= null)
1010 return member_cache
;
1015 Type
[] ifaces
= TypeManager
.ExpandInterfaces (gc
.InterfaceConstraints
);
1016 member_cache
= new MemberCache (this, gc
.EffectiveBaseClass
, ifaces
);
1018 return member_cache
;
1022 public MemberList
FindMembers (MemberTypes mt
, BindingFlags bf
,
1023 MemberFilter filter
, object criteria
)
1026 return MemberList
.Empty
;
1028 ArrayList members
= new ArrayList ();
1030 if (gc
.HasClassConstraint
) {
1031 MemberList list
= TypeManager
.FindMembers (
1032 gc
.ClassConstraint
, mt
, bf
, filter
, criteria
);
1034 members
.AddRange (list
);
1037 Type
[] ifaces
= TypeManager
.ExpandInterfaces (gc
.InterfaceConstraints
);
1038 foreach (Type t
in ifaces
) {
1039 MemberList list
= TypeManager
.FindMembers (
1040 t
, mt
, bf
, filter
, criteria
);
1042 members
.AddRange (list
);
1045 return new MemberList (members
);
1048 public bool IsSubclassOf (Type t
)
1050 if (type
.Equals (t
))
1053 if (constraints
!= null)
1054 return constraints
.IsSubclassOf (t
);
1059 public void InflateConstraints (Type declaring
)
1061 if (constraints
!= null)
1062 gc
= new InflatedConstraints (constraints
, declaring
);
1065 public override bool IsClsComplianceRequired ()
1070 protected class InflatedConstraints
: GenericConstraints
1072 GenericConstraints gc
;
1074 Type class_constraint
;
1075 Type
[] iface_constraints
;
1078 public InflatedConstraints (GenericConstraints gc
, Type declaring
)
1079 : this (gc
, TypeManager
.GetTypeArguments (declaring
))
1082 public InflatedConstraints (GenericConstraints gc
, Type
[] dargs
)
1087 ArrayList list
= new ArrayList ();
1088 if (gc
.HasClassConstraint
)
1089 list
.Add (inflate (gc
.ClassConstraint
));
1090 foreach (Type iface
in gc
.InterfaceConstraints
)
1091 list
.Add (inflate (iface
));
1093 bool has_class_constr
= false;
1094 if (list
.Count
> 0) {
1095 Type first
= (Type
) list
[0];
1096 has_class_constr
= !first
.IsGenericParameter
&& !first
.IsInterface
;
1099 if ((list
.Count
> 0) && has_class_constr
) {
1100 class_constraint
= (Type
) list
[0];
1101 iface_constraints
= new Type
[list
.Count
- 1];
1102 list
.CopyTo (1, iface_constraints
, 0, list
.Count
- 1);
1104 iface_constraints
= new Type
[list
.Count
];
1105 list
.CopyTo (iface_constraints
, 0);
1108 if (HasValueTypeConstraint
)
1109 base_type
= TypeManager
.value_type
;
1110 else if (class_constraint
!= null)
1111 base_type
= class_constraint
;
1113 base_type
= TypeManager
.object_type
;
1116 Type
inflate (Type t
)
1120 if (t
.IsGenericParameter
)
1121 return t
.GenericParameterPosition
< dargs
.Length
? dargs
[t
.GenericParameterPosition
] : t
;
1122 if (t
.IsGenericType
) {
1123 Type
[] args
= t
.GetGenericArguments ();
1124 Type
[] inflated
= new Type
[args
.Length
];
1126 for (int i
= 0; i
< args
.Length
; i
++)
1127 inflated
[i
] = inflate (args
[i
]);
1129 t
= t
.GetGenericTypeDefinition ();
1130 t
= t
.MakeGenericType (inflated
);
1136 public override string TypeParameter
{
1137 get { return gc.TypeParameter; }
1140 public override GenericParameterAttributes Attributes
{
1141 get { return gc.Attributes; }
1144 public override Type ClassConstraint
{
1145 get { return class_constraint; }
1148 public override Type EffectiveBaseClass
{
1149 get { return base_type; }
1152 public override Type
[] InterfaceConstraints
{
1153 get { return iface_constraints; }
1159 /// A TypeExpr which already resolved to a type parameter.
1161 public class TypeParameterExpr
: TypeExpr
{
1163 public TypeParameterExpr (TypeParameter type_parameter
, Location loc
)
1165 this.type
= type_parameter
.Type
;
1166 this.eclass
= ExprClass
.TypeParameter
;
1170 protected override TypeExpr
DoResolveAsTypeStep (IMemberContext ec
)
1172 throw new NotSupportedException ();
1175 public override FullNamedExpression
ResolveAsTypeStep (IMemberContext ec
, bool silent
)
1180 public override bool IsInterface
{
1181 get { return false; }
1184 public override bool CheckAccessLevel (IMemberContext ds
)
1191 // Tracks the type arguments when instantiating a generic type. It's used
1192 // by both type arguments and type parameters
1194 public class TypeArguments
{
1198 public TypeArguments ()
1200 args
= new ArrayList ();
1203 public TypeArguments (params FullNamedExpression
[] types
)
1205 this.args
= new ArrayList (types
);
1208 public void Add (FullNamedExpression type
)
1213 public void Add (TypeArguments new_args
)
1215 args
.AddRange (new_args
.args
);
1218 // TODO: Should be deleted
1219 public TypeParameterName
[] GetDeclarations ()
1221 return (TypeParameterName
[]) args
.ToArray (typeof (TypeParameterName
));
1225 /// We may only be used after Resolve() is called and return the fully
1228 public Type
[] Arguments
{
1240 public string GetSignatureForError()
1242 StringBuilder sb
= new StringBuilder();
1243 for (int i
= 0; i
< Count
; ++i
)
1245 Expression expr
= (Expression
)args
[i
];
1246 sb
.Append(expr
.GetSignatureForError());
1250 return sb
.ToString();
1254 /// Resolve the type arguments.
1256 public bool Resolve (IMemberContext ec
)
1259 return atypes
.Length
!= 0;
1261 int count
= args
.Count
;
1264 atypes
= new Type
[count
];
1266 for (int i
= 0; i
< count
; i
++){
1267 TypeExpr te
= ((FullNamedExpression
) args
[i
]).ResolveAsTypeTerminal (ec
, false);
1273 atypes
[i
] = te
.Type
;
1275 if (te
.Type
.IsSealed
&& te
.Type
.IsAbstract
) {
1276 ec
.Compiler
.Report
.Error (718, te
.Location
, "`{0}': static classes cannot be used as generic arguments",
1277 te
.GetSignatureForError ());
1281 if (te
.Type
.IsPointer
|| TypeManager
.IsSpecialType (te
.Type
)) {
1282 ec
.Compiler
.Report
.Error (306, te
.Location
,
1283 "The type `{0}' may not be used as a type argument",
1284 te
.GetSignatureForError ());
1290 atypes
= Type
.EmptyTypes
;
1295 public TypeArguments
Clone ()
1297 TypeArguments copy
= new TypeArguments ();
1298 foreach (Expression ta
in args
)
1305 public class TypeParameterName
: SimpleName
1307 Attributes attributes
;
1310 public TypeParameterName (string name
, Attributes attrs
, Location loc
)
1311 : this (name
, attrs
, Variance
.None
, loc
)
1315 public TypeParameterName (string name
, Attributes attrs
, Variance variance
, Location loc
)
1319 this.variance
= variance
;
1322 public Attributes OptAttributes
{
1328 public Variance Variance
{
1336 /// A reference expression to generic type
1338 class GenericTypeExpr
: TypeExpr
1341 Type
[] gen_params
; // TODO: Waiting for constrains check cleanup
1345 // Should be carefully used only with defined generic containers. Type parameters
1346 // can be used as type arguments in this case.
1348 // TODO: This could be GenericTypeExpr specialization
1350 public GenericTypeExpr (DeclSpace gType
, Location l
)
1352 open_type
= gType
.TypeBuilder
.GetGenericTypeDefinition ();
1354 args
= new TypeArguments ();
1355 foreach (TypeParameter type_param
in gType
.TypeParameters
)
1356 args
.Add (new TypeParameterExpr (type_param
, l
));
1362 /// Instantiate the generic type `t' with the type arguments `args'.
1363 /// Use this constructor if you already know the fully resolved
1366 public GenericTypeExpr (Type t
, TypeArguments args
, Location l
)
1368 open_type
= t
.GetGenericTypeDefinition ();
1374 public TypeArguments TypeArguments
{
1375 get { return args; }
1378 public override string GetSignatureForError ()
1380 return TypeManager
.CSharpName (type
);
1383 protected override TypeExpr
DoResolveAsTypeStep (IMemberContext ec
)
1385 if (eclass
!= ExprClass
.Invalid
)
1388 eclass
= ExprClass
.Type
;
1390 if (!args
.Resolve (ec
))
1393 gen_params
= open_type
.GetGenericArguments ();
1394 Type
[] atypes
= args
.Arguments
;
1396 if (atypes
.Length
!= gen_params
.Length
) {
1397 Namespace
.Error_InvalidNumberOfTypeArguments (open_type
, loc
);
1402 // Now bind the parameters
1404 type
= open_type
.MakeGenericType (atypes
);
1409 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1410 /// after fully resolving the constructed type.
1412 public bool CheckConstraints (IMemberContext ec
)
1414 return ConstraintChecker
.CheckConstraints (ec
, open_type
, gen_params
, args
.Arguments
, loc
);
1417 public override bool CheckAccessLevel (IMemberContext mc
)
1419 return mc
.CurrentTypeDefinition
.CheckAccessLevel (open_type
);
1422 public override bool IsClass
{
1423 get { return open_type.IsClass; }
1426 public override bool IsValueType
{
1427 get { return TypeManager.IsStruct (open_type); }
1430 public override bool IsInterface
{
1431 get { return open_type.IsInterface; }
1434 public override bool IsSealed
{
1435 get { return open_type.IsSealed; }
1438 public override bool Equals (object obj
)
1440 GenericTypeExpr cobj
= obj
as GenericTypeExpr
;
1444 if ((type
== null) || (cobj
.type
== null))
1447 return type
== cobj
.type
;
1450 public override int GetHashCode ()
1452 return base.GetHashCode ();
1456 public abstract class ConstraintChecker
1458 protected readonly Type
[] gen_params
;
1459 protected readonly Type
[] atypes
;
1460 protected readonly Location loc
;
1461 protected Report Report
;
1463 protected ConstraintChecker (Type
[] gen_params
, Type
[] atypes
, Location loc
, Report r
)
1465 this.gen_params
= gen_params
;
1466 this.atypes
= atypes
;
1472 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1473 /// after fully resolving the constructed type.
1475 public bool CheckConstraints (IMemberContext ec
)
1477 for (int i
= 0; i
< gen_params
.Length
; i
++) {
1478 if (!CheckConstraints (ec
, i
))
1485 protected bool CheckConstraints (IMemberContext ec
, int index
)
1487 Type atype
= atypes
[index
];
1488 Type ptype
= gen_params
[index
];
1493 Expression aexpr
= new EmptyExpression (atype
);
1495 GenericConstraints gc
= TypeManager
.GetTypeParameterConstraints (ptype
);
1499 bool is_class
, is_struct
;
1500 if (atype
.IsGenericParameter
) {
1501 GenericConstraints agc
= TypeManager
.GetTypeParameterConstraints (atype
);
1503 if (agc
is Constraints
) {
1504 // FIXME: No constraints can be resolved here, we are in
1505 // completely wrong/different context. This path is hit
1506 // when resolving base type of unresolved generic type
1507 // with constraints. We are waiting with CheckConsttraints
1508 // after type-definition but not in this case
1509 if (!((Constraints
) agc
).Resolve (null, null, Report
))
1512 is_class
= agc
.IsReferenceType
;
1513 is_struct
= agc
.IsValueType
;
1515 is_class
= is_struct
= false;
1518 is_class
= TypeManager
.IsReferenceType (atype
);
1519 is_struct
= TypeManager
.IsValueType (atype
) && !TypeManager
.IsNullableType (atype
);
1523 // First, check the `class' and `struct' constraints.
1525 if (gc
.HasReferenceTypeConstraint
&& !is_class
) {
1526 Report
.Error (452, loc
, "The type `{0}' must be " +
1527 "a reference type in order to use it " +
1528 "as type parameter `{1}' in the " +
1529 "generic type or method `{2}'.",
1530 TypeManager
.CSharpName (atype
),
1531 TypeManager
.CSharpName (ptype
),
1532 GetSignatureForError ());
1534 } else if (gc
.HasValueTypeConstraint
&& !is_struct
) {
1535 Report
.Error (453, loc
, "The type `{0}' must be a " +
1536 "non-nullable value type in order to use it " +
1537 "as type parameter `{1}' in the " +
1538 "generic type or method `{2}'.",
1539 TypeManager
.CSharpName (atype
),
1540 TypeManager
.CSharpName (ptype
),
1541 GetSignatureForError ());
1546 // The class constraint comes next.
1548 if (gc
.HasClassConstraint
) {
1549 if (!CheckConstraint (ec
, ptype
, aexpr
, gc
.ClassConstraint
))
1554 // Now, check the interface constraints.
1556 if (gc
.InterfaceConstraints
!= null) {
1557 foreach (Type it
in gc
.InterfaceConstraints
) {
1558 if (!CheckConstraint (ec
, ptype
, aexpr
, it
))
1564 // Finally, check the constructor constraint.
1567 if (!gc
.HasConstructorConstraint
)
1570 if (TypeManager
.IsValueType (atype
))
1573 if (HasDefaultConstructor (atype
))
1576 Report_SymbolRelatedToPreviousError ();
1577 Report
.SymbolRelatedToPreviousError (atype
);
1578 Report
.Error (310, loc
, "The type `{0}' must have a public " +
1579 "parameterless constructor in order to use it " +
1580 "as parameter `{1}' in the generic type or " +
1582 TypeManager
.CSharpName (atype
),
1583 TypeManager
.CSharpName (ptype
),
1584 GetSignatureForError ());
1588 protected bool CheckConstraint (IMemberContext ec
, Type ptype
, Expression expr
,
1592 // All this is needed because we don't have
1593 // real inflated type hierarchy
1595 if (TypeManager
.HasGenericArguments (ctype
)) {
1596 Type
[] types
= TypeManager
.GetTypeArguments (ctype
);
1598 TypeArguments new_args
= new TypeArguments ();
1600 for (int i
= 0; i
< types
.Length
; i
++) {
1601 Type t
= TypeManager
.TypeToCoreType (types
[i
]);
1603 if (t
.IsGenericParameter
) {
1604 int pos
= t
.GenericParameterPosition
;
1605 if (t
.DeclaringMethod
== null && this is MethodConstraintChecker
) {
1606 Type parent
= ((MethodConstraintChecker
) this).declaring_type
;
1607 t
= parent
.GetGenericArguments ()[pos
];
1612 new_args
.Add (new TypeExpression (t
, loc
));
1615 TypeExpr ct
= new GenericTypeExpr (ctype
, new_args
, loc
);
1616 if (ct
.ResolveAsTypeStep (ec
, false) == null)
1619 } else if (ctype
.IsGenericParameter
) {
1620 int pos
= ctype
.GenericParameterPosition
;
1621 if (ctype
.DeclaringMethod
== null) {
1625 ctype
= atypes
[pos
];
1629 if (Convert
.ImplicitStandardConversionExists (expr
, ctype
))
1632 Report_SymbolRelatedToPreviousError ();
1633 Report
.SymbolRelatedToPreviousError (expr
.Type
);
1635 if (TypeManager
.IsNullableType (expr
.Type
) && ctype
.IsInterface
) {
1636 Report
.Error (313, loc
,
1637 "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. " +
1638 "The nullable type `{0}' never satisfies interface constraint of type `{3}'",
1639 TypeManager
.CSharpName (expr
.Type
), TypeManager
.CSharpName (ptype
),
1640 GetSignatureForError (), TypeManager
.CSharpName (ctype
));
1642 Report
.Error (309, loc
,
1643 "The type `{0}' must be convertible to `{1}' in order to " +
1644 "use it as parameter `{2}' in the generic type or method `{3}'",
1645 TypeManager
.CSharpName (expr
.Type
), TypeManager
.CSharpName (ctype
),
1646 TypeManager
.CSharpName (ptype
), GetSignatureForError ());
1651 static bool HasDefaultConstructor (Type atype
)
1653 TypeParameter tparam
= TypeManager
.LookupTypeParameter (atype
);
1654 if (tparam
!= null) {
1655 if (tparam
.GenericConstraints
== null)
1658 return tparam
.GenericConstraints
.HasConstructorConstraint
||
1659 tparam
.GenericConstraints
.HasValueTypeConstraint
;
1662 if (atype
.IsAbstract
)
1666 atype
= TypeManager
.DropGenericTypeArguments (atype
);
1667 if (atype
is TypeBuilder
) {
1668 TypeContainer tc
= TypeManager
.LookupTypeContainer (atype
);
1669 if (tc
.InstanceConstructors
== null) {
1670 atype
= atype
.BaseType
;
1674 foreach (Constructor c
in tc
.InstanceConstructors
) {
1675 if ((c
.ModFlags
& Modifiers
.PUBLIC
) == 0)
1677 if ((c
.Parameters
.FixedParameters
!= null) &&
1678 (c
.Parameters
.FixedParameters
.Length
!= 0))
1680 if (c
.Parameters
.HasArglist
|| c
.Parameters
.HasParams
)
1687 MemberInfo
[] list
= TypeManager
.MemberLookup (null, null, atype
, MemberTypes
.Constructor
,
1688 BindingFlags
.Public
| BindingFlags
.Instance
| BindingFlags
.DeclaredOnly
,
1689 ConstructorInfo
.ConstructorName
, null);
1694 foreach (MethodBase mb
in list
) {
1695 AParametersCollection pd
= TypeManager
.GetParameterData (mb
);
1703 protected abstract string GetSignatureForError ();
1704 protected abstract void Report_SymbolRelatedToPreviousError ();
1706 public static bool CheckConstraints (IMemberContext ec
, MethodBase definition
,
1707 MethodBase instantiated
, Location loc
)
1709 MethodConstraintChecker checker
= new MethodConstraintChecker (
1710 definition
, instantiated
.DeclaringType
, definition
.GetGenericArguments (),
1711 instantiated
.GetGenericArguments (), loc
, ec
.Compiler
.Report
);
1713 return checker
.CheckConstraints (ec
);
1716 public static bool CheckConstraints (IMemberContext ec
, Type gt
, Type
[] gen_params
,
1717 Type
[] atypes
, Location loc
)
1719 TypeConstraintChecker checker
= new TypeConstraintChecker (
1720 gt
, gen_params
, atypes
, loc
, ec
.Compiler
.Report
);
1722 return checker
.CheckConstraints (ec
);
1725 protected class MethodConstraintChecker
: ConstraintChecker
1727 MethodBase definition
;
1728 public Type declaring_type
;
1730 public MethodConstraintChecker (MethodBase definition
, Type declaringType
, Type
[] gen_params
,
1731 Type
[] atypes
, Location loc
, Report r
)
1732 : base (gen_params
, atypes
, loc
, r
)
1734 this.declaring_type
= declaringType
;
1735 this.definition
= definition
;
1738 protected override string GetSignatureForError ()
1740 return TypeManager
.CSharpSignature (definition
);
1743 protected override void Report_SymbolRelatedToPreviousError ()
1745 Report
.SymbolRelatedToPreviousError (definition
);
1749 protected class TypeConstraintChecker
: ConstraintChecker
1753 public TypeConstraintChecker (Type gt
, Type
[] gen_params
, Type
[] atypes
,
1754 Location loc
, Report r
)
1755 : base (gen_params
, atypes
, loc
, r
)
1760 protected override string GetSignatureForError ()
1762 return TypeManager
.CSharpName (gt
);
1765 protected override void Report_SymbolRelatedToPreviousError ()
1767 Report
.SymbolRelatedToPreviousError (gt
);
1773 /// A generic method definition.
1775 public class GenericMethod
: DeclSpace
1777 FullNamedExpression return_type
;
1778 ParametersCompiled parameters
;
1780 public GenericMethod (NamespaceEntry ns
, DeclSpace parent
, MemberName name
,
1781 FullNamedExpression return_type
, ParametersCompiled parameters
)
1782 : base (ns
, parent
, name
, null)
1784 this.return_type
= return_type
;
1785 this.parameters
= parameters
;
1788 public override TypeContainer CurrentTypeDefinition
{
1790 return Parent
.CurrentTypeDefinition
;
1794 public override TypeParameter
[] CurrentTypeParameters
{
1796 return base.type_params
;
1800 public override TypeBuilder
DefineType ()
1802 throw new Exception ();
1805 public override bool Define ()
1807 for (int i
= 0; i
< TypeParameters
.Length
; i
++)
1808 if (!TypeParameters
[i
].Resolve (this))
1815 /// Define and resolve the type parameters.
1816 /// We're called from Method.Define().
1818 public bool Define (MethodOrOperator m
)
1820 TypeParameterName
[] names
= MemberName
.TypeArguments
.GetDeclarations ();
1821 string[] snames
= new string [names
.Length
];
1822 for (int i
= 0; i
< names
.Length
; i
++) {
1823 string type_argument_name
= names
[i
].Name
;
1824 int idx
= parameters
.GetParameterIndexByName (type_argument_name
);
1828 b
= new Block (null);
1830 b
.Error_AlreadyDeclaredTypeParameter (Report
, parameters
[i
].Location
,
1831 type_argument_name
, "method parameter");
1834 snames
[i
] = type_argument_name
;
1837 GenericTypeParameterBuilder
[] gen_params
= m
.MethodBuilder
.DefineGenericParameters (snames
);
1838 for (int i
= 0; i
< TypeParameters
.Length
; i
++)
1839 TypeParameters
[i
].Define (gen_params
[i
]);
1844 for (int i
= 0; i
< TypeParameters
.Length
; i
++) {
1845 if (!TypeParameters
[i
].ResolveType (this))
1853 /// We're called from MethodData.Define() after creating the MethodBuilder.
1855 public bool DefineType (IMemberContext ec
, MethodBuilder mb
,
1856 MethodInfo implementing
, bool is_override
)
1858 for (int i
= 0; i
< TypeParameters
.Length
; i
++)
1859 if (!TypeParameters
[i
].DefineType (
1860 ec
, mb
, implementing
, is_override
))
1863 bool ok
= parameters
.Resolve (ec
);
1865 if ((return_type
!= null) && (return_type
.ResolveAsTypeTerminal (ec
, false) == null))
1871 public void EmitAttributes ()
1873 for (int i
= 0; i
< TypeParameters
.Length
; i
++)
1874 TypeParameters
[i
].Emit ();
1876 if (OptAttributes
!= null)
1877 OptAttributes
.Emit ();
1880 public override MemberList
FindMembers (MemberTypes mt
, BindingFlags bf
,
1881 MemberFilter filter
, object criteria
)
1883 throw new Exception ();
1886 public override string GetSignatureForError ()
1888 return base.GetSignatureForError () + parameters
.GetSignatureForError ();
1891 public override MemberCache MemberCache
{
1897 public override AttributeTargets AttributeTargets
{
1899 return AttributeTargets
.Method
| AttributeTargets
.ReturnValue
;
1903 public override string DocCommentHeader
{
1904 get { return "M:"; }
1907 public new void VerifyClsCompliance ()
1909 foreach (TypeParameter tp
in TypeParameters
) {
1910 if (tp
.Constraints
== null)
1913 tp
.Constraints
.VerifyClsCompliance (Report
);
1918 public partial class TypeManager
1920 static public Type activator_type
;
1922 public static TypeContainer
LookupGenericTypeContainer (Type t
)
1924 t
= DropGenericTypeArguments (t
);
1925 return LookupTypeContainer (t
);
1928 public static Variance
GetTypeParameterVariance (Type type
)
1930 TypeParameter tparam
= LookupTypeParameter (type
);
1932 return tparam
.Variance
;
1934 switch (type
.GenericParameterAttributes
& GenericParameterAttributes
.VarianceMask
) {
1935 case GenericParameterAttributes
.Covariant
:
1936 return Variance
.Covariant
;
1937 case GenericParameterAttributes
.Contravariant
:
1938 return Variance
.Contravariant
;
1940 return Variance
.None
;
1944 public static Variance
CheckTypeVariance (Type t
, Variance expected
, IMemberContext member
)
1946 TypeParameter tp
= LookupTypeParameter (t
);
1948 Variance v
= tp
.Variance
;
1949 if (expected
== Variance
.None
&& v
!= expected
||
1950 expected
== Variance
.Covariant
&& v
== Variance
.Contravariant
||
1951 expected
== Variance
.Contravariant
&& v
== Variance
.Covariant
)
1952 tp
.ErrorInvalidVariance (member
, expected
);
1957 if (t
.IsGenericType
) {
1958 Type
[] targs_definition
= GetTypeArguments (DropGenericTypeArguments (t
));
1959 Type
[] targs
= GetTypeArguments (t
);
1960 for (int i
= 0; i
< targs_definition
.Length
; ++i
) {
1961 Variance v
= GetTypeParameterVariance (targs_definition
[i
]);
1962 CheckTypeVariance (targs
[i
], (Variance
) ((int)v
* (int)expected
), member
);
1969 return CheckTypeVariance (GetElementType (t
), expected
, member
);
1971 return Variance
.None
;
1974 public static bool IsVariantOf (Type type1
, Type type2
)
1976 if (!type1
.IsGenericType
|| !type2
.IsGenericType
)
1979 Type generic_target_type
= DropGenericTypeArguments (type2
);
1980 if (DropGenericTypeArguments (type1
) != generic_target_type
)
1983 Type
[] t1
= GetTypeArguments (type1
);
1984 Type
[] t2
= GetTypeArguments (type2
);
1985 Type
[] targs_definition
= GetTypeArguments (generic_target_type
);
1986 for (int i
= 0; i
< targs_definition
.Length
; ++i
) {
1987 Variance v
= GetTypeParameterVariance (targs_definition
[i
]);
1988 if (v
== Variance
.None
) {
1994 if (v
== Variance
.Covariant
) {
1995 if (!Convert
.ImplicitReferenceConversionExists (new EmptyExpression (t1
[i
]), t2
[i
]))
1997 } else if (!Convert
.ImplicitReferenceConversionExists (new EmptyExpression (t2
[i
]), t1
[i
])) {
2006 /// Check whether `a' and `b' may become equal generic types.
2007 /// The algorithm to do that is a little bit complicated.
2009 public static bool MayBecomeEqualGenericTypes (Type a
, Type b
, Type
[] class_inferred
,
2010 Type
[] method_inferred
)
2012 if (a
.IsGenericParameter
) {
2014 // If a is an array of a's type, they may never
2018 b
= GetElementType (b
);
2024 // If b is a generic parameter or an actual type,
2025 // they may become equal:
2027 // class X<T,U> : I<T>, I<U>
2028 // class X<T> : I<T>, I<float>
2030 if (b
.IsGenericParameter
|| !b
.IsGenericType
) {
2031 int pos
= a
.GenericParameterPosition
;
2032 Type
[] args
= a
.DeclaringMethod
!= null ? method_inferred
: class_inferred
;
2033 if (args
[pos
] == null) {
2038 return args
[pos
] == a
;
2042 // We're now comparing a type parameter with a
2043 // generic instance. They may become equal unless
2044 // the type parameter appears anywhere in the
2045 // generic instance:
2047 // class X<T,U> : I<T>, I<X<U>>
2048 // -> error because you could instanciate it as
2051 // class X<T> : I<T>, I<X<T>> -> ok
2054 Type
[] bargs
= GetTypeArguments (b
);
2055 for (int i
= 0; i
< bargs
.Length
; i
++) {
2056 if (a
.Equals (bargs
[i
]))
2063 if (b
.IsGenericParameter
)
2064 return MayBecomeEqualGenericTypes (b
, a
, class_inferred
, method_inferred
);
2067 // At this point, neither a nor b are a type parameter.
2069 // If one of them is a generic instance, let
2070 // MayBecomeEqualGenericInstances() compare them (if the
2071 // other one is not a generic instance, they can never
2075 if (a
.IsGenericType
|| b
.IsGenericType
)
2076 return MayBecomeEqualGenericInstances (a
, b
, class_inferred
, method_inferred
);
2079 // If both of them are arrays.
2082 if (a
.IsArray
&& b
.IsArray
) {
2083 if (a
.GetArrayRank () != b
.GetArrayRank ())
2086 a
= GetElementType (a
);
2087 b
= GetElementType (b
);
2089 return MayBecomeEqualGenericTypes (a
, b
, class_inferred
, method_inferred
);
2093 // Ok, two ordinary types.
2096 return a
.Equals (b
);
2100 // Checks whether two generic instances may become equal for some
2101 // particular instantiation (26.3.1).
2103 public static bool MayBecomeEqualGenericInstances (Type a
, Type b
,
2104 Type
[] class_inferred
,
2105 Type
[] method_inferred
)
2107 if (!a
.IsGenericType
|| !b
.IsGenericType
)
2109 if (a
.GetGenericTypeDefinition () != b
.GetGenericTypeDefinition ())
2112 return MayBecomeEqualGenericInstances (
2113 GetTypeArguments (a
), GetTypeArguments (b
), class_inferred
, method_inferred
);
2116 public static bool MayBecomeEqualGenericInstances (Type
[] aargs
, Type
[] bargs
,
2117 Type
[] class_inferred
,
2118 Type
[] method_inferred
)
2120 if (aargs
.Length
!= bargs
.Length
)
2123 for (int i
= 0; i
< aargs
.Length
; i
++) {
2124 if (!MayBecomeEqualGenericTypes (aargs
[i
], bargs
[i
], class_inferred
, method_inferred
))
2132 /// Type inference. Try to infer the type arguments from `method',
2133 /// which is invoked with the arguments `arguments'. This is used
2134 /// when resolving an Invocation or a DelegateInvocation and the user
2135 /// did not explicitly specify type arguments.
2137 public static int InferTypeArguments (ResolveContext ec
, Arguments arguments
, ref MethodBase method
)
2139 ATypeInference ti
= ATypeInference
.CreateInstance (arguments
);
2140 Type
[] i_args
= ti
.InferMethodArguments (ec
, method
);
2142 return ti
.InferenceScore
;
2144 if (i_args
.Length
== 0)
2147 method
= ((MethodInfo
) method
).MakeGenericMethod (i_args
);
2152 public static bool InferTypeArguments (ResolveContext ec, AParametersCollection param, ref MethodBase method)
2154 if (!TypeManager.IsGenericMethod (method))
2157 ATypeInference ti = ATypeInference.CreateInstance (DelegateCreation.CreateDelegateMethodArguments (param, Location.Null));
2158 Type[] i_args = ti.InferDelegateArguments (ec, method);
2162 method = ((MethodInfo) method).MakeGenericMethod (i_args);
2168 abstract class ATypeInference
2170 protected readonly Arguments arguments
;
2171 protected readonly int arg_count
;
2173 protected ATypeInference (Arguments arguments
)
2175 this.arguments
= arguments
;
2176 if (arguments
!= null)
2177 arg_count
= arguments
.Count
;
2180 public static ATypeInference
CreateInstance (Arguments arguments
)
2182 return new TypeInference (arguments
);
2185 public virtual int InferenceScore
{
2187 return int.MaxValue
;
2191 public abstract Type
[] InferMethodArguments (ResolveContext ec
, MethodBase method
);
2192 // public abstract Type[] InferDelegateArguments (ResolveContext ec, MethodBase method);
2196 // Implements C# type inference
2198 class TypeInference
: ATypeInference
2201 // Tracks successful rate of type inference
2203 int score
= int.MaxValue
;
2205 public TypeInference (Arguments arguments
)
2210 public override int InferenceScore
{
2217 public override Type[] InferDelegateArguments (ResolveContext ec, MethodBase method)
2219 AParametersCollection pd = TypeManager.GetParameterData (method);
2220 if (arg_count != pd.Count)
2223 Type[] d_gargs = method.GetGenericArguments ();
2224 TypeInferenceContext context = new TypeInferenceContext (d_gargs);
2226 // A lower-bound inference is made from each argument type Uj of D
2227 // to the corresponding parameter type Tj of M
2228 for (int i = 0; i < arg_count; ++i) {
2229 Type t = pd.Types [i];
2230 if (!t.IsGenericParameter)
2233 context.LowerBoundInference (arguments [i].Expr.Type, t);
2236 if (!context.FixAllTypes (ec))
2239 return context.InferredTypeArguments;
2242 public override Type
[] InferMethodArguments (ResolveContext ec
, MethodBase method
)
2244 Type
[] method_generic_args
= method
.GetGenericArguments ();
2245 TypeInferenceContext context
= new TypeInferenceContext (method_generic_args
);
2246 if (!context
.UnfixedVariableExists
)
2247 return Type
.EmptyTypes
;
2249 AParametersCollection pd
= TypeManager
.GetParameterData (method
);
2250 if (!InferInPhases (ec
, context
, pd
))
2253 return context
.InferredTypeArguments
;
2257 // Implements method type arguments inference
2259 bool InferInPhases (ResolveContext ec
, TypeInferenceContext tic
, AParametersCollection methodParameters
)
2261 int params_arguments_start
;
2262 if (methodParameters
.HasParams
) {
2263 params_arguments_start
= methodParameters
.Count
- 1;
2265 params_arguments_start
= arg_count
;
2268 Type
[] ptypes
= methodParameters
.Types
;
2271 // The first inference phase
2273 Type method_parameter
= null;
2274 for (int i
= 0; i
< arg_count
; i
++) {
2275 Argument a
= arguments
[i
];
2279 if (i
< params_arguments_start
) {
2280 method_parameter
= methodParameters
.Types
[i
];
2281 } else if (i
== params_arguments_start
) {
2282 if (arg_count
== params_arguments_start
+ 1 && TypeManager
.HasElementType (a
.Type
))
2283 method_parameter
= methodParameters
.Types
[params_arguments_start
];
2285 method_parameter
= TypeManager
.GetElementType (methodParameters
.Types
[params_arguments_start
]);
2287 ptypes
= (Type
[]) ptypes
.Clone ();
2288 ptypes
[i
] = method_parameter
;
2292 // When a lambda expression, an anonymous method
2293 // is used an explicit argument type inference takes a place
2295 AnonymousMethodExpression am
= a
.Expr
as AnonymousMethodExpression
;
2297 if (am
.ExplicitTypeInference (ec
, tic
, method_parameter
))
2303 score
-= tic
.ExactInference (a
.Type
, method_parameter
);
2307 if (a
.Expr
.Type
== TypeManager
.null_type
)
2310 if (TypeManager
.IsValueType (method_parameter
)) {
2311 score
-= tic
.LowerBoundInference (a
.Type
, method_parameter
);
2316 // Otherwise an output type inference is made
2318 score
-= tic
.OutputTypeInference (ec
, a
.Expr
, method_parameter
);
2322 // Part of the second phase but because it happens only once
2323 // we don't need to call it in cycle
2325 bool fixed_any
= false;
2326 if (!tic
.FixIndependentTypeArguments (ec
, ptypes
, ref fixed_any
))
2329 return DoSecondPhase (ec
, tic
, ptypes
, !fixed_any
);
2332 bool DoSecondPhase (ResolveContext ec
, TypeInferenceContext tic
, Type
[] methodParameters
, bool fixDependent
)
2334 bool fixed_any
= false;
2335 if (fixDependent
&& !tic
.FixDependentTypes (ec
, ref fixed_any
))
2338 // If no further unfixed type variables exist, type inference succeeds
2339 if (!tic
.UnfixedVariableExists
)
2342 if (!fixed_any
&& fixDependent
)
2345 // For all arguments where the corresponding argument output types
2346 // contain unfixed type variables but the input types do not,
2347 // an output type inference is made
2348 for (int i
= 0; i
< arg_count
; i
++) {
2350 // Align params arguments
2351 Type t_i
= methodParameters
[i
>= methodParameters
.Length
? methodParameters
.Length
- 1: i
];
2353 if (!TypeManager
.IsDelegateType (t_i
)) {
2354 if (TypeManager
.DropGenericTypeArguments (t_i
) != TypeManager
.expression_type
)
2357 t_i
= t_i
.GetGenericArguments () [0];
2360 MethodInfo mi
= Delegate
.GetInvokeMethod (ec
.Compiler
, t_i
, t_i
);
2361 Type rtype
= mi
.ReturnType
;
2364 // Blablabla, because reflection does not work with dynamic types
2365 Type
[] g_args
= t_i
.GetGenericArguments ();
2366 rtype
= g_args
[rtype
.GenericParameterPosition
];
2369 if (tic
.IsReturnTypeNonDependent (ec
, mi
, rtype
))
2370 score
-= tic
.OutputTypeInference (ec
, arguments
[i
].Expr
, t_i
);
2374 return DoSecondPhase (ec
, tic
, methodParameters
, true);
2378 public class TypeInferenceContext
2389 public readonly Type Type
;
2390 public readonly BoundKind Kind
;
2392 public BoundInfo (Type type
, BoundKind kind
)
2398 public override int GetHashCode ()
2400 return Type
.GetHashCode ();
2403 public override bool Equals (object obj
)
2405 BoundInfo a
= (BoundInfo
) obj
;
2406 return Type
== a
.Type
&& Kind
== a
.Kind
;
2410 readonly Type
[] unfixed_types
;
2411 readonly Type
[] fixed_types
;
2412 readonly ArrayList
[] bounds
;
2415 public TypeInferenceContext (Type
[] typeArguments
)
2417 if (typeArguments
.Length
== 0)
2418 throw new ArgumentException ("Empty generic arguments");
2420 fixed_types
= new Type
[typeArguments
.Length
];
2421 for (int i
= 0; i
< typeArguments
.Length
; ++i
) {
2422 if (typeArguments
[i
].IsGenericParameter
) {
2423 if (bounds
== null) {
2424 bounds
= new ArrayList
[typeArguments
.Length
];
2425 unfixed_types
= new Type
[typeArguments
.Length
];
2427 unfixed_types
[i
] = typeArguments
[i
];
2429 fixed_types
[i
] = typeArguments
[i
];
2435 // Used together with AddCommonTypeBound fo implement
2436 // 7.4.2.13 Finding the best common type of a set of expressions
2438 public TypeInferenceContext ()
2440 fixed_types
= new Type
[1];
2441 unfixed_types
= new Type
[1];
2442 unfixed_types
[0] = InternalType
.Arglist
; // it can be any internal type
2443 bounds
= new ArrayList
[1];
2446 public Type
[] InferredTypeArguments
{
2452 public void AddCommonTypeBound (Type type
)
2454 AddToBounds (new BoundInfo (type
, BoundKind
.Lower
), 0);
2457 void AddToBounds (BoundInfo bound
, int index
)
2460 // Some types cannot be used as type arguments
2462 if (bound
.Type
== TypeManager
.void_type
|| bound
.Type
.IsPointer
)
2465 ArrayList a
= bounds
[index
];
2467 a
= new ArrayList ();
2470 if (a
.Contains (bound
))
2475 // SPEC: does not cover type inference using constraints
2477 //if (TypeManager.IsGenericParameter (t)) {
2478 // GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
2479 // if (constraints != null) {
2480 // //if (constraints.EffectiveBaseClass != null)
2481 // // t = constraints.EffectiveBaseClass;
2487 bool AllTypesAreFixed (Type
[] types
)
2489 foreach (Type t
in types
) {
2490 if (t
.IsGenericParameter
) {
2496 if (t
.IsGenericType
)
2497 return AllTypesAreFixed (t
.GetGenericArguments ());
2504 // 26.3.3.8 Exact Inference
2506 public int ExactInference (Type u
, Type v
)
2508 // If V is an array type
2513 if (u
.GetArrayRank () != v
.GetArrayRank ())
2516 return ExactInference (TypeManager
.GetElementType (u
), TypeManager
.GetElementType (v
));
2519 // If V is constructed type and U is constructed type
2520 if (v
.IsGenericType
&& !v
.IsGenericTypeDefinition
) {
2521 if (!u
.IsGenericType
)
2524 Type
[] ga_u
= u
.GetGenericArguments ();
2525 Type
[] ga_v
= v
.GetGenericArguments ();
2526 if (ga_u
.Length
!= ga_v
.Length
)
2530 for (int i
= 0; i
< ga_u
.Length
; ++i
)
2531 score
+= ExactInference (ga_u
[i
], ga_v
[i
]);
2533 return score
> 0 ? 1 : 0;
2536 // If V is one of the unfixed type arguments
2537 int pos
= IsUnfixed (v
);
2541 AddToBounds (new BoundInfo (u
, BoundKind
.Exact
), pos
);
2545 public bool FixAllTypes (ResolveContext ec
)
2547 for (int i
= 0; i
< unfixed_types
.Length
; ++i
) {
2548 if (!FixType (ec
, i
))
2555 // All unfixed type variables Xi are fixed for which all of the following hold:
2556 // a, There is at least one type variable Xj that depends on Xi
2557 // b, Xi has a non-empty set of bounds
2559 public bool FixDependentTypes (ResolveContext ec
, ref bool fixed_any
)
2561 for (int i
= 0; i
< unfixed_types
.Length
; ++i
) {
2562 if (unfixed_types
[i
] == null)
2565 if (bounds
[i
] == null)
2568 if (!FixType (ec
, i
))
2578 // All unfixed type variables Xi which depend on no Xj are fixed
2580 public bool FixIndependentTypeArguments (ResolveContext ec
, Type
[] methodParameters
, ref bool fixed_any
)
2582 ArrayList types_to_fix
= new ArrayList (unfixed_types
);
2583 for (int i
= 0; i
< methodParameters
.Length
; ++i
) {
2584 Type t
= methodParameters
[i
];
2586 if (!TypeManager
.IsDelegateType (t
)) {
2587 if (TypeManager
.DropGenericTypeArguments (t
) != TypeManager
.expression_type
)
2590 t
= t
.GetGenericArguments () [0];
2593 if (t
.IsGenericParameter
)
2596 MethodInfo invoke
= Delegate
.GetInvokeMethod (ec
.Compiler
, t
, t
);
2597 Type rtype
= invoke
.ReturnType
;
2598 if (!rtype
.IsGenericParameter
&& !rtype
.IsGenericType
)
2602 // Blablabla, because reflection does not work with dynamic types
2603 if (rtype
.IsGenericParameter
) {
2604 Type
[] g_args
= t
.GetGenericArguments ();
2605 rtype
= g_args
[rtype
.GenericParameterPosition
];
2608 // Remove dependent types, they cannot be fixed yet
2609 RemoveDependentTypes (types_to_fix
, rtype
);
2612 foreach (Type t
in types_to_fix
) {
2616 int idx
= IsUnfixed (t
);
2617 if (idx
>= 0 && !FixType (ec
, idx
)) {
2622 fixed_any
= types_to_fix
.Count
> 0;
2629 public bool FixType (ResolveContext ec
, int i
)
2631 // It's already fixed
2632 if (unfixed_types
[i
] == null)
2633 throw new InternalErrorException ("Type argument has been already fixed");
2638 ArrayList candidates
= (ArrayList
)bounds
[i
];
2639 if (candidates
== null)
2642 if (candidates
.Count
== 1) {
2643 unfixed_types
[i
] = null;
2644 Type t
= ((BoundInfo
) candidates
[0]).Type
;
2645 if (t
== TypeManager
.null_type
)
2648 fixed_types
[i
] = t
;
2653 // Determines a unique type from which there is
2654 // a standard implicit conversion to all the other
2657 Type best_candidate
= null;
2659 int candidates_count
= candidates
.Count
;
2660 for (int ci
= 0; ci
< candidates_count
; ++ci
) {
2661 BoundInfo bound
= (BoundInfo
)candidates
[ci
];
2662 for (cii
= 0; cii
< candidates_count
; ++cii
) {
2666 BoundInfo cbound
= (BoundInfo
) candidates
[cii
];
2668 // Same type parameters with different bounds
2669 if (cbound
.Type
== bound
.Type
) {
2670 if (bound
.Kind
!= BoundKind
.Exact
)
2676 if (bound
.Kind
== BoundKind
.Exact
|| cbound
.Kind
== BoundKind
.Exact
) {
2677 if (cbound
.Kind
!= BoundKind
.Exact
) {
2678 if (!Convert
.ImplicitConversionExists (ec
, new TypeExpression (cbound
.Type
, Location
.Null
), bound
.Type
)) {
2685 if (bound
.Kind
!= BoundKind
.Exact
) {
2686 if (!Convert
.ImplicitConversionExists (ec
, new TypeExpression (bound
.Type
, Location
.Null
), cbound
.Type
)) {
2697 if (bound
.Kind
== BoundKind
.Lower
) {
2698 if (!Convert
.ImplicitConversionExists (ec
, new TypeExpression (cbound
.Type
, Location
.Null
), bound
.Type
)) {
2702 if (!Convert
.ImplicitConversionExists (ec
, new TypeExpression (bound
.Type
, Location
.Null
), cbound
.Type
)) {
2708 if (cii
!= candidates_count
)
2711 if (best_candidate
!= null && best_candidate
!= bound
.Type
)
2714 best_candidate
= bound
.Type
;
2717 if (best_candidate
== null)
2720 unfixed_types
[i
] = null;
2721 fixed_types
[i
] = best_candidate
;
2726 // Uses inferred types to inflate delegate type argument
2728 public Type
InflateGenericArgument (Type parameter
)
2730 if (parameter
.IsGenericParameter
) {
2732 // Inflate method generic argument (MVAR) only
2734 if (parameter
.DeclaringMethod
== null)
2737 return fixed_types
[parameter
.GenericParameterPosition
];
2740 if (parameter
.IsGenericType
) {
2741 Type
[] parameter_targs
= parameter
.GetGenericArguments ();
2742 for (int ii
= 0; ii
< parameter_targs
.Length
; ++ii
) {
2743 parameter_targs
[ii
] = InflateGenericArgument (parameter_targs
[ii
]);
2745 return parameter
.GetGenericTypeDefinition ().MakeGenericType (parameter_targs
);
2752 // Tests whether all delegate input arguments are fixed and generic output type
2753 // requires output type inference
2755 public bool IsReturnTypeNonDependent (ResolveContext ec
, MethodInfo invoke
, Type returnType
)
2757 if (returnType
.IsGenericParameter
) {
2758 if (IsFixed (returnType
))
2760 } else if (returnType
.IsGenericType
) {
2761 if (TypeManager
.IsDelegateType (returnType
)) {
2762 invoke
= Delegate
.GetInvokeMethod (ec
.Compiler
, returnType
, returnType
);
2763 return IsReturnTypeNonDependent (ec
, invoke
, invoke
.ReturnType
);
2766 Type
[] g_args
= returnType
.GetGenericArguments ();
2768 // At least one unfixed return type has to exist
2769 if (AllTypesAreFixed (g_args
))
2775 // All generic input arguments have to be fixed
2776 AParametersCollection d_parameters
= TypeManager
.GetParameterData (invoke
);
2777 return AllTypesAreFixed (d_parameters
.Types
);
2780 bool IsFixed (Type type
)
2782 return IsUnfixed (type
) == -1;
2785 int IsUnfixed (Type type
)
2787 if (!type
.IsGenericParameter
)
2790 //return unfixed_types[type.GenericParameterPosition] != null;
2791 for (int i
= 0; i
< unfixed_types
.Length
; ++i
) {
2792 if (unfixed_types
[i
] == type
)
2800 // 26.3.3.9 Lower-bound Inference
2802 public int LowerBoundInference (Type u
, Type v
)
2804 return LowerBoundInference (u
, v
, false);
2808 // Lower-bound (false) or Upper-bound (true) inference based on inversed argument
2810 int LowerBoundInference (Type u
, Type v
, bool inversed
)
2812 // If V is one of the unfixed type arguments
2813 int pos
= IsUnfixed (v
);
2815 AddToBounds (new BoundInfo (u
, inversed
? BoundKind
.Upper
: BoundKind
.Lower
), pos
);
2819 // If U is an array type
2821 int u_dim
= u
.GetArrayRank ();
2823 Type u_i
= TypeManager
.GetElementType (u
);
2826 if (u_dim
!= v
.GetArrayRank ())
2829 v_i
= TypeManager
.GetElementType (v
);
2831 if (TypeManager
.IsValueType (u_i
))
2832 return ExactInference (u_i
, v_i
);
2834 return LowerBoundInference (u_i
, v_i
, inversed
);
2840 if (v
.IsGenericType
) {
2841 Type g_v
= v
.GetGenericTypeDefinition ();
2842 if ((g_v
!= TypeManager
.generic_ilist_type
) && (g_v
!= TypeManager
.generic_icollection_type
) &&
2843 (g_v
!= TypeManager
.generic_ienumerable_type
))
2846 v_i
= TypeManager
.TypeToCoreType (TypeManager
.GetTypeArguments (v
) [0]);
2847 if (TypeManager
.IsValueType (u_i
))
2848 return ExactInference (u_i
, v_i
);
2850 return LowerBoundInference (u_i
, v_i
);
2852 } else if (v
.IsGenericType
&& !v
.IsGenericTypeDefinition
) {
2854 // if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
2855 // such that U is identical to, inherits from (directly or indirectly),
2856 // or implements (directly or indirectly) C<U1..Uk>
2858 ArrayList u_candidates
= new ArrayList ();
2859 if (u
.IsGenericType
)
2860 u_candidates
.Add (u
);
2862 for (Type t
= u
.BaseType
; t
!= null; t
= t
.BaseType
) {
2863 if (t
.IsGenericType
&& !t
.IsGenericTypeDefinition
)
2864 u_candidates
.Add (t
);
2867 // TODO: Implement GetGenericInterfaces only and remove
2868 // the if from foreach
2869 u_candidates
.AddRange (TypeManager
.GetInterfaces (u
));
2871 Type open_v
= v
.GetGenericTypeDefinition ();
2872 Type
[] unique_candidate_targs
= null;
2873 Type
[] ga_v
= v
.GetGenericArguments ();
2874 foreach (Type u_candidate
in u_candidates
) {
2875 if (!u_candidate
.IsGenericType
|| u_candidate
.IsGenericTypeDefinition
)
2878 if (TypeManager
.DropGenericTypeArguments (u_candidate
) != open_v
)
2882 // The unique set of types U1..Uk means that if we have an interface I<T>,
2883 // class U : I<int>, I<long> then no type inference is made when inferring
2884 // type I<T> by applying type U because T could be int or long
2886 if (unique_candidate_targs
!= null) {
2887 Type
[] second_unique_candidate_targs
= u_candidate
.GetGenericArguments ();
2888 if (TypeManager
.IsEqual (unique_candidate_targs
, second_unique_candidate_targs
)) {
2889 unique_candidate_targs
= second_unique_candidate_targs
;
2894 // This should always cause type inference failure
2900 unique_candidate_targs
= u_candidate
.GetGenericArguments ();
2903 if (unique_candidate_targs
!= null) {
2904 Type
[] ga_open_v
= open_v
.GetGenericArguments ();
2906 for (int i
= 0; i
< unique_candidate_targs
.Length
; ++i
) {
2907 Variance variance
= TypeManager
.GetTypeParameterVariance (ga_open_v
[i
]);
2909 Type u_i
= unique_candidate_targs
[i
];
2910 if (variance
== Variance
.None
|| TypeManager
.IsValueType (u_i
)) {
2911 if (ExactInference (u_i
, ga_v
[i
]) == 0)
2914 bool upper_bound
= (variance
== Variance
.Contravariant
&& !inversed
) ||
2915 (variance
== Variance
.Covariant
&& inversed
);
2917 if (LowerBoundInference (u_i
, ga_v
[i
], upper_bound
) == 0)
2929 // 26.3.3.6 Output Type Inference
2931 public int OutputTypeInference (ResolveContext ec
, Expression e
, Type t
)
2933 // If e is a lambda or anonymous method with inferred return type
2934 AnonymousMethodExpression ame
= e
as AnonymousMethodExpression
;
2936 Type rt
= ame
.InferReturnType (ec
, this, t
);
2937 MethodInfo invoke
= Delegate
.GetInvokeMethod (ec
.Compiler
, t
, t
);
2940 AParametersCollection pd
= TypeManager
.GetParameterData (invoke
);
2941 return ame
.Parameters
.Count
== pd
.Count
? 1 : 0;
2944 Type rtype
= invoke
.ReturnType
;
2946 // Blablabla, because reflection does not work with dynamic types
2947 Type
[] g_args
= t
.GetGenericArguments ();
2948 rtype
= g_args
[rtype
.GenericParameterPosition
];
2950 return LowerBoundInference (rt
, rtype
) + 1;
2954 // if E is a method group and T is a delegate type or expression tree type
2955 // return type Tb with parameter types T1..Tk and return type Tb, and overload
2956 // resolution of E with the types T1..Tk yields a single method with return type U,
2957 // then a lower-bound inference is made from U for Tb.
2959 if (e
is MethodGroupExpr
) {
2960 // TODO: Or expression tree
2961 if (!TypeManager
.IsDelegateType (t
))
2964 MethodInfo invoke
= Delegate
.GetInvokeMethod (ec
.Compiler
, t
, t
);
2965 Type rtype
= invoke
.ReturnType
;
2967 // Blablabla, because reflection does not work with dynamic types
2968 Type
[] g_args
= t
.GetGenericArguments ();
2969 rtype
= g_args
[rtype
.GenericParameterPosition
];
2972 if (!TypeManager
.IsGenericType (rtype
))
2975 MethodGroupExpr mg
= (MethodGroupExpr
) e
;
2976 Arguments args
= DelegateCreation
.CreateDelegateMethodArguments (TypeManager
.GetParameterData (invoke
), e
.Location
);
2977 mg
= mg
.OverloadResolve (ec
, ref args
, true, e
.Location
);
2981 // TODO: What should happen when return type is of generic type ?
2982 throw new NotImplementedException ();
2983 // return LowerBoundInference (null, rtype) + 1;
2987 // if e is an expression with type U, then
2988 // a lower-bound inference is made from U for T
2990 return LowerBoundInference (e
.Type
, t
) * 2;
2993 void RemoveDependentTypes (ArrayList types
, Type returnType
)
2995 int idx
= IsUnfixed (returnType
);
3001 if (returnType
.IsGenericType
) {
3002 foreach (Type t
in returnType
.GetGenericArguments ()) {
3003 RemoveDependentTypes (types
, t
);
3008 public bool UnfixedVariableExists
{
3010 if (unfixed_types
== null)
3013 foreach (Type ut
in unfixed_types
)