2 // generic.cs: Generics support
4 // Authors: Martin Baulig (martin@ximian.com)
5 // Miguel de Icaza (miguel@ximian.com)
6 // Marek Safar (marek.safar@gmail.com)
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
10 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004-2008 Novell, Inc
14 using System
.Reflection
;
15 using System
.Reflection
.Emit
;
16 using System
.Globalization
;
17 using System
.Collections
.Generic
;
20 namespace Mono
.CSharp
{
23 /// Abstract base class for type parameter constraints.
24 /// The type parameter can come from a generic type definition or from reflection.
26 public abstract class GenericConstraints
{
27 public abstract GenericParameterAttributes Attributes
{
31 public bool HasConstructorConstraint
{
32 get { return (Attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0; }
35 public bool HasReferenceTypeConstraint
{
36 get { return (Attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0; }
39 public bool HasValueTypeConstraint
{
40 get { return (Attributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0; }
43 public virtual bool HasClassConstraint
{
44 get { return ClassConstraint != null; }
47 public abstract Type ClassConstraint
{
51 public abstract Type
[] InterfaceConstraints
{
55 public abstract Type EffectiveBaseClass
{
60 // Returns whether the type parameter is "known to be a reference type".
62 public virtual bool IsReferenceType
{
64 if (HasReferenceTypeConstraint
)
66 if (HasValueTypeConstraint
)
69 if (ClassConstraint
!= null) {
70 if (ClassConstraint
.IsValueType
)
73 if (ClassConstraint
!= TypeManager
.object_type
)
77 foreach (Type t
in InterfaceConstraints
) {
78 if (!t
.IsGenericParameter
)
81 GenericConstraints gc
= TypeManager
.GetTypeParameterConstraints (t
);
82 if ((gc
!= null) && gc
.IsReferenceType
)
91 // Returns whether the type parameter is "known to be a value type".
93 public virtual bool IsValueType
{
95 if (HasValueTypeConstraint
)
97 if (HasReferenceTypeConstraint
)
100 if (ClassConstraint
!= null) {
101 if (!TypeManager
.IsValueType (ClassConstraint
))
104 if (ClassConstraint
!= TypeManager
.value_type
)
108 foreach (Type t
in InterfaceConstraints
) {
109 if (!t
.IsGenericParameter
)
112 GenericConstraints gc
= TypeManager
.GetTypeParameterConstraints (t
);
113 if ((gc
!= null) && gc
.IsValueType
)
122 public class ReflectionConstraints
: GenericConstraints
124 GenericParameterAttributes attrs
;
126 Type class_constraint
;
127 Type
[] iface_constraints
;
129 public static GenericConstraints
GetConstraints (Type t
)
131 Type
[] constraints
= t
.GetGenericParameterConstraints ();
132 GenericParameterAttributes attrs
= t
.GenericParameterAttributes
;
133 if (constraints
.Length
== 0 && attrs
== GenericParameterAttributes
.None
)
135 return new ReflectionConstraints (t
.Name
, constraints
, attrs
);
138 private ReflectionConstraints (string name
, Type
[] constraints
, GenericParameterAttributes attrs
)
142 int interface_constraints_pos
= 0;
143 if ((attrs
& GenericParameterAttributes
.NotNullableValueTypeConstraint
) != 0) {
144 base_type
= TypeManager
.value_type
;
145 interface_constraints_pos
= 1;
146 } else if ((attrs
& GenericParameterAttributes
.ReferenceTypeConstraint
) != 0) {
147 if (constraints
.Length
> 0 && constraints
[0].IsClass
) {
148 class_constraint
= base_type
= constraints
[0];
149 interface_constraints_pos
= 1;
151 base_type
= TypeManager
.object_type
;
154 base_type
= TypeManager
.object_type
;
157 if (constraints
.Length
> interface_constraints_pos
) {
158 if (interface_constraints_pos
== 0) {
159 iface_constraints
= constraints
;
161 iface_constraints
= new Type
[constraints
.Length
- interface_constraints_pos
];
162 Array
.Copy (constraints
, interface_constraints_pos
, iface_constraints
, 0, iface_constraints
.Length
);
165 iface_constraints
= Type
.EmptyTypes
;
169 public override GenericParameterAttributes Attributes
171 get { return attrs; }
174 public override Type ClassConstraint
176 get { return class_constraint; }
179 public override Type EffectiveBaseClass
181 get { return base_type; }
184 public override Type
[] InterfaceConstraints
186 get { return iface_constraints; }
193 // Don't add or modify internal values, they are used as -/+ calculation signs
201 public enum SpecialConstraint
204 Constructor
= 1 << 2,
209 public class SpecialContraintExpr
: FullNamedExpression
211 public SpecialContraintExpr (SpecialConstraint constraint
, Location loc
)
214 this.Constraint
= constraint
;
217 public SpecialConstraint Constraint { get; private set; }
219 protected override Expression
DoResolve (ResolveContext rc
)
221 throw new NotImplementedException ();
226 // A set of parsed constraints for a type parameter
228 public class Constraints
: GenericConstraints
230 SimpleMemberName tparam
;
231 List
<FullNamedExpression
> constraints
;
233 GenericParameterAttributes attrs
;
234 TypeExpr class_constraint
;
235 List
<TypeExpr
> iface_constraints
;
236 List
<TypeExpr
> type_param_constraints
;
238 Type class_constraint_type
;
239 Type
[] iface_constraint_types
;
240 Type effective_base_type
;
245 // name is the identifier, constraints is an arraylist of
246 // Expressions (with types) or `true' for the constructor constraint.
248 public Constraints (SimpleMemberName tparam
, List
<FullNamedExpression
> constraints
, Location loc
)
250 this.tparam
= tparam
;
251 this.constraints
= constraints
;
257 public SimpleMemberName TypeParameter
{
265 public Constraints
Clone ()
267 return new Constraints (tparam
, constraints
, loc
);
271 /// Resolve the constraints - but only resolve things into Expression's, not
272 /// into actual types.
274 public bool Resolve (MemberCore ec
, TypeParameter tp
, Report Report
)
282 iface_constraints
= new List
<TypeExpr
> (2); // TODO: Too expensive allocation
283 type_param_constraints
= new List
<TypeExpr
> ();
285 foreach (var obj
in constraints
) {
287 if (obj
is SpecialContraintExpr
) {
288 SpecialConstraint sc
= ((SpecialContraintExpr
) obj
).Constraint
;
290 if (sc
== SpecialConstraint
.Constructor
) {
291 if (!HasValueTypeConstraint
) {
292 attrs
|= GenericParameterAttributes
.DefaultConstructorConstraint
;
297 if (sc
== SpecialConstraint
.Class
)
298 attrs
|= GenericParameterAttributes
.ReferenceTypeConstraint
;
300 attrs
|= GenericParameterAttributes
.NotNullableValueTypeConstraint
;
304 int errors
= Report
.Errors
;
305 FullNamedExpression fn
= obj
.ResolveAsTypeStep (ec
, false);
308 if (errors
!= Report
.Errors
)
311 NamespaceEntry
.Error_NamespaceNotFound (loc
, obj
.GetSignatureForError (), Report
);
316 GenericTypeExpr cexpr
= fn
as GenericTypeExpr
;
318 expr
= cexpr
.ResolveAsBaseTerminal (ec
, false);
319 if (expr
!= null && cexpr
.HasDynamicArguments ()) {
320 Report
.Error (1968, cexpr
.Location
,
321 "A constraint cannot be the dynamic type `{0}'",
322 cexpr
.GetSignatureForError ());
326 expr
= ((Expression
) obj
).ResolveAsTypeTerminal (ec
, false);
328 if ((expr
== null) || (expr
.Type
== null))
331 if (TypeManager
.IsGenericParameter (expr
.Type
))
332 type_param_constraints
.Add (expr
);
333 else if (expr
.IsInterface
)
334 iface_constraints
.Add (expr
);
335 else if (class_constraint
!= null || iface_constraints
.Count
!= 0) {
336 Report
.Error (406, loc
,
337 "The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
338 expr
.GetSignatureForError ());
340 } else if (HasReferenceTypeConstraint
|| HasValueTypeConstraint
) {
341 Report
.Error (450, loc
, "`{0}': cannot specify both " +
342 "a constraint class and the `class' " +
343 "or `struct' constraint", expr
.GetSignatureForError ());
346 class_constraint
= expr
;
350 // Checks whether each generic method parameter constraint type
351 // is valid with respect to T
353 if (tp
!= null && tp
.Type
.DeclaringMethod
!= null) {
354 TypeManager
.CheckTypeVariance (expr
.Type
, Variance
.Contravariant
, ec
as MemberCore
);
357 if (!ec
.IsAccessibleAs (fn
.Type
)) {
358 Report
.SymbolRelatedToPreviousError (fn
.Type
);
359 Report
.Error (703, loc
,
360 "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
361 fn
.GetSignatureForError (), ec
.GetSignatureForError ());
367 var list
= new List
<Type
> ();
368 foreach (TypeExpr iface_constraint
in iface_constraints
) {
369 foreach (Type type
in list
) {
370 if (!type
.Equals (iface_constraint
.Type
))
373 Report
.Error (405, loc
,
374 "Duplicate constraint `{0}' for type " +
375 "parameter `{1}'.", iface_constraint
.GetSignatureForError (),
380 list
.Add (iface_constraint
.Type
);
383 foreach (TypeExpr expr
in type_param_constraints
) {
384 foreach (Type type
in list
) {
385 if (!type
.Equals (expr
.Type
))
388 Report
.Error (405, loc
,
389 "Duplicate constraint `{0}' for type " +
390 "parameter `{1}'.", expr
.GetSignatureForError (), tparam
.Value
);
394 list
.Add (expr
.Type
);
397 iface_constraint_types
= new Type
[list
.Count
];
398 list
.CopyTo (iface_constraint_types
, 0);
400 if (class_constraint
!= null) {
401 class_constraint_type
= class_constraint
.Type
;
402 if (class_constraint_type
== null)
405 if (class_constraint_type
.IsSealed
) {
406 if (class_constraint_type
.IsAbstract
)
408 Report
.Error (717, loc
, "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
409 TypeManager
.CSharpName (class_constraint_type
));
413 Report
.Error (701, loc
, "`{0}' is not a valid constraint. A constraint must be an interface, " +
414 "a non-sealed class or a type parameter", TypeManager
.CSharpName(class_constraint_type
));
419 if ((class_constraint_type
== TypeManager
.array_type
) ||
420 (class_constraint_type
== TypeManager
.delegate_type
) ||
421 (class_constraint_type
== TypeManager
.enum_type
) ||
422 (class_constraint_type
== TypeManager
.value_type
) ||
423 (class_constraint_type
== TypeManager
.object_type
) ||
424 class_constraint_type
== TypeManager
.multicast_delegate_type
) {
425 Report
.Error (702, loc
,
426 "A constraint cannot be special class `{0}'",
427 TypeManager
.CSharpName (class_constraint_type
));
431 if (TypeManager
.IsDynamicType (class_constraint_type
)) {
432 Report
.Error (1967, loc
, "A constraint cannot be the dynamic type");
437 if (class_constraint_type
!= null)
438 effective_base_type
= class_constraint_type
;
439 else if (HasValueTypeConstraint
)
440 effective_base_type
= TypeManager
.value_type
;
442 effective_base_type
= TypeManager
.object_type
;
444 if ((attrs
& GenericParameterAttributes
.NotNullableValueTypeConstraint
) != 0)
445 attrs
|= GenericParameterAttributes
.DefaultConstructorConstraint
;
451 bool CheckTypeParameterConstraints (Type tparam
, ref TypeExpr prevConstraint
, List
<Type
> seen
, Report Report
)
455 Constraints constraints
= TypeManager
.LookupTypeParameter (tparam
).Constraints
;
456 if (constraints
== null)
459 if (constraints
.HasValueTypeConstraint
) {
460 Report
.Error (456, loc
,
461 "Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
462 tparam
.Name
, this.tparam
.Value
);
467 // Checks whether there are no conflicts between type parameter constraints
471 // where U : A, B // A and B are not convertible
473 if (constraints
.HasClassConstraint
) {
474 if (prevConstraint
!= null) {
475 Type t2
= constraints
.ClassConstraint
;
476 TypeExpr e2
= constraints
.class_constraint
;
478 if (!Convert
.ImplicitReferenceConversionExists (prevConstraint
, t2
) &&
479 !Convert
.ImplicitReferenceConversionExists (e2
, prevConstraint
.Type
)) {
480 Report
.Error (455, loc
,
481 "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
482 this.tparam
.Value
, TypeManager
.CSharpName (prevConstraint
.Type
), TypeManager
.CSharpName (t2
));
487 prevConstraint
= constraints
.class_constraint
;
490 if (constraints
.type_param_constraints
== null)
493 foreach (TypeExpr expr
in constraints
.type_param_constraints
) {
494 if (seen
.Contains (expr
.Type
)) {
495 Report
.Error (454, loc
, "Circular constraint " +
496 "dependency involving `{0}' and `{1}'",
497 tparam
.Name
, expr
.GetSignatureForError ());
501 if (!CheckTypeParameterConstraints (expr
.Type
, ref prevConstraint
, seen
, Report
))
509 /// Resolve the constraints into actual types.
511 public bool ResolveTypes (IMemberContext ec
, Report r
)
516 resolved_types
= true;
518 foreach (object obj
in constraints
) {
519 GenericTypeExpr cexpr
= obj
as GenericTypeExpr
;
523 if (!cexpr
.CheckConstraints (ec
))
527 if (type_param_constraints
.Count
!= 0) {
528 var seen
= new List
<Type
> ();
529 TypeExpr prev_constraint
= class_constraint
;
530 foreach (TypeExpr expr
in type_param_constraints
) {
531 if (!CheckTypeParameterConstraints (expr
.Type
, ref prev_constraint
, seen
, r
))
537 for (int i
= 0; i
< iface_constraints
.Count
; ++i
) {
538 TypeExpr iface_constraint
= (TypeExpr
) iface_constraints
[i
];
539 iface_constraint
= iface_constraint
.ResolveAsTypeTerminal (ec
, false);
540 if (iface_constraint
== null)
542 iface_constraints
[i
] = iface_constraint
;
545 if (class_constraint
!= null) {
546 class_constraint
= class_constraint
.ResolveAsTypeTerminal (ec
, false);
547 if (class_constraint
== null)
554 public override GenericParameterAttributes Attributes
{
555 get { return attrs; }
558 public override bool HasClassConstraint
{
559 get { return class_constraint != null; }
562 public override Type ClassConstraint
{
563 get { return class_constraint_type; }
566 public override Type
[] InterfaceConstraints
{
567 get { return iface_constraint_types; }
570 public override Type EffectiveBaseClass
{
571 get { return effective_base_type; }
574 public bool IsSubclassOf (Type t
)
576 if ((class_constraint_type
!= null) &&
577 class_constraint_type
.IsSubclassOf (t
))
580 if (iface_constraint_types
== null)
583 foreach (Type iface
in iface_constraint_types
) {
584 if (TypeManager
.IsSubclassOf (iface
, t
))
591 public Location Location
{
598 /// This is used when we're implementing a generic interface method.
599 /// Each method type parameter in implementing method must have the same
600 /// constraints than the corresponding type parameter in the interface
601 /// method. To do that, we're called on each of the implementing method's
604 public bool AreEqual (GenericConstraints gc
)
606 if (gc
.Attributes
!= attrs
)
609 if (HasClassConstraint
!= gc
.HasClassConstraint
)
611 if (HasClassConstraint
&& !TypeManager
.IsEqual (gc
.ClassConstraint
, ClassConstraint
))
614 int gc_icount
= gc
.InterfaceConstraints
!= null ?
615 gc
.InterfaceConstraints
.Length
: 0;
616 int icount
= InterfaceConstraints
!= null ?
617 InterfaceConstraints
.Length
: 0;
619 if (gc_icount
!= icount
)
622 for (int i
= 0; i
< gc
.InterfaceConstraints
.Length
; ++i
) {
623 Type iface
= gc
.InterfaceConstraints
[i
];
624 if (iface
.IsGenericType
)
625 iface
= iface
.GetGenericTypeDefinition ();
628 for (int ii
= 0; ii
< InterfaceConstraints
.Length
; ii
++) {
629 Type check
= InterfaceConstraints
[ii
];
630 if (check
.IsGenericType
)
631 check
= check
.GetGenericTypeDefinition ();
633 if (TypeManager
.IsEqual (iface
, check
)) {
646 public void VerifyClsCompliance (Report r
)
648 if (class_constraint_type
!= null && !AttributeTester
.IsClsCompliant (class_constraint_type
))
649 Warning_ConstrainIsNotClsCompliant (class_constraint_type
, class_constraint
.Location
, r
);
651 if (iface_constraint_types
!= null) {
652 for (int i
= 0; i
< iface_constraint_types
.Length
; ++i
) {
653 if (!AttributeTester
.IsClsCompliant (iface_constraint_types
[i
]))
654 Warning_ConstrainIsNotClsCompliant (iface_constraint_types
[i
],
655 ((TypeExpr
)iface_constraints
[i
]).Location
, r
);
660 void Warning_ConstrainIsNotClsCompliant (Type t
, Location loc
, Report Report
)
662 Report
.SymbolRelatedToPreviousError (t
);
663 Report
.Warning (3024, 1, loc
, "Constraint type `{0}' is not CLS-compliant",
664 TypeManager
.CSharpName (t
));
669 /// A type parameter from a generic type definition.
671 public class TypeParameter
: MemberCore
, IMemberContainer
673 static readonly string[] attribute_target
= new string [] { "type parameter" }
;
676 GenericConstraints gc
;
677 Constraints constraints
;
678 GenericTypeParameterBuilder type
;
679 MemberCache member_cache
;
682 public TypeParameter (DeclSpace parent
, DeclSpace decl
, string name
,
683 Constraints constraints
, Attributes attrs
, Variance variance
, Location loc
)
684 : base (parent
, new MemberName (name
, loc
), attrs
)
687 this.constraints
= constraints
;
688 this.variance
= variance
;
691 public GenericConstraints GenericConstraints
{
692 get { return gc != null ? gc : constraints; }
695 public Constraints Constraints
{
696 get { return constraints; }
699 public DeclSpace DeclSpace
{
703 public Variance Variance
{
704 get { return variance; }
712 /// This is the first method which is called during the resolving
713 /// process; we're called immediately after creating the type parameters
714 /// with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
717 /// We're either called from TypeContainer.DefineType() or from
718 /// GenericMethod.Define() (called from Method.Define()).
720 public void Define (GenericTypeParameterBuilder type
)
722 if (this.type
!= null)
723 throw new InvalidOperationException ();
726 TypeManager
.AddTypeParameter (type
, this);
729 public void ErrorInvalidVariance (IMemberContext mc
, Variance expected
)
731 // TODO: Report.SymbolRelatedToPreviousError (mc);
732 string input_variance
= Variance
== Variance
.Contravariant
? "contravariant" : "covariant";
733 string gtype_variance
;
735 case Variance
.Contravariant
: gtype_variance
= "contravariantly"; break;
736 case Variance
.Covariant
: gtype_variance
= "covariantly"; break;
737 default: gtype_variance
= "invariantly"; break;
740 Delegate d
= mc
as Delegate
;
741 string parameters
= d
!= null ? d
.Parameters
.GetSignatureForError () : "";
743 Report
.Error (1961, Location
,
744 "The {2} type parameter `{0}' must be {3} valid on `{1}{4}'",
745 GetSignatureForError (), mc
.GetSignatureForError (), input_variance
, gtype_variance
, parameters
);
749 /// This is the second method which is called during the resolving
750 /// process - in case of class type parameters, we're called from
751 /// TypeContainer.ResolveType() - after it resolved the class'es
752 /// base class and interfaces. For method type parameters, we're
753 /// called immediately after Define().
755 /// We're just resolving the constraints into expressions here, we
756 /// don't resolve them into actual types.
758 /// Note that in the special case of partial generic classes, we may be
759 /// called _before_ Define() and we may also be called multiple types.
761 public bool Resolve (DeclSpace ds
)
763 if (constraints
!= null) {
764 if (!constraints
.Resolve (ds
, this, Report
)) {
774 /// This is the third method which is called during the resolving
775 /// process. We're called immediately after calling DefineConstraints()
776 /// on all of the current class'es type parameters.
778 /// Our job is to resolve the constraints to actual types.
780 /// Note that we may have circular dependencies on type parameters - this
781 /// is why Resolve() and ResolveType() are separate.
783 public bool ResolveType (IMemberContext ec
)
785 if (constraints
!= null) {
786 if (!constraints
.ResolveTypes (ec
, Report
)) {
796 /// This is the fourth and last method which is called during the resolving
797 /// process. We're called after everything is fully resolved and actually
798 /// register the constraints with SRE and the TypeManager.
800 public bool DefineType (IMemberContext ec
)
802 return DefineType (ec
, null, null, false);
806 /// This is the fith and last method which is called during the resolving
807 /// process. We're called after everything is fully resolved and actually
808 /// register the constraints with SRE and the TypeManager.
810 /// The `builder', `implementing' and `is_override' arguments are only
811 /// applicable to method type parameters.
813 public bool DefineType (IMemberContext ec
, MethodBuilder builder
,
814 MethodInfo implementing
, bool is_override
)
816 if (!ResolveType (ec
))
819 if (implementing
!= null) {
820 if (is_override
&& (constraints
!= null)) {
821 Report
.Error (460, Location
,
822 "`{0}': Cannot specify constraints for overrides or explicit interface implementation methods",
823 TypeManager
.CSharpSignature (builder
));
827 MethodBase mb
= TypeManager
.DropGenericMethodArguments (implementing
);
829 int pos
= type
.GenericParameterPosition
;
830 Type mparam
= mb
.GetGenericArguments () [pos
];
831 GenericConstraints temp_gc
= ReflectionConstraints
.GetConstraints (mparam
);
834 gc
= new InflatedConstraints (temp_gc
, implementing
.DeclaringType
);
835 else if (constraints
!= null)
836 gc
= new InflatedConstraints (constraints
, implementing
.DeclaringType
);
839 if (constraints
!= null) {
842 else if (!constraints
.AreEqual (gc
))
845 if (!is_override
&& (temp_gc
!= null))
850 Report
.SymbolRelatedToPreviousError (implementing
);
853 425, Location
, "The constraints for type " +
854 "parameter `{0}' of method `{1}' must match " +
855 "the constraints for type parameter `{2}' " +
856 "of interface method `{3}'. Consider using " +
857 "an explicit interface implementation instead",
858 Name
, TypeManager
.CSharpSignature (builder
),
859 TypeManager
.CSharpName (mparam
), TypeManager
.CSharpSignature (mb
));
862 } else if (DeclSpace
is CompilerGeneratedClass
) {
863 TypeParameter
[] tparams
= DeclSpace
.TypeParameters
;
864 Type
[] types
= new Type
[tparams
.Length
];
865 for (int i
= 0; i
< tparams
.Length
; i
++)
866 types
[i
] = tparams
[i
].Type
;
868 if (constraints
!= null)
869 gc
= new InflatedConstraints (constraints
, types
);
871 gc
= (GenericConstraints
) constraints
;
874 SetConstraints (type
);
878 public static TypeParameter
FindTypeParameter (TypeParameter
[] tparams
, string name
)
880 foreach (var tp
in tparams
) {
888 public void SetConstraints (GenericTypeParameterBuilder type
)
890 GenericParameterAttributes attr
= GenericParameterAttributes
.None
;
891 if (variance
== Variance
.Contravariant
)
892 attr
|= GenericParameterAttributes
.Contravariant
;
893 else if (variance
== Variance
.Covariant
)
894 attr
|= GenericParameterAttributes
.Covariant
;
897 if (gc
.HasClassConstraint
|| gc
.HasValueTypeConstraint
)
898 type
.SetBaseTypeConstraint (gc
.EffectiveBaseClass
);
900 attr
|= gc
.Attributes
;
901 type
.SetInterfaceConstraints (gc
.InterfaceConstraints
);
902 TypeManager
.RegisterBuilder (type
, gc
.InterfaceConstraints
);
905 type
.SetGenericParameterAttributes (attr
);
909 /// This is called for each part of a partial generic type definition.
911 /// If `new_constraints' is not null and we don't already have constraints,
912 /// they become our constraints. If we already have constraints, we must
913 /// check that they're the same.
916 public bool UpdateConstraints (MemberCore ec
, Constraints new_constraints
)
919 throw new InvalidOperationException ();
921 if (new_constraints
== null)
924 if (!new_constraints
.Resolve (ec
, this, Report
))
926 if (!new_constraints
.ResolveTypes (ec
, Report
))
929 if (constraints
!= null)
930 return constraints
.AreEqual (new_constraints
);
932 constraints
= new_constraints
;
936 public override void Emit ()
938 if (OptAttributes
!= null)
939 OptAttributes
.Emit ();
944 public override string DocCommentHeader
{
946 throw new InvalidOperationException (
947 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
955 public override bool Define ()
960 public override void ApplyAttributeBuilder (Attribute a
, CustomAttributeBuilder cb
, PredefinedAttributes pa
)
962 type
.SetCustomAttribute (cb
);
965 public override AttributeTargets AttributeTargets
{
967 return AttributeTargets
.GenericParameter
;
971 public override string[] ValidAttributeTargets
{
973 return attribute_target
;
981 string IMemberContainer
.Name
{
985 MemberCache IMemberContainer
.BaseCache
{
990 if (gc
.EffectiveBaseClass
.BaseType
== null)
993 return TypeManager
.LookupMemberCache (gc
.EffectiveBaseClass
.BaseType
);
997 bool IMemberContainer
.IsInterface
{
998 get { return false; }
1001 MemberList IMemberContainer
.GetMembers (MemberTypes mt
, BindingFlags bf
)
1003 throw new NotSupportedException ();
1006 public MemberCache MemberCache
{
1008 if (member_cache
!= null)
1009 return member_cache
;
1014 Type
[] ifaces
= TypeManager
.ExpandInterfaces (gc
.InterfaceConstraints
);
1015 member_cache
= new MemberCache (this, gc
.EffectiveBaseClass
, ifaces
);
1017 return member_cache
;
1021 public MemberList
FindMembers (MemberTypes mt
, BindingFlags bf
,
1022 MemberFilter filter
, object criteria
)
1025 return MemberList
.Empty
;
1027 var members
= new List
<MemberInfo
> ();
1029 if (gc
.HasClassConstraint
) {
1030 MemberList list
= TypeManager
.FindMembers (
1031 gc
.ClassConstraint
, mt
, bf
, filter
, criteria
);
1033 members
.AddRange (list
);
1036 Type
[] ifaces
= TypeManager
.ExpandInterfaces (gc
.InterfaceConstraints
);
1037 foreach (Type t
in ifaces
) {
1038 MemberList list
= TypeManager
.FindMembers (
1039 t
, mt
, bf
, filter
, criteria
);
1041 members
.AddRange (list
);
1044 return new MemberList (members
);
1047 public bool IsSubclassOf (Type t
)
1049 if (type
.Equals (t
))
1052 if (constraints
!= null)
1053 return constraints
.IsSubclassOf (t
);
1058 public void InflateConstraints (Type declaring
)
1060 if (constraints
!= null)
1061 gc
= new InflatedConstraints (constraints
, declaring
);
1064 public override bool IsClsComplianceRequired ()
1069 protected class InflatedConstraints
: GenericConstraints
1071 GenericConstraints gc
;
1073 Type class_constraint
;
1074 Type
[] iface_constraints
;
1077 public InflatedConstraints (GenericConstraints gc
, Type declaring
)
1078 : this (gc
, TypeManager
.GetTypeArguments (declaring
))
1081 public InflatedConstraints (GenericConstraints gc
, Type
[] dargs
)
1086 var list
= new List
<Type
> ();
1087 if (gc
.HasClassConstraint
)
1088 list
.Add (inflate (gc
.ClassConstraint
));
1089 foreach (Type iface
in gc
.InterfaceConstraints
)
1090 list
.Add (inflate (iface
));
1092 bool has_class_constr
= false;
1093 if (list
.Count
> 0) {
1094 Type first
= (Type
) list
[0];
1095 has_class_constr
= !first
.IsGenericParameter
&& !first
.IsInterface
;
1098 if ((list
.Count
> 0) && has_class_constr
) {
1099 class_constraint
= (Type
) list
[0];
1100 iface_constraints
= new Type
[list
.Count
- 1];
1101 list
.CopyTo (1, iface_constraints
, 0, list
.Count
- 1);
1103 iface_constraints
= new Type
[list
.Count
];
1104 list
.CopyTo (iface_constraints
, 0);
1107 if (HasValueTypeConstraint
)
1108 base_type
= TypeManager
.value_type
;
1109 else if (class_constraint
!= null)
1110 base_type
= class_constraint
;
1112 base_type
= TypeManager
.object_type
;
1115 Type
inflate (Type t
)
1119 if (t
.IsGenericParameter
)
1120 return t
.GenericParameterPosition
< dargs
.Length
? dargs
[t
.GenericParameterPosition
] : t
;
1121 if (t
.IsGenericType
) {
1122 Type
[] args
= t
.GetGenericArguments ();
1123 Type
[] inflated
= new Type
[args
.Length
];
1125 for (int i
= 0; i
< args
.Length
; i
++)
1126 inflated
[i
] = inflate (args
[i
]);
1128 t
= t
.GetGenericTypeDefinition ();
1129 t
= t
.MakeGenericType (inflated
);
1135 public override GenericParameterAttributes Attributes
{
1136 get { return gc.Attributes; }
1139 public override Type ClassConstraint
{
1140 get { return class_constraint; }
1143 public override Type EffectiveBaseClass
{
1144 get { return base_type; }
1147 public override Type
[] InterfaceConstraints
{
1148 get { return iface_constraints; }
1154 /// A TypeExpr which already resolved to a type parameter.
1156 public class TypeParameterExpr
: TypeExpr
{
1158 public TypeParameterExpr (TypeParameter type_parameter
, Location loc
)
1160 this.type
= type_parameter
.Type
;
1161 this.eclass
= ExprClass
.TypeParameter
;
1165 protected override TypeExpr
DoResolveAsTypeStep (IMemberContext ec
)
1167 throw new NotSupportedException ();
1170 public override FullNamedExpression
ResolveAsTypeStep (IMemberContext ec
, bool silent
)
1175 public override bool IsInterface
{
1176 get { return false; }
1179 public override bool CheckAccessLevel (IMemberContext ds
)
1186 // Tracks the type arguments when instantiating a generic type. It's used
1187 // by both type arguments and type parameters
1189 public class TypeArguments
{
1190 List
<FullNamedExpression
> args
;
1193 public TypeArguments ()
1195 args
= new List
<FullNamedExpression
> ();
1198 public TypeArguments (params FullNamedExpression
[] types
)
1200 this.args
= new List
<FullNamedExpression
> (types
);
1203 public void Add (FullNamedExpression type
)
1208 public void Add (TypeArguments new_args
)
1210 args
.AddRange (new_args
.args
);
1213 // TODO: Kill this monster
1214 public TypeParameterName
[] GetDeclarations ()
1216 return args
.ConvertAll (i
=> (TypeParameterName
) i
).ToArray ();
1220 /// We may only be used after Resolve() is called and return the fully
1223 public Type
[] Arguments
{
1235 public string GetSignatureForError()
1237 StringBuilder sb
= new StringBuilder();
1238 for (int i
= 0; i
< Count
; ++i
)
1240 Expression expr
= (Expression
)args
[i
];
1241 sb
.Append(expr
.GetSignatureForError());
1245 return sb
.ToString();
1249 /// Resolve the type arguments.
1251 public bool Resolve (IMemberContext ec
)
1254 return atypes
.Length
!= 0;
1256 int count
= args
.Count
;
1259 atypes
= new Type
[count
];
1261 for (int i
= 0; i
< count
; i
++){
1262 TypeExpr te
= ((FullNamedExpression
) args
[i
]).ResolveAsTypeTerminal (ec
, false);
1268 atypes
[i
] = te
.Type
;
1270 if (te
.Type
.IsSealed
&& te
.Type
.IsAbstract
) {
1271 ec
.Compiler
.Report
.Error (718, te
.Location
, "`{0}': static classes cannot be used as generic arguments",
1272 te
.GetSignatureForError ());
1276 if (te
.Type
.IsPointer
|| TypeManager
.IsSpecialType (te
.Type
)) {
1277 ec
.Compiler
.Report
.Error (306, te
.Location
,
1278 "The type `{0}' may not be used as a type argument",
1279 te
.GetSignatureForError ());
1285 atypes
= Type
.EmptyTypes
;
1290 public TypeArguments
Clone ()
1292 TypeArguments copy
= new TypeArguments ();
1293 foreach (var ta
in args
)
1300 public class TypeParameterName
: SimpleName
1302 Attributes attributes
;
1305 public TypeParameterName (string name
, Attributes attrs
, Location loc
)
1306 : this (name
, attrs
, Variance
.None
, loc
)
1310 public TypeParameterName (string name
, Attributes attrs
, Variance variance
, Location loc
)
1314 this.variance
= variance
;
1317 public Attributes OptAttributes
{
1323 public Variance Variance
{
1331 /// A reference expression to generic type
1333 class GenericTypeExpr
: TypeExpr
1336 Type
[] gen_params
; // TODO: Waiting for constrains check cleanup
1340 // Should be carefully used only with defined generic containers. Type parameters
1341 // can be used as type arguments in this case.
1343 // TODO: This could be GenericTypeExpr specialization
1345 public GenericTypeExpr (DeclSpace gType
, Location l
)
1347 open_type
= gType
.TypeBuilder
.GetGenericTypeDefinition ();
1349 args
= new TypeArguments ();
1350 foreach (TypeParameter type_param
in gType
.TypeParameters
)
1351 args
.Add (new TypeParameterExpr (type_param
, l
));
1357 /// Instantiate the generic type `t' with the type arguments `args'.
1358 /// Use this constructor if you already know the fully resolved
1361 public GenericTypeExpr (Type t
, TypeArguments args
, Location l
)
1363 open_type
= t
.GetGenericTypeDefinition ();
1369 public TypeArguments TypeArguments
{
1370 get { return args; }
1373 public override string GetSignatureForError ()
1375 return TypeManager
.CSharpName (type
);
1378 protected override TypeExpr
DoResolveAsTypeStep (IMemberContext ec
)
1380 eclass
= ExprClass
.Type
;
1382 if (!args
.Resolve (ec
))
1385 gen_params
= open_type
.GetGenericArguments ();
1386 Type
[] atypes
= args
.Arguments
;
1388 if (atypes
.Length
!= gen_params
.Length
) {
1389 Namespace
.Error_InvalidNumberOfTypeArguments (ec
.Compiler
.Report
, open_type
, loc
);
1394 // Now bind the parameters
1396 type
= open_type
.MakeGenericType (atypes
);
1401 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1402 /// after fully resolving the constructed type.
1404 public bool CheckConstraints (IMemberContext ec
)
1406 return ConstraintChecker
.CheckConstraints (ec
, open_type
, gen_params
, args
.Arguments
, loc
);
1409 public override bool CheckAccessLevel (IMemberContext mc
)
1411 return mc
.CurrentTypeDefinition
.CheckAccessLevel (open_type
);
1414 public bool HasDynamicArguments ()
1416 return HasDynamicArguments (args
.Arguments
);
1419 static bool HasDynamicArguments (Type
[] args
)
1421 foreach (var item
in args
)
1423 if (TypeManager
.IsGenericType (item
))
1424 return HasDynamicArguments (TypeManager
.GetTypeArguments (item
));
1426 if (TypeManager
.IsDynamicType (item
))
1433 public override bool IsClass
{
1434 get { return open_type.IsClass; }
1437 public override bool IsValueType
{
1438 get { return TypeManager.IsStruct (open_type); }
1441 public override bool IsInterface
{
1442 get { return open_type.IsInterface; }
1445 public override bool IsSealed
{
1446 get { return open_type.IsSealed; }
1449 public override bool Equals (object obj
)
1451 GenericTypeExpr cobj
= obj
as GenericTypeExpr
;
1455 if ((type
== null) || (cobj
.type
== null))
1458 return type
== cobj
.type
;
1461 public override int GetHashCode ()
1463 return base.GetHashCode ();
1467 public abstract class ConstraintChecker
1469 protected readonly Type
[] gen_params
;
1470 protected readonly Type
[] atypes
;
1471 protected readonly Location loc
;
1472 protected Report Report
;
1474 protected ConstraintChecker (Type
[] gen_params
, Type
[] atypes
, Location loc
, Report r
)
1476 this.gen_params
= gen_params
;
1477 this.atypes
= atypes
;
1483 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1484 /// after fully resolving the constructed type.
1486 public bool CheckConstraints (IMemberContext ec
)
1488 for (int i
= 0; i
< gen_params
.Length
; i
++) {
1489 if (!CheckConstraints (ec
, i
))
1496 protected bool CheckConstraints (IMemberContext ec
, int index
)
1498 Type atype
= TypeManager
.TypeToCoreType (atypes
[index
]);
1499 Type ptype
= gen_params
[index
];
1504 Expression aexpr
= new EmptyExpression (atype
);
1506 GenericConstraints gc
= TypeManager
.GetTypeParameterConstraints (ptype
);
1510 bool is_class
, is_struct
;
1511 if (atype
.IsGenericParameter
) {
1512 GenericConstraints agc
= TypeManager
.GetTypeParameterConstraints (atype
);
1514 if (agc
is Constraints
) {
1515 // FIXME: No constraints can be resolved here, we are in
1516 // completely wrong/different context. This path is hit
1517 // when resolving base type of unresolved generic type
1518 // with constraints. We are waiting with CheckConsttraints
1519 // after type-definition but not in this case
1520 if (!((Constraints
) agc
).Resolve (null, null, Report
))
1523 is_class
= agc
.IsReferenceType
;
1524 is_struct
= agc
.IsValueType
;
1526 is_class
= is_struct
= false;
1529 is_class
= TypeManager
.IsReferenceType (atype
);
1530 is_struct
= TypeManager
.IsValueType (atype
) && !TypeManager
.IsNullableType (atype
);
1534 // First, check the `class' and `struct' constraints.
1536 if (gc
.HasReferenceTypeConstraint
&& !is_class
) {
1537 Report
.Error (452, loc
, "The type `{0}' must be " +
1538 "a reference type in order to use it " +
1539 "as type parameter `{1}' in the " +
1540 "generic type or method `{2}'.",
1541 TypeManager
.CSharpName (atype
),
1542 TypeManager
.CSharpName (ptype
),
1543 GetSignatureForError ());
1545 } else if (gc
.HasValueTypeConstraint
&& !is_struct
) {
1546 Report
.Error (453, loc
, "The type `{0}' must be a " +
1547 "non-nullable value type in order to use it " +
1548 "as type parameter `{1}' in the " +
1549 "generic type or method `{2}'.",
1550 TypeManager
.CSharpName (atype
),
1551 TypeManager
.CSharpName (ptype
),
1552 GetSignatureForError ());
1557 // The class constraint comes next.
1559 if (gc
.HasClassConstraint
) {
1560 if (!CheckConstraint (ec
, ptype
, aexpr
, gc
.ClassConstraint
))
1565 // Now, check the interface constraints.
1567 if (gc
.InterfaceConstraints
!= null) {
1568 foreach (Type it
in gc
.InterfaceConstraints
) {
1569 if (!CheckConstraint (ec
, ptype
, aexpr
, it
))
1575 // Finally, check the constructor constraint.
1578 if (!gc
.HasConstructorConstraint
)
1581 if (TypeManager
.IsValueType (atype
))
1584 if (HasDefaultConstructor (atype
))
1587 Report_SymbolRelatedToPreviousError ();
1588 Report
.SymbolRelatedToPreviousError (atype
);
1589 Report
.Error (310, loc
, "The type `{0}' must have a public " +
1590 "parameterless constructor in order to use it " +
1591 "as parameter `{1}' in the generic type or " +
1593 TypeManager
.CSharpName (atype
),
1594 TypeManager
.CSharpName (ptype
),
1595 GetSignatureForError ());
1599 Type
InflateType(IMemberContext ec
, Type ctype
)
1601 Type
[] types
= TypeManager
.GetTypeArguments (ctype
);
1603 TypeArguments new_args
= new TypeArguments ();
1605 for (int i
= 0; i
< types
.Length
; i
++) {
1606 Type t
= TypeManager
.TypeToCoreType (types
[i
]);
1608 if (t
.IsGenericParameter
) {
1609 int pos
= t
.GenericParameterPosition
;
1610 if (t
.DeclaringMethod
== null && this is MethodConstraintChecker
) {
1611 Type parent
= ((MethodConstraintChecker
) this).declaring_type
;
1612 t
= parent
.GetGenericArguments ()[pos
];
1616 } else if(TypeManager
.HasGenericArguments(t
)) {
1617 t
= InflateType (ec
, t
);
1622 new_args
.Add (new TypeExpression (t
, loc
));
1625 TypeExpr ct
= new GenericTypeExpr (ctype
, new_args
, loc
);
1626 if (ct
.ResolveAsTypeStep (ec
, false) == null)
1632 protected bool CheckConstraint (IMemberContext ec
, Type ptype
, Expression expr
,
1636 // All this is needed because we don't have
1637 // real inflated type hierarchy
1639 if (TypeManager
.HasGenericArguments (ctype
)) {
1640 ctype
= InflateType (ec
, ctype
);
1644 } else if (ctype
.IsGenericParameter
) {
1645 int pos
= ctype
.GenericParameterPosition
;
1646 if (ctype
.DeclaringMethod
== null) {
1650 ctype
= atypes
[pos
];
1654 if (Convert
.ImplicitStandardConversionExists (expr
, ctype
))
1657 Report_SymbolRelatedToPreviousError ();
1658 Report
.SymbolRelatedToPreviousError (expr
.Type
);
1660 if (TypeManager
.IsNullableType (expr
.Type
) && ctype
.IsInterface
) {
1661 Report
.Error (313, loc
,
1662 "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. " +
1663 "The nullable type `{0}' never satisfies interface constraint of type `{3}'",
1664 TypeManager
.CSharpName (expr
.Type
), TypeManager
.CSharpName (ptype
),
1665 GetSignatureForError (), TypeManager
.CSharpName (ctype
));
1667 Report
.Error (309, loc
,
1668 "The type `{0}' must be convertible to `{1}' in order to " +
1669 "use it as parameter `{2}' in the generic type or method `{3}'",
1670 TypeManager
.CSharpName (expr
.Type
), TypeManager
.CSharpName (ctype
),
1671 TypeManager
.CSharpName (ptype
), GetSignatureForError ());
1676 static bool HasDefaultConstructor (Type atype
)
1678 TypeParameter tparam
= TypeManager
.LookupTypeParameter (atype
);
1679 if (tparam
!= null) {
1680 if (tparam
.GenericConstraints
== null)
1683 return tparam
.GenericConstraints
.HasConstructorConstraint
||
1684 tparam
.GenericConstraints
.HasValueTypeConstraint
;
1687 if (atype
.IsAbstract
)
1691 atype
= TypeManager
.DropGenericTypeArguments (atype
);
1692 if (atype
is TypeBuilder
) {
1693 TypeContainer tc
= TypeManager
.LookupTypeContainer (atype
);
1694 if (tc
.InstanceConstructors
== null) {
1695 atype
= atype
.BaseType
;
1699 foreach (Constructor c
in tc
.InstanceConstructors
) {
1700 if ((c
.ModFlags
& Modifiers
.PUBLIC
) == 0)
1702 if ((c
.Parameters
.FixedParameters
!= null) &&
1703 (c
.Parameters
.FixedParameters
.Length
!= 0))
1705 if (c
.Parameters
.HasArglist
|| c
.Parameters
.HasParams
)
1712 MemberInfo
[] list
= TypeManager
.MemberLookup (null, null, atype
, MemberTypes
.Constructor
,
1713 BindingFlags
.Public
| BindingFlags
.Instance
| BindingFlags
.DeclaredOnly
,
1714 ConstructorInfo
.ConstructorName
, null);
1719 foreach (MethodBase mb
in list
) {
1720 AParametersCollection pd
= TypeManager
.GetParameterData (mb
);
1728 protected abstract string GetSignatureForError ();
1729 protected abstract void Report_SymbolRelatedToPreviousError ();
1731 public static bool CheckConstraints (IMemberContext ec
, MethodBase definition
,
1732 MethodBase instantiated
, Location loc
)
1734 MethodConstraintChecker checker
= new MethodConstraintChecker (
1735 definition
, instantiated
.DeclaringType
, definition
.GetGenericArguments (),
1736 instantiated
.GetGenericArguments (), loc
, ec
.Compiler
.Report
);
1738 return checker
.CheckConstraints (ec
);
1741 public static bool CheckConstraints (IMemberContext ec
, Type gt
, Type
[] gen_params
,
1742 Type
[] atypes
, Location loc
)
1744 TypeConstraintChecker checker
= new TypeConstraintChecker (
1745 gt
, gen_params
, atypes
, loc
, ec
.Compiler
.Report
);
1747 return checker
.CheckConstraints (ec
);
1750 protected class MethodConstraintChecker
: ConstraintChecker
1752 MethodBase definition
;
1753 public Type declaring_type
;
1755 public MethodConstraintChecker (MethodBase definition
, Type declaringType
, Type
[] gen_params
,
1756 Type
[] atypes
, Location loc
, Report r
)
1757 : base (gen_params
, atypes
, loc
, r
)
1759 this.declaring_type
= declaringType
;
1760 this.definition
= definition
;
1763 protected override string GetSignatureForError ()
1765 return TypeManager
.CSharpSignature (definition
);
1768 protected override void Report_SymbolRelatedToPreviousError ()
1770 Report
.SymbolRelatedToPreviousError (definition
);
1774 protected class TypeConstraintChecker
: ConstraintChecker
1778 public TypeConstraintChecker (Type gt
, Type
[] gen_params
, Type
[] atypes
,
1779 Location loc
, Report r
)
1780 : base (gen_params
, atypes
, loc
, r
)
1785 protected override string GetSignatureForError ()
1787 return TypeManager
.CSharpName (gt
);
1790 protected override void Report_SymbolRelatedToPreviousError ()
1792 Report
.SymbolRelatedToPreviousError (gt
);
1798 /// A generic method definition.
1800 public class GenericMethod
: DeclSpace
1802 FullNamedExpression return_type
;
1803 ParametersCompiled parameters
;
1805 public GenericMethod (NamespaceEntry ns
, DeclSpace parent
, MemberName name
,
1806 FullNamedExpression return_type
, ParametersCompiled parameters
)
1807 : base (ns
, parent
, name
, null)
1809 this.return_type
= return_type
;
1810 this.parameters
= parameters
;
1813 public override TypeContainer CurrentTypeDefinition
{
1815 return Parent
.CurrentTypeDefinition
;
1819 public override TypeParameter
[] CurrentTypeParameters
{
1821 return base.type_params
;
1825 public override TypeBuilder
DefineType ()
1827 throw new Exception ();
1830 public override bool Define ()
1832 for (int i
= 0; i
< TypeParameters
.Length
; i
++)
1833 if (!TypeParameters
[i
].Resolve (this))
1840 /// Define and resolve the type parameters.
1841 /// We're called from Method.Define().
1843 public bool Define (MethodOrOperator m
)
1845 TypeParameterName
[] names
= MemberName
.TypeArguments
.GetDeclarations ();
1846 string[] snames
= new string [names
.Length
];
1847 for (int i
= 0; i
< names
.Length
; i
++) {
1848 string type_argument_name
= names
[i
].Name
;
1849 int idx
= parameters
.GetParameterIndexByName (type_argument_name
);
1853 b
= new Block (null);
1855 b
.Error_AlreadyDeclaredTypeParameter (Report
, parameters
[i
].Location
,
1856 type_argument_name
, "method parameter");
1859 snames
[i
] = type_argument_name
;
1862 GenericTypeParameterBuilder
[] gen_params
= m
.MethodBuilder
.DefineGenericParameters (snames
);
1863 for (int i
= 0; i
< TypeParameters
.Length
; i
++)
1864 TypeParameters
[i
].Define (gen_params
[i
]);
1869 for (int i
= 0; i
< TypeParameters
.Length
; i
++) {
1870 if (!TypeParameters
[i
].ResolveType (this))
1878 /// We're called from MethodData.Define() after creating the MethodBuilder.
1880 public bool DefineType (IMemberContext ec
, MethodBuilder mb
,
1881 MethodInfo implementing
, bool is_override
)
1883 for (int i
= 0; i
< TypeParameters
.Length
; i
++)
1884 if (!TypeParameters
[i
].DefineType (
1885 ec
, mb
, implementing
, is_override
))
1888 bool ok
= parameters
.Resolve (ec
);
1890 if ((return_type
!= null) && (return_type
.ResolveAsTypeTerminal (ec
, false) == null))
1896 public void EmitAttributes ()
1898 for (int i
= 0; i
< TypeParameters
.Length
; i
++)
1899 TypeParameters
[i
].Emit ();
1901 if (OptAttributes
!= null)
1902 OptAttributes
.Emit ();
1905 public override MemberList
FindMembers (MemberTypes mt
, BindingFlags bf
,
1906 MemberFilter filter
, object criteria
)
1908 throw new Exception ();
1911 public override string GetSignatureForError ()
1913 return base.GetSignatureForError () + parameters
.GetSignatureForError ();
1916 public override MemberCache MemberCache
{
1922 public override AttributeTargets AttributeTargets
{
1924 return AttributeTargets
.Method
| AttributeTargets
.ReturnValue
;
1928 public override string DocCommentHeader
{
1929 get { return "M:"; }
1932 public new void VerifyClsCompliance ()
1934 foreach (TypeParameter tp
in TypeParameters
) {
1935 if (tp
.Constraints
== null)
1938 tp
.Constraints
.VerifyClsCompliance (Report
);
1943 partial class TypeManager
1945 public static TypeContainer
LookupGenericTypeContainer (Type t
)
1947 t
= DropGenericTypeArguments (t
);
1948 return LookupTypeContainer (t
);
1951 public static Variance
GetTypeParameterVariance (Type type
)
1953 TypeParameter tparam
= LookupTypeParameter (type
);
1955 return tparam
.Variance
;
1957 switch (type
.GenericParameterAttributes
& GenericParameterAttributes
.VarianceMask
) {
1958 case GenericParameterAttributes
.Covariant
:
1959 return Variance
.Covariant
;
1960 case GenericParameterAttributes
.Contravariant
:
1961 return Variance
.Contravariant
;
1963 return Variance
.None
;
1967 public static Variance
CheckTypeVariance (Type t
, Variance expected
, IMemberContext member
)
1969 TypeParameter tp
= LookupTypeParameter (t
);
1971 Variance v
= tp
.Variance
;
1972 if (expected
== Variance
.None
&& v
!= expected
||
1973 expected
== Variance
.Covariant
&& v
== Variance
.Contravariant
||
1974 expected
== Variance
.Contravariant
&& v
== Variance
.Covariant
)
1975 tp
.ErrorInvalidVariance (member
, expected
);
1980 if (t
.IsGenericType
) {
1981 Type
[] targs_definition
= GetTypeArguments (DropGenericTypeArguments (t
));
1982 Type
[] targs
= GetTypeArguments (t
);
1983 for (int i
= 0; i
< targs_definition
.Length
; ++i
) {
1984 Variance v
= GetTypeParameterVariance (targs_definition
[i
]);
1985 CheckTypeVariance (targs
[i
], (Variance
) ((int)v
* (int)expected
), member
);
1992 return CheckTypeVariance (GetElementType (t
), expected
, member
);
1994 return Variance
.None
;
1997 public static bool IsVariantOf (Type type1
, Type type2
)
1999 if (!type1
.IsGenericType
|| !type2
.IsGenericType
)
2002 Type generic_target_type
= DropGenericTypeArguments (type2
);
2003 if (DropGenericTypeArguments (type1
) != generic_target_type
)
2006 Type
[] t1
= GetTypeArguments (type1
);
2007 Type
[] t2
= GetTypeArguments (type2
);
2008 Type
[] targs_definition
= GetTypeArguments (generic_target_type
);
2009 for (int i
= 0; i
< targs_definition
.Length
; ++i
) {
2010 Variance v
= GetTypeParameterVariance (targs_definition
[i
]);
2011 if (v
== Variance
.None
) {
2017 if (v
== Variance
.Covariant
) {
2018 if (!Convert
.ImplicitReferenceConversionExists (new EmptyExpression (t1
[i
]), t2
[i
]))
2020 } else if (!Convert
.ImplicitReferenceConversionExists (new EmptyExpression (t2
[i
]), t1
[i
])) {
2029 /// Check whether `a' and `b' may become equal generic types.
2030 /// The algorithm to do that is a little bit complicated.
2032 public static bool MayBecomeEqualGenericTypes (Type a
, Type b
, Type
[] class_inferred
,
2033 Type
[] method_inferred
)
2035 if (a
.IsGenericParameter
) {
2037 // If a is an array of a's type, they may never
2041 b
= GetElementType (b
);
2047 // If b is a generic parameter or an actual type,
2048 // they may become equal:
2050 // class X<T,U> : I<T>, I<U>
2051 // class X<T> : I<T>, I<float>
2053 if (b
.IsGenericParameter
|| !b
.IsGenericType
) {
2054 int pos
= a
.GenericParameterPosition
;
2055 Type
[] args
= a
.DeclaringMethod
!= null ? method_inferred
: class_inferred
;
2056 if (args
[pos
] == null) {
2061 return args
[pos
] == a
;
2065 // We're now comparing a type parameter with a
2066 // generic instance. They may become equal unless
2067 // the type parameter appears anywhere in the
2068 // generic instance:
2070 // class X<T,U> : I<T>, I<X<U>>
2071 // -> error because you could instanciate it as
2074 // class X<T> : I<T>, I<X<T>> -> ok
2077 Type
[] bargs
= GetTypeArguments (b
);
2078 for (int i
= 0; i
< bargs
.Length
; i
++) {
2079 if (a
.Equals (bargs
[i
]))
2086 if (b
.IsGenericParameter
)
2087 return MayBecomeEqualGenericTypes (b
, a
, class_inferred
, method_inferred
);
2090 // At this point, neither a nor b are a type parameter.
2092 // If one of them is a generic instance, let
2093 // MayBecomeEqualGenericInstances() compare them (if the
2094 // other one is not a generic instance, they can never
2098 if (a
.IsGenericType
|| b
.IsGenericType
)
2099 return MayBecomeEqualGenericInstances (a
, b
, class_inferred
, method_inferred
);
2102 // If both of them are arrays.
2105 if (a
.IsArray
&& b
.IsArray
) {
2106 if (a
.GetArrayRank () != b
.GetArrayRank ())
2109 a
= GetElementType (a
);
2110 b
= GetElementType (b
);
2112 return MayBecomeEqualGenericTypes (a
, b
, class_inferred
, method_inferred
);
2116 // Ok, two ordinary types.
2119 return a
.Equals (b
);
2123 // Checks whether two generic instances may become equal for some
2124 // particular instantiation (26.3.1).
2126 public static bool MayBecomeEqualGenericInstances (Type a
, Type b
,
2127 Type
[] class_inferred
,
2128 Type
[] method_inferred
)
2130 if (!a
.IsGenericType
|| !b
.IsGenericType
)
2132 if (a
.GetGenericTypeDefinition () != b
.GetGenericTypeDefinition ())
2135 return MayBecomeEqualGenericInstances (
2136 GetTypeArguments (a
), GetTypeArguments (b
), class_inferred
, method_inferred
);
2139 public static bool MayBecomeEqualGenericInstances (Type
[] aargs
, Type
[] bargs
,
2140 Type
[] class_inferred
,
2141 Type
[] method_inferred
)
2143 if (aargs
.Length
!= bargs
.Length
)
2146 for (int i
= 0; i
< aargs
.Length
; i
++) {
2147 if (!MayBecomeEqualGenericTypes (aargs
[i
], bargs
[i
], class_inferred
, method_inferred
))
2155 /// Type inference. Try to infer the type arguments from `method',
2156 /// which is invoked with the arguments `arguments'. This is used
2157 /// when resolving an Invocation or a DelegateInvocation and the user
2158 /// did not explicitly specify type arguments.
2160 public static int InferTypeArguments (ResolveContext ec
, Arguments arguments
, ref MethodSpec method
)
2162 ATypeInference ti
= ATypeInference
.CreateInstance (arguments
);
2163 Type
[] i_args
= ti
.InferMethodArguments (ec
, method
);
2165 return ti
.InferenceScore
;
2167 if (i_args
.Length
== 0)
2170 method
= method
.Inflate (i_args
);
2175 public static bool InferTypeArguments (ResolveContext ec, AParametersCollection param, ref MethodBase method)
2177 if (!TypeManager.IsGenericMethod (method))
2180 ATypeInference ti = ATypeInference.CreateInstance (DelegateCreation.CreateDelegateMethodArguments (param, Location.Null));
2181 Type[] i_args = ti.InferDelegateArguments (ec, method);
2185 method = ((MethodInfo) method).MakeGenericMethod (i_args);
2191 abstract class ATypeInference
2193 protected readonly Arguments arguments
;
2194 protected readonly int arg_count
;
2196 protected ATypeInference (Arguments arguments
)
2198 this.arguments
= arguments
;
2199 if (arguments
!= null)
2200 arg_count
= arguments
.Count
;
2203 public static ATypeInference
CreateInstance (Arguments arguments
)
2205 return new TypeInference (arguments
);
2208 public virtual int InferenceScore
{
2210 return int.MaxValue
;
2214 public abstract Type
[] InferMethodArguments (ResolveContext ec
, MethodSpec method
);
2215 // public abstract Type[] InferDelegateArguments (ResolveContext ec, MethodBase method);
2219 // Implements C# type inference
2221 class TypeInference
: ATypeInference
2224 // Tracks successful rate of type inference
2226 int score
= int.MaxValue
;
2228 public TypeInference (Arguments arguments
)
2233 public override int InferenceScore
{
2240 public override Type[] InferDelegateArguments (ResolveContext ec, MethodBase method)
2242 AParametersCollection pd = TypeManager.GetParameterData (method);
2243 if (arg_count != pd.Count)
2246 Type[] d_gargs = method.GetGenericArguments ();
2247 TypeInferenceContext context = new TypeInferenceContext (d_gargs);
2249 // A lower-bound inference is made from each argument type Uj of D
2250 // to the corresponding parameter type Tj of M
2251 for (int i = 0; i < arg_count; ++i) {
2252 Type t = pd.Types [i];
2253 if (!t.IsGenericParameter)
2256 context.LowerBoundInference (arguments [i].Expr.Type, t);
2259 if (!context.FixAllTypes (ec))
2262 return context.InferredTypeArguments;
2265 public override Type
[] InferMethodArguments (ResolveContext ec
, MethodSpec method
)
2267 var method_generic_args
= method
.GetGenericArguments ();
2268 TypeInferenceContext context
= new TypeInferenceContext (method_generic_args
);
2269 if (!context
.UnfixedVariableExists
)
2270 return Type
.EmptyTypes
;
2272 AParametersCollection pd
= method
.Parameters
;
2273 if (!InferInPhases (ec
, context
, pd
))
2276 return context
.InferredTypeArguments
;
2280 // Implements method type arguments inference
2282 bool InferInPhases (ResolveContext ec
, TypeInferenceContext tic
, AParametersCollection methodParameters
)
2284 int params_arguments_start
;
2285 if (methodParameters
.HasParams
) {
2286 params_arguments_start
= methodParameters
.Count
- 1;
2288 params_arguments_start
= arg_count
;
2291 Type
[] ptypes
= methodParameters
.Types
;
2294 // The first inference phase
2296 Type method_parameter
= null;
2297 for (int i
= 0; i
< arg_count
; i
++) {
2298 Argument a
= arguments
[i
];
2302 if (i
< params_arguments_start
) {
2303 method_parameter
= methodParameters
.Types
[i
];
2304 } else if (i
== params_arguments_start
) {
2305 if (arg_count
== params_arguments_start
+ 1 && TypeManager
.HasElementType (a
.Type
))
2306 method_parameter
= methodParameters
.Types
[params_arguments_start
];
2308 method_parameter
= TypeManager
.GetElementType (methodParameters
.Types
[params_arguments_start
]);
2310 ptypes
= (Type
[]) ptypes
.Clone ();
2311 ptypes
[i
] = method_parameter
;
2315 // When a lambda expression, an anonymous method
2316 // is used an explicit argument type inference takes a place
2318 AnonymousMethodExpression am
= a
.Expr
as AnonymousMethodExpression
;
2320 if (am
.ExplicitTypeInference (ec
, tic
, method_parameter
))
2326 score
-= tic
.ExactInference (a
.Type
, method_parameter
);
2330 if (a
.Expr
.Type
== TypeManager
.null_type
)
2333 if (TypeManager
.IsValueType (method_parameter
)) {
2334 score
-= tic
.LowerBoundInference (a
.Type
, method_parameter
);
2339 // Otherwise an output type inference is made
2341 score
-= tic
.OutputTypeInference (ec
, a
.Expr
, method_parameter
);
2345 // Part of the second phase but because it happens only once
2346 // we don't need to call it in cycle
2348 bool fixed_any
= false;
2349 if (!tic
.FixIndependentTypeArguments (ec
, ptypes
, ref fixed_any
))
2352 return DoSecondPhase (ec
, tic
, ptypes
, !fixed_any
);
2355 bool DoSecondPhase (ResolveContext ec
, TypeInferenceContext tic
, Type
[] methodParameters
, bool fixDependent
)
2357 bool fixed_any
= false;
2358 if (fixDependent
&& !tic
.FixDependentTypes (ec
, ref fixed_any
))
2361 // If no further unfixed type variables exist, type inference succeeds
2362 if (!tic
.UnfixedVariableExists
)
2365 if (!fixed_any
&& fixDependent
)
2368 // For all arguments where the corresponding argument output types
2369 // contain unfixed type variables but the input types do not,
2370 // an output type inference is made
2371 for (int i
= 0; i
< arg_count
; i
++) {
2373 // Align params arguments
2374 Type t_i
= methodParameters
[i
>= methodParameters
.Length
? methodParameters
.Length
- 1: i
];
2376 if (!TypeManager
.IsDelegateType (t_i
)) {
2377 if (TypeManager
.DropGenericTypeArguments (t_i
) != TypeManager
.expression_type
)
2380 t_i
= t_i
.GetGenericArguments () [0];
2383 var mi
= Delegate
.GetInvokeMethod (ec
.Compiler
, t_i
, t_i
);
2384 Type rtype
= mi
.ReturnType
;
2387 // Blablabla, because reflection does not work with dynamic types
2388 // Type[] g_args = t_i.GetGenericArguments ();
2389 // rtype = g_args[rtype.GenericParameterPosition];
2392 if (tic
.IsReturnTypeNonDependent (ec
, mi
, rtype
))
2393 score
-= tic
.OutputTypeInference (ec
, arguments
[i
].Expr
, t_i
);
2397 return DoSecondPhase (ec
, tic
, methodParameters
, true);
2401 public class TypeInferenceContext
2412 public readonly Type Type
;
2413 public readonly BoundKind Kind
;
2415 public BoundInfo (Type type
, BoundKind kind
)
2421 public override int GetHashCode ()
2423 return Type
.GetHashCode ();
2426 public override bool Equals (object obj
)
2428 BoundInfo a
= (BoundInfo
) obj
;
2429 return Type
== a
.Type
&& Kind
== a
.Kind
;
2433 readonly Type
[] unfixed_types
;
2434 readonly Type
[] fixed_types
;
2435 readonly List
<BoundInfo
>[] bounds
;
2438 public TypeInferenceContext (Type
[] typeArguments
)
2440 if (typeArguments
.Length
== 0)
2441 throw new ArgumentException ("Empty generic arguments");
2443 fixed_types
= new Type
[typeArguments
.Length
];
2444 for (int i
= 0; i
< typeArguments
.Length
; ++i
) {
2445 if (typeArguments
[i
].IsGenericParameter
) {
2446 if (bounds
== null) {
2447 bounds
= new List
<BoundInfo
> [typeArguments
.Length
];
2448 unfixed_types
= new Type
[typeArguments
.Length
];
2450 unfixed_types
[i
] = typeArguments
[i
];
2452 fixed_types
[i
] = typeArguments
[i
];
2458 // Used together with AddCommonTypeBound fo implement
2459 // 7.4.2.13 Finding the best common type of a set of expressions
2461 public TypeInferenceContext ()
2463 fixed_types
= new Type
[1];
2464 unfixed_types
= new Type
[1];
2465 unfixed_types
[0] = InternalType
.Arglist
; // it can be any internal type
2466 bounds
= new List
<BoundInfo
> [1];
2469 public Type
[] InferredTypeArguments
{
2475 public void AddCommonTypeBound (Type type
)
2477 AddToBounds (new BoundInfo (type
, BoundKind
.Lower
), 0);
2480 void AddToBounds (BoundInfo bound
, int index
)
2483 // Some types cannot be used as type arguments
2485 if (bound
.Type
== TypeManager
.void_type
|| bound
.Type
.IsPointer
)
2488 var a
= bounds
[index
];
2490 a
= new List
<BoundInfo
> ();
2493 if (a
.Contains (bound
))
2498 // SPEC: does not cover type inference using constraints
2500 //if (TypeManager.IsGenericParameter (t)) {
2501 // GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
2502 // if (constraints != null) {
2503 // //if (constraints.EffectiveBaseClass != null)
2504 // // t = constraints.EffectiveBaseClass;
2510 bool AllTypesAreFixed (Type
[] types
)
2512 foreach (Type t
in types
) {
2513 if (t
.IsGenericParameter
) {
2519 if (t
.IsGenericType
)
2520 return AllTypesAreFixed (t
.GetGenericArguments ());
2527 // 26.3.3.8 Exact Inference
2529 public int ExactInference (Type u
, Type v
)
2531 // If V is an array type
2536 if (u
.GetArrayRank () != v
.GetArrayRank ())
2539 return ExactInference (TypeManager
.GetElementType (u
), TypeManager
.GetElementType (v
));
2542 // If V is constructed type and U is constructed type
2543 if (v
.IsGenericType
&& !v
.IsGenericTypeDefinition
) {
2544 if (!u
.IsGenericType
)
2547 Type
[] ga_u
= u
.GetGenericArguments ();
2548 Type
[] ga_v
= v
.GetGenericArguments ();
2549 if (ga_u
.Length
!= ga_v
.Length
)
2553 for (int i
= 0; i
< ga_u
.Length
; ++i
)
2554 score
+= ExactInference (ga_u
[i
], ga_v
[i
]);
2556 return score
> 0 ? 1 : 0;
2559 // If V is one of the unfixed type arguments
2560 int pos
= IsUnfixed (v
);
2564 AddToBounds (new BoundInfo (u
, BoundKind
.Exact
), pos
);
2568 public bool FixAllTypes (ResolveContext ec
)
2570 for (int i
= 0; i
< unfixed_types
.Length
; ++i
) {
2571 if (!FixType (ec
, i
))
2578 // All unfixed type variables Xi are fixed for which all of the following hold:
2579 // a, There is at least one type variable Xj that depends on Xi
2580 // b, Xi has a non-empty set of bounds
2582 public bool FixDependentTypes (ResolveContext ec
, ref bool fixed_any
)
2584 for (int i
= 0; i
< unfixed_types
.Length
; ++i
) {
2585 if (unfixed_types
[i
] == null)
2588 if (bounds
[i
] == null)
2591 if (!FixType (ec
, i
))
2601 // All unfixed type variables Xi which depend on no Xj are fixed
2603 public bool FixIndependentTypeArguments (ResolveContext ec
, Type
[] methodParameters
, ref bool fixed_any
)
2605 var types_to_fix
= new List
<Type
> (unfixed_types
);
2606 for (int i
= 0; i
< methodParameters
.Length
; ++i
) {
2607 Type t
= methodParameters
[i
];
2609 if (!TypeManager
.IsDelegateType (t
)) {
2610 if (TypeManager
.DropGenericTypeArguments (t
) != TypeManager
.expression_type
)
2613 t
= t
.GetGenericArguments () [0];
2616 if (t
.IsGenericParameter
)
2619 var invoke
= Delegate
.GetInvokeMethod (ec
.Compiler
, t
, t
);
2620 Type rtype
= invoke
.ReturnType
;
2621 if (!rtype
.IsGenericParameter
&& !rtype
.IsGenericType
)
2625 // Blablabla, because reflection does not work with dynamic types
2626 // if (rtype.IsGenericParameter) {
2627 // Type [] g_args = t.GetGenericArguments ();
2628 // rtype = g_args [rtype.GenericParameterPosition];
2631 // Remove dependent types, they cannot be fixed yet
2632 RemoveDependentTypes (types_to_fix
, rtype
);
2635 foreach (Type t
in types_to_fix
) {
2639 int idx
= IsUnfixed (t
);
2640 if (idx
>= 0 && !FixType (ec
, idx
)) {
2645 fixed_any
= types_to_fix
.Count
> 0;
2652 public bool FixType (ResolveContext ec
, int i
)
2654 // It's already fixed
2655 if (unfixed_types
[i
] == null)
2656 throw new InternalErrorException ("Type argument has been already fixed");
2661 var candidates
= bounds
[i
];
2662 if (candidates
== null)
2665 if (candidates
.Count
== 1) {
2666 unfixed_types
[i
] = null;
2667 Type t
= candidates
[0].Type
;
2668 if (t
== TypeManager
.null_type
)
2671 fixed_types
[i
] = t
;
2676 // Determines a unique type from which there is
2677 // a standard implicit conversion to all the other
2680 Type best_candidate
= null;
2682 int candidates_count
= candidates
.Count
;
2683 for (int ci
= 0; ci
< candidates_count
; ++ci
) {
2684 BoundInfo bound
= (BoundInfo
)candidates
[ci
];
2685 for (cii
= 0; cii
< candidates_count
; ++cii
) {
2689 BoundInfo cbound
= (BoundInfo
) candidates
[cii
];
2691 // Same type parameters with different bounds
2692 if (cbound
.Type
== bound
.Type
) {
2693 if (bound
.Kind
!= BoundKind
.Exact
)
2699 if (bound
.Kind
== BoundKind
.Exact
|| cbound
.Kind
== BoundKind
.Exact
) {
2700 if (cbound
.Kind
!= BoundKind
.Exact
) {
2701 if (!Convert
.ImplicitConversionExists (ec
, new TypeExpression (cbound
.Type
, Location
.Null
), bound
.Type
)) {
2708 if (bound
.Kind
!= BoundKind
.Exact
) {
2709 if (!Convert
.ImplicitConversionExists (ec
, new TypeExpression (bound
.Type
, Location
.Null
), cbound
.Type
)) {
2720 if (bound
.Kind
== BoundKind
.Lower
) {
2721 if (!Convert
.ImplicitConversionExists (ec
, new TypeExpression (cbound
.Type
, Location
.Null
), bound
.Type
)) {
2725 if (!Convert
.ImplicitConversionExists (ec
, new TypeExpression (bound
.Type
, Location
.Null
), cbound
.Type
)) {
2731 if (cii
!= candidates_count
)
2734 if (best_candidate
!= null && best_candidate
!= bound
.Type
)
2737 best_candidate
= bound
.Type
;
2740 if (best_candidate
== null)
2743 unfixed_types
[i
] = null;
2744 fixed_types
[i
] = best_candidate
;
2749 // Uses inferred types to inflate delegate type argument
2751 public Type
InflateGenericArgument (Type parameter
)
2753 if (parameter
.IsGenericParameter
) {
2755 // Inflate method generic argument (MVAR) only
2757 if (parameter
.DeclaringMethod
== null)
2760 return fixed_types
[parameter
.GenericParameterPosition
];
2763 if (parameter
.IsGenericType
) {
2764 Type
[] parameter_targs
= parameter
.GetGenericArguments ();
2765 for (int ii
= 0; ii
< parameter_targs
.Length
; ++ii
) {
2766 parameter_targs
[ii
] = InflateGenericArgument (parameter_targs
[ii
]);
2768 return parameter
.GetGenericTypeDefinition ().MakeGenericType (parameter_targs
);
2775 // Tests whether all delegate input arguments are fixed and generic output type
2776 // requires output type inference
2778 public bool IsReturnTypeNonDependent (ResolveContext ec
, MethodSpec invoke
, Type returnType
)
2780 if (returnType
.IsGenericParameter
) {
2781 if (IsFixed (returnType
))
2783 } else if (returnType
.IsGenericType
) {
2784 if (TypeManager
.IsDelegateType (returnType
)) {
2785 invoke
= Delegate
.GetInvokeMethod (ec
.Compiler
, returnType
, returnType
);
2786 return IsReturnTypeNonDependent (ec
, invoke
, invoke
.ReturnType
);
2789 Type
[] g_args
= returnType
.GetGenericArguments ();
2791 // At least one unfixed return type has to exist
2792 if (AllTypesAreFixed (g_args
))
2798 // All generic input arguments have to be fixed
2799 AParametersCollection d_parameters
= invoke
.Parameters
;
2800 return AllTypesAreFixed (d_parameters
.Types
);
2803 bool IsFixed (Type type
)
2805 return IsUnfixed (type
) == -1;
2808 int IsUnfixed (Type type
)
2810 if (!type
.IsGenericParameter
)
2813 //return unfixed_types[type.GenericParameterPosition] != null;
2814 for (int i
= 0; i
< unfixed_types
.Length
; ++i
) {
2815 if (unfixed_types
[i
] == type
)
2823 // 26.3.3.9 Lower-bound Inference
2825 public int LowerBoundInference (Type u
, Type v
)
2827 return LowerBoundInference (u
, v
, false);
2831 // Lower-bound (false) or Upper-bound (true) inference based on inversed argument
2833 int LowerBoundInference (Type u
, Type v
, bool inversed
)
2835 // If V is one of the unfixed type arguments
2836 int pos
= IsUnfixed (v
);
2838 AddToBounds (new BoundInfo (u
, inversed
? BoundKind
.Upper
: BoundKind
.Lower
), pos
);
2842 // If U is an array type
2844 int u_dim
= u
.GetArrayRank ();
2846 Type u_i
= TypeManager
.GetElementType (u
);
2849 if (u_dim
!= v
.GetArrayRank ())
2852 v_i
= TypeManager
.GetElementType (v
);
2854 if (TypeManager
.IsValueType (u_i
))
2855 return ExactInference (u_i
, v_i
);
2857 return LowerBoundInference (u_i
, v_i
, inversed
);
2863 if (v
.IsGenericType
) {
2864 Type g_v
= v
.GetGenericTypeDefinition ();
2865 if ((g_v
!= TypeManager
.generic_ilist_type
) && (g_v
!= TypeManager
.generic_icollection_type
) &&
2866 (g_v
!= TypeManager
.generic_ienumerable_type
))
2869 v_i
= TypeManager
.TypeToCoreType (TypeManager
.GetTypeArguments (v
) [0]);
2870 if (TypeManager
.IsValueType (u_i
))
2871 return ExactInference (u_i
, v_i
);
2873 return LowerBoundInference (u_i
, v_i
);
2875 } else if (v
.IsGenericType
&& !v
.IsGenericTypeDefinition
) {
2877 // if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
2878 // such that U is identical to, inherits from (directly or indirectly),
2879 // or implements (directly or indirectly) C<U1..Uk>
2881 var u_candidates
= new List
<Type
> ();
2882 if (u
.IsGenericType
)
2883 u_candidates
.Add (u
);
2885 for (Type t
= u
.BaseType
; t
!= null; t
= t
.BaseType
) {
2886 if (t
.IsGenericType
&& !t
.IsGenericTypeDefinition
)
2887 u_candidates
.Add (t
);
2890 // TODO: Implement GetGenericInterfaces only and remove
2891 // the if from foreach
2892 u_candidates
.AddRange (TypeManager
.GetInterfaces (u
));
2894 Type open_v
= v
.GetGenericTypeDefinition ();
2895 Type
[] unique_candidate_targs
= null;
2896 Type
[] ga_v
= v
.GetGenericArguments ();
2897 foreach (Type u_candidate
in u_candidates
) {
2898 if (!u_candidate
.IsGenericType
|| u_candidate
.IsGenericTypeDefinition
)
2901 if (TypeManager
.DropGenericTypeArguments (u_candidate
) != open_v
)
2905 // The unique set of types U1..Uk means that if we have an interface I<T>,
2906 // class U : I<int>, I<long> then no type inference is made when inferring
2907 // type I<T> by applying type U because T could be int or long
2909 if (unique_candidate_targs
!= null) {
2910 Type
[] second_unique_candidate_targs
= u_candidate
.GetGenericArguments ();
2911 if (TypeManager
.IsEqual (unique_candidate_targs
, second_unique_candidate_targs
)) {
2912 unique_candidate_targs
= second_unique_candidate_targs
;
2917 // This should always cause type inference failure
2923 unique_candidate_targs
= u_candidate
.GetGenericArguments ();
2926 if (unique_candidate_targs
!= null) {
2927 Type
[] ga_open_v
= open_v
.GetGenericArguments ();
2929 for (int i
= 0; i
< unique_candidate_targs
.Length
; ++i
) {
2930 Variance variance
= TypeManager
.GetTypeParameterVariance (ga_open_v
[i
]);
2932 Type u_i
= unique_candidate_targs
[i
];
2933 if (variance
== Variance
.None
|| TypeManager
.IsValueType (u_i
)) {
2934 if (ExactInference (u_i
, ga_v
[i
]) == 0)
2937 bool upper_bound
= (variance
== Variance
.Contravariant
&& !inversed
) ||
2938 (variance
== Variance
.Covariant
&& inversed
);
2940 if (LowerBoundInference (u_i
, ga_v
[i
], upper_bound
) == 0)
2952 // 26.3.3.6 Output Type Inference
2954 public int OutputTypeInference (ResolveContext ec
, Expression e
, Type t
)
2956 // If e is a lambda or anonymous method with inferred return type
2957 AnonymousMethodExpression ame
= e
as AnonymousMethodExpression
;
2959 Type rt
= ame
.InferReturnType (ec
, this, t
);
2960 var invoke
= Delegate
.GetInvokeMethod (ec
.Compiler
, t
, t
);
2963 AParametersCollection pd
= invoke
.Parameters
;
2964 return ame
.Parameters
.Count
== pd
.Count
? 1 : 0;
2967 Type rtype
= invoke
.ReturnType
;
2969 // Blablabla, because reflection does not work with dynamic types
2970 // Type [] g_args = t.GetGenericArguments ();
2971 // rtype = g_args [rtype.GenericParameterPosition];
2973 return LowerBoundInference (rt
, rtype
) + 1;
2977 // if E is a method group and T is a delegate type or expression tree type
2978 // return type Tb with parameter types T1..Tk and return type Tb, and overload
2979 // resolution of E with the types T1..Tk yields a single method with return type U,
2980 // then a lower-bound inference is made from U for Tb.
2982 if (e
is MethodGroupExpr
) {
2983 // TODO: Or expression tree
2984 if (!TypeManager
.IsDelegateType (t
))
2987 var invoke
= Delegate
.GetInvokeMethod (ec
.Compiler
, t
, t
);
2988 Type rtype
= invoke
.ReturnType
;
2990 // Blablabla, because reflection does not work with dynamic types
2991 // Type [] g_args = t.GetGenericArguments ();
2992 // rtype = g_args [rtype.GenericParameterPosition];
2995 if (!TypeManager
.IsGenericType (rtype
))
2998 MethodGroupExpr mg
= (MethodGroupExpr
) e
;
2999 Arguments args
= DelegateCreation
.CreateDelegateMethodArguments (invoke
.Parameters
, e
.Location
);
3000 mg
= mg
.OverloadResolve (ec
, ref args
, true, e
.Location
);
3004 // TODO: What should happen when return type is of generic type ?
3005 throw new NotImplementedException ();
3006 // return LowerBoundInference (null, rtype) + 1;
3010 // if e is an expression with type U, then
3011 // a lower-bound inference is made from U for T
3013 return LowerBoundInference (e
.Type
, t
) * 2;
3016 void RemoveDependentTypes (List
<Type
> types
, Type returnType
)
3018 int idx
= IsUnfixed (returnType
);
3024 if (returnType
.IsGenericType
) {
3025 foreach (Type t
in returnType
.GetGenericArguments ()) {
3026 RemoveDependentTypes (types
, t
);
3031 public bool UnfixedVariableExists
{
3033 if (unfixed_types
== null)
3036 foreach (Type ut
in unfixed_types
)