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
12 // Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
16 using System.Collections.Generic;
21 using MetaType = IKVM.Reflection.Type;
22 using IKVM.Reflection;
23 using IKVM.Reflection.Emit;
25 using MetaType = System.Type;
26 using System.Reflection;
27 using System.Reflection.Emit;
30 namespace Mono.CSharp {
34 // Don't add or modify internal values, they are used as -/+ calculation signs
42 public enum SpecialConstraint
50 public class SpecialContraintExpr : FullNamedExpression
52 public SpecialContraintExpr (SpecialConstraint constraint, Location loc)
55 this.Constraint = constraint;
58 public SpecialConstraint Constraint { get; private set; }
60 protected override Expression DoResolve (ResolveContext rc)
62 throw new NotImplementedException ();
65 public override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext ec)
67 throw new NotImplementedException ();
72 // A set of parsed constraints for a type parameter
74 public class Constraints
76 SimpleMemberName tparam;
77 List<FullNamedExpression> constraints;
82 public Constraints (SimpleMemberName tparam, List<FullNamedExpression> constraints, Location loc)
85 this.constraints = constraints;
91 public List<FullNamedExpression> TypeExpressions {
97 public Location Location {
103 public SimpleMemberName TypeParameter {
111 public static bool CheckConflictingInheritedConstraint (TypeParameterSpec spec, TypeSpec bb, IMemberContext context, Location loc)
113 if (spec.HasSpecialClass && bb.IsStruct) {
114 context.Module.Compiler.Report.Error (455, loc,
115 "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
116 spec.Name, "class", bb.GetSignatureForError ());
121 return CheckConflictingInheritedConstraint (spec, spec.BaseType, bb, context, loc);
124 static bool CheckConflictingInheritedConstraint (TypeParameterSpec spec, TypeSpec ba, TypeSpec bb, IMemberContext context, Location loc)
129 if (TypeSpec.IsBaseClass (ba, bb, false) || TypeSpec.IsBaseClass (bb, ba, false))
132 Error_ConflictingConstraints (context, spec, ba, bb, loc);
136 public static void Error_ConflictingConstraints (IMemberContext context, TypeParameterSpec tp, TypeSpec ba, TypeSpec bb, Location loc)
138 context.Module.Compiler.Report.Error (455, loc,
139 "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
140 tp.Name, ba.GetSignatureForError (), bb.GetSignatureForError ());
143 public void CheckGenericConstraints (IMemberContext context, bool obsoleteCheck)
145 foreach (var c in constraints) {
154 ObsoleteAttribute obsolete_attr = t.GetAttributeObsolete ();
155 if (obsolete_attr != null)
156 AttributeTester.Report_ObsoleteMessage (obsolete_attr, t.GetSignatureForError (), c.Location, context.Module.Compiler.Report);
159 ConstraintChecker.Check (context, t, c.Location);
164 // Resolve the constraints types with only possible early checks, return
165 // value `false' is reserved for recursive failure
167 public bool Resolve (IMemberContext context, TypeParameter tp)
177 List<TypeParameterSpec> tparam_types = null;
178 bool iface_found = false;
180 spec.BaseType = context.Module.Compiler.BuiltinTypes.Object;
182 for (int i = 0; i < constraints.Count; ++i) {
183 var constraint = constraints[i];
185 if (constraint is SpecialContraintExpr) {
186 spec.SpecialConstraint |= ((SpecialContraintExpr) constraint).Constraint;
187 if (spec.HasSpecialStruct)
188 spec.BaseType = context.Module.Compiler.BuiltinTypes.ValueType;
190 // Set to null as it does not have a type
191 constraints[i] = null;
195 var type = constraint.ResolveAsType (context);
199 if (type.Arity > 0 && ((InflatedTypeSpec) type).HasDynamicArgument ()) {
200 context.Module.Compiler.Report.Error (1968, constraint.Location,
201 "A constraint cannot be the dynamic type `{0}'", type.GetSignatureForError ());
205 if (!context.CurrentMemberDefinition.IsAccessibleAs (type)) {
206 context.Module.Compiler.Report.SymbolRelatedToPreviousError (type);
207 context.Module.Compiler.Report.Error (703, loc,
208 "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
209 type.GetSignatureForError (), context.GetSignatureForError ());
212 if (type.IsInterface) {
213 if (!spec.AddInterface (type)) {
214 context.Module.Compiler.Report.Error (405, constraint.Location,
215 "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
223 var constraint_tp = type as TypeParameterSpec;
224 if (constraint_tp != null) {
225 if (tparam_types == null) {
226 tparam_types = new List<TypeParameterSpec> (2);
227 } else if (tparam_types.Contains (constraint_tp)) {
228 context.Module.Compiler.Report.Error (405, constraint.Location,
229 "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
234 // Checks whether each generic method parameter constraint type
235 // is valid with respect to T
237 if (tp.IsMethodTypeParameter) {
238 TypeManager.CheckTypeVariance (type, Variance.Contravariant, context);
241 var tp_def = constraint_tp.MemberDefinition as TypeParameter;
242 if (tp_def != null && !tp_def.ResolveConstraints (context)) {
243 context.Module.Compiler.Report.Error (454, constraint.Location,
244 "Circular constraint dependency involving `{0}' and `{1}'",
245 constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
250 // Checks whether there are no conflicts between type parameter constraints
256 // A and B are not convertible and only 1 class constraint is allowed
258 if (constraint_tp.HasTypeConstraint) {
259 if (spec.HasTypeConstraint || spec.HasSpecialStruct) {
260 if (!CheckConflictingInheritedConstraint (spec, constraint_tp.BaseType, context, constraint.Location))
263 for (int ii = 0; ii < tparam_types.Count; ++ii) {
264 if (!tparam_types[ii].HasTypeConstraint)
267 if (!CheckConflictingInheritedConstraint (spec, tparam_types[ii].BaseType, constraint_tp.BaseType, context, constraint.Location))
273 if (constraint_tp.HasSpecialStruct) {
274 context.Module.Compiler.Report.Error (456, constraint.Location,
275 "Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
276 constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
280 tparam_types.Add (constraint_tp);
284 if (iface_found || spec.HasTypeConstraint) {
285 context.Module.Compiler.Report.Error (406, constraint.Location,
286 "The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
287 type.GetSignatureForError ());
290 if (spec.HasSpecialStruct || spec.HasSpecialClass) {
291 context.Module.Compiler.Report.Error (450, constraint.Location,
292 "`{0}': cannot specify both a constraint class and the `class' or `struct' constraint",
293 type.GetSignatureForError ());
296 switch (type.BuiltinType) {
297 case BuiltinTypeSpec.Type.Array:
298 case BuiltinTypeSpec.Type.Delegate:
299 case BuiltinTypeSpec.Type.MulticastDelegate:
300 case BuiltinTypeSpec.Type.Enum:
301 case BuiltinTypeSpec.Type.ValueType:
302 case BuiltinTypeSpec.Type.Object:
303 context.Module.Compiler.Report.Error (702, constraint.Location,
304 "A constraint cannot be special class `{0}'", type.GetSignatureForError ());
306 case BuiltinTypeSpec.Type.Dynamic:
307 context.Module.Compiler.Report.Error (1967, constraint.Location,
308 "A constraint cannot be the dynamic type");
312 if (type.IsSealed || !type.IsClass) {
313 context.Module.Compiler.Report.Error (701, loc,
314 "`{0}' is not a valid constraint. A constraint must be an interface, a non-sealed class or a type parameter",
315 TypeManager.CSharpName (type));
320 context.Module.Compiler.Report.Error (717, constraint.Location,
321 "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
322 type.GetSignatureForError ());
325 spec.BaseType = type;
328 if (tparam_types != null)
329 spec.TypeArguments = tparam_types.ToArray ();
336 public void VerifyClsCompliance (Report report)
338 foreach (var c in constraints)
343 if (!c.Type.IsCLSCompliant ()) {
344 report.SymbolRelatedToPreviousError (c.Type);
345 report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
346 c.Type.GetSignatureForError ());
353 // A type parameter for a generic type or generic method definition
355 public class TypeParameter : MemberCore, ITypeDefinition
357 static readonly string[] attribute_target = new string [] { "type parameter" };
359 Constraints constraints;
360 GenericTypeParameterBuilder builder;
361 TypeParameterSpec spec;
363 public TypeParameter (int index, MemberName name, Constraints constraints, Attributes attrs, Variance variance)
364 : base (null, name, attrs)
366 this.constraints = constraints;
367 this.spec = new TypeParameterSpec (null, index, this, SpecialConstraint.None, variance, null);
373 public TypeParameter (MemberName name, Attributes attrs, Variance variance)
374 : base (null, name, attrs)
376 this.spec = new TypeParameterSpec (null, -1, this, SpecialConstraint.None, variance, null);
379 public TypeParameter (TypeParameterSpec spec, TypeSpec parentSpec, MemberName name, Attributes attrs)
380 : base (null, name, attrs)
382 this.spec = new TypeParameterSpec (parentSpec, spec.DeclaredPosition, spec.MemberDefinition, spec.SpecialConstraint, spec.Variance, null) {
383 BaseType = spec.BaseType,
384 InterfacesDefined = spec.InterfacesDefined,
385 TypeArguments = spec.TypeArguments
391 public override AttributeTargets AttributeTargets {
393 return AttributeTargets.GenericParameter;
397 public Constraints Constraints {
406 public IAssemblyDefinition DeclaringAssembly {
408 return Module.DeclaringAssembly;
412 public override string DocCommentHeader {
414 throw new InvalidOperationException (
415 "Unexpected attempt to get doc comment from " + this.GetType ());
419 bool ITypeDefinition.IsPartial {
425 public bool IsMethodTypeParameter {
427 return spec.IsMethodOwned;
433 return MemberName.Name;
437 public string Namespace {
443 public TypeParameterSpec Type {
449 public int TypeParametersCount {
455 public TypeParameterSpec[] TypeParameters {
461 public override string[] ValidAttributeTargets {
463 return attribute_target;
467 public Variance Variance {
469 return spec.Variance;
476 // This is called for each part of a partial generic type definition.
478 // If partial type parameters constraints are not null and we don't
479 // already have constraints they become our constraints. If we already
480 // have constraints, we must check that they're the same.
482 public bool AddPartialConstraints (TypeDefinition part, TypeParameter tp)
485 throw new InvalidOperationException ();
487 var new_constraints = tp.constraints;
488 if (new_constraints == null)
491 // TODO: could create spec only
492 //tp.Define (null, -1, part.Definition);
493 tp.spec.DeclaringType = part.Definition;
494 if (!tp.ResolveConstraints (part))
497 if (constraints != null)
498 return spec.HasSameConstraintsDefinition (tp.Type);
500 // Copy constraint from resolved part to partial container
501 spec.SpecialConstraint = tp.spec.SpecialConstraint;
502 spec.InterfacesDefined = tp.spec.InterfacesDefined;
503 spec.TypeArguments = tp.spec.TypeArguments;
504 spec.BaseType = tp.spec.BaseType;
509 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
511 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
514 public void CheckGenericConstraints (bool obsoleteCheck)
516 if (constraints != null)
517 constraints.CheckGenericConstraints (this, obsoleteCheck);
520 public TypeParameter CreateHoistedCopy (TypeSpec declaringSpec)
522 return new TypeParameter (spec, declaringSpec, MemberName, null);
525 public override bool Define ()
531 // This is the first method which is called during the resolving
532 // process; we're called immediately after creating the type parameters
533 // with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
536 public void Define (GenericTypeParameterBuilder type, TypeSpec declaringType, TypeContainer parent)
539 throw new InternalErrorException ();
541 // Needed to get compiler reference
542 this.Parent = parent;
544 spec.DeclaringType = declaringType;
545 spec.SetMetaInfo (type);
548 public void EmitConstraints (GenericTypeParameterBuilder builder)
550 var attr = GenericParameterAttributes.None;
551 if (spec.Variance == Variance.Contravariant)
552 attr |= GenericParameterAttributes.Contravariant;
553 else if (spec.Variance == Variance.Covariant)
554 attr |= GenericParameterAttributes.Covariant;
556 if (spec.HasSpecialClass)
557 attr |= GenericParameterAttributes.ReferenceTypeConstraint;
558 else if (spec.HasSpecialStruct)
559 attr |= GenericParameterAttributes.NotNullableValueTypeConstraint | GenericParameterAttributes.DefaultConstructorConstraint;
561 if (spec.HasSpecialConstructor)
562 attr |= GenericParameterAttributes.DefaultConstructorConstraint;
564 if (spec.BaseType.BuiltinType != BuiltinTypeSpec.Type.Object)
565 builder.SetBaseTypeConstraint (spec.BaseType.GetMetaInfo ());
567 if (spec.InterfacesDefined != null)
568 builder.SetInterfaceConstraints (spec.InterfacesDefined.Select (l => l.GetMetaInfo ()).ToArray ());
570 if (spec.TypeArguments != null)
571 builder.SetInterfaceConstraints (spec.TypeArguments.Select (l => l.GetMetaInfo ()).ToArray ());
573 builder.SetGenericParameterAttributes (attr);
576 public override void Emit ()
578 EmitConstraints (builder);
580 if (OptAttributes != null)
581 OptAttributes.Emit ();
586 public void ErrorInvalidVariance (IMemberContext mc, Variance expected)
588 Report.SymbolRelatedToPreviousError (mc.CurrentMemberDefinition);
589 string input_variance = Variance == Variance.Contravariant ? "contravariant" : "covariant";
590 string gtype_variance;
592 case Variance.Contravariant: gtype_variance = "contravariantly"; break;
593 case Variance.Covariant: gtype_variance = "covariantly"; break;
594 default: gtype_variance = "invariantly"; break;
597 Delegate d = mc as Delegate;
598 string parameters = d != null ? d.Parameters.GetSignatureForError () : "";
600 Report.Error (1961, Location,
601 "The {2} type parameter `{0}' must be {3} valid on `{1}{4}'",
602 GetSignatureForError (), mc.GetSignatureForError (), input_variance, gtype_variance, parameters);
605 public TypeSpec GetAttributeCoClass ()
610 public string GetAttributeDefaultMember ()
612 throw new NotSupportedException ();
615 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
617 throw new NotSupportedException ();
620 public override string GetSignatureForDocumentation ()
622 throw new NotImplementedException ();
625 public override string GetSignatureForError ()
627 return MemberName.Name;
630 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
632 return spec.MemberDefinition.DeclaringAssembly == assembly;
635 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
637 throw new NotSupportedException ("Not supported for compiled definition");
641 // Resolves all type parameter constraints
643 public bool ResolveConstraints (IMemberContext context)
645 if (constraints != null)
646 return constraints.Resolve (context, this);
648 if (spec.BaseType == null)
649 spec.BaseType = context.Module.Compiler.BuiltinTypes.Object;
654 public override bool IsClsComplianceRequired ()
659 public new void VerifyClsCompliance ()
661 if (constraints != null)
662 constraints.VerifyClsCompliance (Report);
665 public void WarningParentNameConflict (TypeParameter conflict)
667 conflict.Report.SymbolRelatedToPreviousError (conflict.Location, null);
668 conflict.Report.Warning (693, 3, Location,
669 "Type parameter `{0}' has the same name as the type parameter from outer type `{1}'",
670 GetSignatureForError (), conflict.CurrentType.GetSignatureForError ());
674 [System.Diagnostics.DebuggerDisplay ("{DisplayDebugInfo()}")]
675 public class TypeParameterSpec : TypeSpec
677 public static readonly new TypeParameterSpec[] EmptyTypes = new TypeParameterSpec[0];
680 SpecialConstraint spec;
683 TypeSpec[] ifaces_defined;
686 // Creates type owned type parameter
688 public TypeParameterSpec (TypeSpec declaringType, int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
689 : base (MemberKind.TypeParameter, declaringType, definition, info, Modifiers.PUBLIC)
691 this.variance = variance;
693 state &= ~StateFlags.Obsolete_Undetected;
698 // Creates method owned type parameter
700 public TypeParameterSpec (int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
701 : this (null, index, definition, spec, variance, info)
707 public int DeclaredPosition {
716 public bool HasSpecialConstructor {
718 return (spec & SpecialConstraint.Constructor) != 0;
722 public bool HasSpecialClass {
724 return (spec & SpecialConstraint.Class) != 0;
728 public bool HasSpecialStruct {
730 return (spec & SpecialConstraint.Struct) != 0;
734 public bool HasTypeConstraint {
736 var bt = BaseType.BuiltinType;
737 return bt != BuiltinTypeSpec.Type.Object && bt != BuiltinTypeSpec.Type.ValueType;
741 public override IList<TypeSpec> Interfaces {
743 if ((state & StateFlags.InterfacesExpanded) == 0) {
744 if (ifaces != null) {
745 for (int i = 0; i < ifaces.Count; ++i ) {
746 var iface_type = ifaces[i];
747 if (iface_type.Interfaces != null) {
748 if (ifaces_defined == null)
749 ifaces_defined = ifaces.ToArray ();
751 for (int ii = 0; ii < iface_type.Interfaces.Count; ++ii) {
752 var ii_iface_type = iface_type.Interfaces [ii];
754 AddInterface (ii_iface_type);
760 if (ifaces_defined == null)
761 ifaces_defined = ifaces == null ? TypeSpec.EmptyTypes : ifaces.ToArray ();
763 state |= StateFlags.InterfacesExpanded;
771 // Unexpanded interfaces list
773 public TypeSpec[] InterfacesDefined {
775 if (ifaces_defined == null) {
779 ifaces_defined = ifaces.ToArray ();
782 return ifaces_defined.Length == 0 ? null : ifaces_defined;
785 ifaces_defined = value;
786 if (value != null && value.Length != 0)
791 public bool IsConstrained {
793 return spec != SpecialConstraint.None || ifaces != null || targs != null || HasTypeConstraint;
798 // Returns whether the type parameter is known to be a reference type
800 public new bool IsReferenceType {
802 if ((spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0)
803 return (spec & SpecialConstraint.Class) != 0;
806 // Full check is needed (see IsValueType for details)
808 if (HasTypeConstraint && TypeSpec.IsReferenceType (BaseType))
812 foreach (var ta in targs) {
814 // Secondary special constraints are ignored (I am not sure why)
816 var tp = ta as TypeParameterSpec;
817 if (tp != null && (tp.spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0)
820 if (TypeSpec.IsReferenceType (ta))
830 // Returns whether the type parameter is known to be a value type
832 public new bool IsValueType {
835 // Even if structs/enums cannot be used directly as constraints
836 // they can apear as constraint type when inheriting base constraint
837 // which has dependant type parameter constraint which has been
838 // inflated using value type
840 // class A : B<int> { override void Foo<U> () {} }
841 // class B<T> { virtual void Foo<U> () where U : T {} }
843 if (HasSpecialStruct)
847 foreach (var ta in targs) {
848 if (TypeSpec.IsValueType (ta))
857 public override string Name {
859 return definition.Name;
863 public bool IsMethodOwned {
865 return DeclaringType == null;
869 public SpecialConstraint SpecialConstraint {
879 // Types used to inflate the generic type
881 public new TypeSpec[] TypeArguments {
890 public Variance Variance {
898 public string DisplayDebugInfo ()
900 var s = GetSignatureForError ();
901 return IsMethodOwned ? s + "!!" : s + "!";
905 // Finds effective base class. The effective base class is always a class-type
907 public TypeSpec GetEffectiveBase ()
909 if (HasSpecialStruct)
913 // If T has a class-type constraint C but no type-parameter constraints, its effective base class is C
915 if (BaseType != null && targs == null) {
917 // If T has a constraint V that is a value-type, use instead the most specific base type of V that is a class-type.
919 // LAMESPEC: Is System.ValueType always the most specific base type in this case?
921 // Note: This can never happen in an explicitly given constraint, but may occur when the constraints of a generic method
922 // are implicitly inherited by an overriding method declaration or an explicit implementation of an interface method.
924 return BaseType.IsStruct ? BaseType.BaseType : BaseType;
928 if (HasTypeConstraint) {
929 Array.Resize (ref types, types.Length + 1);
931 for (int i = 0; i < types.Length - 1; ++i) {
932 types[i] = types[i].BaseType;
935 types[types.Length - 1] = BaseType;
937 types = types.Select (l => l.BaseType).ToArray ();
941 return Convert.FindMostEncompassedType (types);
946 public override string GetSignatureForDocumentation ()
948 var prefix = IsMethodOwned ? "``" : "`";
949 return prefix + DeclaredPosition;
952 public override string GetSignatureForError ()
958 // Constraints have to match by definition but not position, used by
959 // partial classes or methods
961 public bool HasSameConstraintsDefinition (TypeParameterSpec other)
963 if (spec != other.spec)
966 if (BaseType != other.BaseType)
969 if (!TypeSpecComparer.Override.IsSame (InterfacesDefined, other.InterfacesDefined))
972 if (!TypeSpecComparer.Override.IsSame (targs, other.targs))
979 // Constraints have to match by using same set of types, used by
980 // implicit interface implementation
982 public bool HasSameConstraintsImplementation (TypeParameterSpec other)
984 if (spec != other.spec)
988 // It can be same base type or inflated type parameter
990 // interface I<T> { void Foo<U> where U : T; }
991 // class A : I<int> { void Foo<X> where X : int {} }
994 if (!TypeSpecComparer.Override.IsEqual (BaseType, other.BaseType)) {
995 if (other.targs == null)
999 foreach (var otarg in other.targs) {
1000 if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
1010 // Check interfaces implementation -> definition
1011 if (InterfacesDefined != null) {
1013 // Iterate over inflated interfaces
1015 foreach (var iface in Interfaces) {
1017 if (other.InterfacesDefined != null) {
1018 foreach (var oiface in other.Interfaces) {
1019 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
1029 if (other.targs != null) {
1030 foreach (var otarg in other.targs) {
1031 if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
1043 // Check interfaces implementation <- definition
1044 if (other.InterfacesDefined != null) {
1045 if (InterfacesDefined == null)
1049 // Iterate over inflated interfaces
1051 foreach (var oiface in other.Interfaces) {
1053 foreach (var iface in Interfaces) {
1054 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
1065 // Check type parameters implementation -> definition
1066 if (targs != null) {
1067 if (other.targs == null)
1070 foreach (var targ in targs) {
1072 foreach (var otarg in other.targs) {
1073 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
1084 // Check type parameters implementation <- definition
1085 if (other.targs != null) {
1086 foreach (var otarg in other.targs) {
1087 // Ignore inflated type arguments, were checked above
1088 if (!otarg.IsGenericParameter)
1095 foreach (var targ in targs) {
1096 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
1110 public static TypeParameterSpec[] InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec[] tparams)
1112 return InflateConstraints (tparams, l => l, inflator);
1115 public static TypeParameterSpec[] InflateConstraints<T> (TypeParameterSpec[] tparams, Func<T, TypeParameterInflator> inflatorFactory, T arg)
1117 TypeParameterSpec[] constraints = null;
1118 TypeParameterInflator? inflator = null;
1120 for (int i = 0; i < tparams.Length; ++i) {
1121 var tp = tparams[i];
1122 if (tp.HasTypeConstraint || tp.InterfacesDefined != null || tp.TypeArguments != null) {
1123 if (constraints == null) {
1124 constraints = new TypeParameterSpec[tparams.Length];
1125 Array.Copy (tparams, constraints, constraints.Length);
1129 // Using a factory to avoid possibly expensive inflator build up
1131 if (inflator == null)
1132 inflator = inflatorFactory (arg);
1134 constraints[i] = (TypeParameterSpec) constraints[i].InflateMember (inflator.Value);
1138 if (constraints == null)
1139 constraints = tparams;
1144 public void InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec tps)
1146 tps.BaseType = inflator.Inflate (BaseType);
1147 if (ifaces != null) {
1148 tps.ifaces = new List<TypeSpec> (ifaces.Count);
1149 for (int i = 0; i < ifaces.Count; ++i)
1150 tps.ifaces.Add (inflator.Inflate (ifaces[i]));
1153 if (targs != null) {
1154 tps.targs = new TypeSpec[targs.Length];
1155 for (int i = 0; i < targs.Length; ++i)
1156 tps.targs[i] = inflator.Inflate (targs[i]);
1160 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1162 var tps = (TypeParameterSpec) MemberwiseClone ();
1163 InflateConstraints (inflator, tps);
1168 // Populates type parameter members using type parameter constraints
1169 // The trick here is to be called late enough but not too late to
1170 // populate member cache with all members from other types
1172 protected override void InitializeMemberCache (bool onlyTypes)
1174 cache = new MemberCache ();
1177 // For a type parameter the membercache is the union of the sets of members of the types
1178 // specified as a primary constraint or secondary constraint
1180 if (BaseType.BuiltinType != BuiltinTypeSpec.Type.Object && BaseType.BuiltinType != BuiltinTypeSpec.Type.ValueType)
1181 cache.AddBaseType (BaseType);
1183 if (ifaces != null) {
1184 foreach (var iface_type in Interfaces) {
1185 cache.AddInterface (iface_type);
1189 if (targs != null) {
1190 foreach (var ta in targs) {
1191 var b_type = ta.BaseType;
1192 if (b_type.BuiltinType != BuiltinTypeSpec.Type.Object && b_type.BuiltinType != BuiltinTypeSpec.Type.ValueType)
1193 cache.AddBaseType (b_type);
1195 if (ta.Interfaces != null) {
1196 foreach (var iface_type in ta.Interfaces) {
1197 cache.AddInterface (iface_type);
1204 public bool IsConvertibleToInterface (TypeSpec iface)
1206 if (Interfaces != null) {
1207 foreach (var t in Interfaces) {
1213 if (TypeArguments != null) {
1214 foreach (var t in TypeArguments) {
1215 if (((TypeParameterSpec) t).IsConvertibleToInterface (iface))
1223 public override TypeSpec Mutate (TypeParameterMutator mutator)
1225 return mutator.Mutate (this);
1229 public struct TypeParameterInflator
1231 readonly TypeSpec type;
1232 readonly TypeParameterSpec[] tparams;
1233 readonly TypeSpec[] targs;
1234 readonly IModuleContext context;
1236 public TypeParameterInflator (TypeParameterInflator nested, TypeSpec type)
1237 : this (nested.context, type, nested.tparams, nested.targs)
1241 public TypeParameterInflator (IModuleContext context, TypeSpec type, TypeParameterSpec[] tparams, TypeSpec[] targs)
1243 if (tparams.Length != targs.Length)
1244 throw new ArgumentException ("Invalid arguments");
1246 this.context = context;
1247 this.tparams = tparams;
1254 public IModuleContext Context {
1260 public TypeSpec TypeInstance {
1267 // Type parameters to inflate
1269 public TypeParameterSpec[] TypeParameters {
1277 public TypeSpec Inflate (TypeSpec type)
1279 var tp = type as TypeParameterSpec;
1281 return Inflate (tp);
1283 var ac = type as ArrayContainer;
1285 var et = Inflate (ac.Element);
1286 if (et != ac.Element)
1287 return ArrayContainer.MakeType (context.Module, et, ac.Rank);
1293 // When inflating a nested type, inflate its parent first
1294 // in case it's using same type parameters (was inflated within the type)
1298 if (type.IsNested) {
1299 var parent = Inflate (type.DeclaringType);
1302 // Keep the inflated type arguments
1304 targs = type.TypeArguments;
1307 // When inflating imported nested type used inside same declaring type, we get TypeSpec
1308 // because the import cache helps us to catch it. However, that means we have to look at
1309 // type definition to get type argument (they are in fact type parameter in this case)
1311 if (targs.Length == 0 && type.Arity > 0)
1312 targs = type.MemberDefinition.TypeParameters;
1315 // Parent was inflated, find the same type on inflated type
1316 // to use same cache for nested types on same generic parent
1318 type = MemberCache.FindNestedType (parent, type.Name, type.Arity);
1321 // Handle the tricky case where parent shares local type arguments
1322 // which means inflating inflated type
1325 // public static Nested<T> Foo () { return null; }
1327 // public class Nested<U> {}
1330 // return type of Test<string>.Foo() has to be Test<string>.Nested<string>
1332 if (targs.Length > 0) {
1333 var inflated_targs = new TypeSpec[targs.Length];
1334 for (; i < targs.Length; ++i)
1335 inflated_targs[i] = Inflate (targs[i]);
1337 type = type.MakeGenericType (context, inflated_targs);
1343 // Nothing to do for non-generic type
1344 if (type.Arity == 0)
1347 targs = new TypeSpec[type.Arity];
1350 // Inflating using outside type arguments, var v = new Foo<int> (), class Foo<T> {}
1352 if (type is InflatedTypeSpec) {
1353 for (; i < targs.Length; ++i)
1354 targs[i] = Inflate (type.TypeArguments[i]);
1356 type = type.GetDefinition ();
1359 // Inflating parent using inside type arguments, class Foo<T> { ITest<T> foo; }
1361 var args = type.MemberDefinition.TypeParameters;
1362 foreach (var ds_tp in args)
1363 targs[i++] = Inflate (ds_tp);
1366 return type.MakeGenericType (context, targs);
1369 public TypeSpec Inflate (TypeParameterSpec tp)
1371 for (int i = 0; i < tparams.Length; ++i)
1372 if (tparams [i] == tp)
1375 // This can happen when inflating nested types
1376 // without type arguments specified
1382 // Before emitting any code we have to change all MVAR references to VAR
1383 // when the method is of generic type and has hoisted variables
1385 public class TypeParameterMutator
1387 readonly TypeParameters mvar;
1388 readonly TypeParameters var;
1389 Dictionary<TypeSpec, TypeSpec> mutated_typespec;
1391 public TypeParameterMutator (TypeParameters mvar, TypeParameters var)
1393 if (mvar.Count != var.Count)
1394 throw new ArgumentException ();
1402 public TypeParameters MethodTypeParameters {
1410 public static TypeSpec GetMemberDeclaringType (TypeSpec type)
1412 if (type is InflatedTypeSpec) {
1413 if (type.DeclaringType == null)
1414 return type.GetDefinition ();
1416 var parent = GetMemberDeclaringType (type.DeclaringType);
1417 type = MemberCache.GetMember<TypeSpec> (parent, type);
1423 public TypeSpec Mutate (TypeSpec ts)
1426 if (mutated_typespec != null && mutated_typespec.TryGetValue (ts, out value))
1429 value = ts.Mutate (this);
1430 if (mutated_typespec == null)
1431 mutated_typespec = new Dictionary<TypeSpec, TypeSpec> ();
1433 mutated_typespec.Add (ts, value);
1437 public TypeParameterSpec Mutate (TypeParameterSpec tp)
1439 for (int i = 0; i < mvar.Count; ++i) {
1440 if (mvar[i].Type == tp)
1447 public TypeSpec[] Mutate (TypeSpec[] targs)
1449 TypeSpec[] mutated = new TypeSpec[targs.Length];
1450 bool changed = false;
1451 for (int i = 0; i < targs.Length; ++i) {
1452 mutated[i] = Mutate (targs[i]);
1453 changed |= targs[i] != mutated[i];
1456 return changed ? mutated : targs;
1461 /// A TypeExpr which already resolved to a type parameter.
1463 public class TypeParameterExpr : TypeExpression
1465 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1466 : base (type_parameter.Type, loc)
1468 this.eclass = ExprClass.TypeParameter;
1472 public class InflatedTypeSpec : TypeSpec
1475 TypeParameterSpec[] constraints;
1476 readonly TypeSpec open_type;
1477 readonly IModuleContext context;
1479 public InflatedTypeSpec (IModuleContext context, TypeSpec openType, TypeSpec declaringType, TypeSpec[] targs)
1480 : base (openType.Kind, declaringType, openType.MemberDefinition, null, openType.Modifiers)
1483 throw new ArgumentNullException ("targs");
1485 // this.state = openType.state;
1486 this.context = context;
1487 this.open_type = openType;
1490 foreach (var arg in targs) {
1491 if (arg.HasDynamicElement || arg.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1492 state |= StateFlags.HasDynamicElement;
1497 if (open_type.Kind == MemberKind.MissingType)
1498 MemberCache = MemberCache.Empty;
1500 if ((open_type.Modifiers & Modifiers.COMPILER_GENERATED) != 0)
1501 state |= StateFlags.ConstraintsChecked;
1506 public override TypeSpec BaseType {
1508 if (cache == null || (state & StateFlags.PendingBaseTypeInflate) != 0)
1509 InitializeMemberCache (true);
1511 return base.BaseType;
1516 // Inflated type parameters with constraints array, mapping with type arguments is based on index
1518 public TypeParameterSpec[] Constraints {
1520 if (constraints == null) {
1521 constraints = TypeParameterSpec.InflateConstraints (MemberDefinition.TypeParameters, l => l.CreateLocalInflator (context), this);
1529 // Used to cache expensive constraints validation on constructed types
1531 public bool HasConstraintsChecked {
1533 return (state & StateFlags.ConstraintsChecked) != 0;
1536 state = value ? state | StateFlags.ConstraintsChecked : state & ~StateFlags.ConstraintsChecked;
1540 public override IList<TypeSpec> Interfaces {
1543 InitializeMemberCache (true);
1545 return base.Interfaces;
1549 public override bool IsExpressionTreeType {
1551 return (open_type.state & StateFlags.InflatedExpressionType) != 0;
1555 public override bool IsGenericIterateInterface {
1557 return (open_type.state & StateFlags.GenericIterateInterface) != 0;
1561 public override bool IsGenericTask {
1563 return (open_type.state & StateFlags.GenericTask) != 0;
1567 public override bool IsNullableType {
1569 return (open_type.state & StateFlags.InflatedNullableType) != 0;
1574 // Types used to inflate the generic type
1576 public override TypeSpec[] TypeArguments {
1584 public static bool ContainsTypeParameter (TypeSpec type)
1586 if (type.Kind == MemberKind.TypeParameter)
1589 var element_container = type as ElementTypeSpec;
1590 if (element_container != null)
1591 return ContainsTypeParameter (element_container.Element);
1593 foreach (var t in type.TypeArguments) {
1594 if (ContainsTypeParameter (t)) {
1602 TypeParameterInflator CreateLocalInflator (IModuleContext context)
1604 TypeParameterSpec[] tparams_full;
1605 TypeSpec[] targs_full = targs;
1608 // Special case is needed when we are inflating an open type (nested type definition)
1609 // on inflated parent. Consider following case
1611 // Foo<T>.Bar<U> => Foo<string>.Bar<U>
1613 // Any later inflation of Foo<string>.Bar<U> has to also inflate T if used inside Bar<U>
1615 List<TypeSpec> merged_targs = null;
1616 List<TypeParameterSpec> merged_tparams = null;
1618 var type = DeclaringType;
1621 if (type.TypeArguments.Length > 0) {
1622 if (merged_targs == null) {
1623 merged_targs = new List<TypeSpec> ();
1624 merged_tparams = new List<TypeParameterSpec> ();
1625 if (targs.Length > 0) {
1626 merged_targs.AddRange (targs);
1627 merged_tparams.AddRange (open_type.MemberDefinition.TypeParameters);
1630 merged_tparams.AddRange (type.MemberDefinition.TypeParameters);
1631 merged_targs.AddRange (type.TypeArguments);
1633 type = type.DeclaringType;
1634 } while (type != null);
1636 if (merged_targs != null) {
1637 // Type arguments are not in the right order but it should not matter in this case
1638 targs_full = merged_targs.ToArray ();
1639 tparams_full = merged_tparams.ToArray ();
1640 } else if (targs.Length == 0) {
1641 tparams_full = TypeParameterSpec.EmptyTypes;
1643 tparams_full = open_type.MemberDefinition.TypeParameters;
1645 } else if (targs.Length == 0) {
1646 tparams_full = TypeParameterSpec.EmptyTypes;
1648 tparams_full = open_type.MemberDefinition.TypeParameters;
1651 return new TypeParameterInflator (context, this, tparams_full, targs_full);
1654 MetaType CreateMetaInfo (TypeParameterMutator mutator)
1657 // Converts nested type arguments into right order
1658 // Foo<string, bool>.Bar<int> => string, bool, int
1660 var all = new List<MetaType> ();
1661 TypeSpec type = this;
1662 TypeSpec definition = type;
1664 if (type.GetDefinition().IsGeneric) {
1666 type.TypeArguments != TypeSpec.EmptyTypes ?
1667 type.TypeArguments.Select (l => l.GetMetaInfo ()) :
1668 type.MemberDefinition.TypeParameters.Select (l => l.GetMetaInfo ()));
1671 definition = definition.GetDefinition ();
1672 type = type.DeclaringType;
1673 } while (type != null);
1675 return definition.GetMetaInfo ().MakeGenericType (all.ToArray ());
1678 public override ObsoleteAttribute GetAttributeObsolete ()
1680 return open_type.GetAttributeObsolete ();
1683 protected override bool IsNotCLSCompliant (out bool attrValue)
1685 if (base.IsNotCLSCompliant (out attrValue))
1688 foreach (var ta in TypeArguments) {
1689 if (ta.MemberDefinition.CLSAttributeValue == false)
1696 public override TypeSpec GetDefinition ()
1701 public override MetaType GetMetaInfo ()
1704 info = CreateMetaInfo (null);
1709 public override string GetSignatureForError ()
1712 return targs[0].GetSignatureForError () + "?";
1714 return base.GetSignatureForError ();
1717 protected override string GetTypeNameSignature ()
1719 if (targs.Length == 0 || MemberDefinition is AnonymousTypeClass)
1722 return "<" + TypeManager.CSharpName (targs) + ">";
1725 public bool HasDynamicArgument ()
1727 for (int i = 0; i < targs.Length; ++i) {
1728 var item = targs[i];
1730 if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1733 if (item is InflatedTypeSpec) {
1734 if (((InflatedTypeSpec) item).HasDynamicArgument ())
1741 while (item.IsArray) {
1742 item = ((ArrayContainer) item).Element;
1745 if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1753 protected override void InitializeMemberCache (bool onlyTypes)
1755 if (cache == null) {
1756 var open_cache = onlyTypes ? open_type.MemberCacheTypes : open_type.MemberCache;
1758 // Surprisingly, calling MemberCache on open type could meantime create cache on this type
1759 // for imported type parameter constraints referencing nested type of this declaration
1761 cache = new MemberCache (open_cache);
1764 var inflator = CreateLocalInflator (context);
1767 // Two stage inflate due to possible nested types recursive
1777 // When resolving type of `b' members of `B' cannot be
1778 // inflated because are not yet available in membercache
1780 if ((state & StateFlags.PendingMemberCacheMembers) == 0) {
1781 open_type.MemberCacheTypes.InflateTypes (cache, inflator);
1784 // Inflate any implemented interfaces
1786 if (open_type.Interfaces != null) {
1787 ifaces = new List<TypeSpec> (open_type.Interfaces.Count);
1788 foreach (var iface in open_type.Interfaces) {
1789 var iface_inflated = inflator.Inflate (iface);
1790 if (iface_inflated == null)
1793 AddInterface (iface_inflated);
1798 // Handles the tricky case of recursive nested base generic type
1800 // class A<T> : Base<A<T>.Nested> {
1804 // When inflating A<T>. base type is not yet known, secondary
1805 // inflation is required (not common case) once base scope
1808 if (open_type.BaseType == null) {
1810 state |= StateFlags.PendingBaseTypeInflate;
1812 BaseType = inflator.Inflate (open_type.BaseType);
1814 } else if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1816 // It can happen when resolving base type without being defined
1817 // which is not allowed to happen and will always lead to an error
1819 // class B { class N {} }
1820 // class A<T> : A<B.N> {}
1822 if (open_type.BaseType == null)
1825 BaseType = inflator.Inflate (open_type.BaseType);
1826 state &= ~StateFlags.PendingBaseTypeInflate;
1830 state |= StateFlags.PendingMemberCacheMembers;
1834 var tc = open_type.MemberDefinition as TypeDefinition;
1835 if (tc != null && !tc.HasMembersDefined) {
1837 // Inflating MemberCache with undefined members
1842 if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1843 BaseType = inflator.Inflate (open_type.BaseType);
1844 state &= ~StateFlags.PendingBaseTypeInflate;
1847 state &= ~StateFlags.PendingMemberCacheMembers;
1848 open_type.MemberCache.InflateMembers (cache, open_type, inflator);
1851 public override TypeSpec Mutate (TypeParameterMutator mutator)
1853 var targs = TypeArguments;
1855 targs = mutator.Mutate (targs);
1857 var decl = DeclaringType;
1858 if (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
1859 decl = mutator.Mutate (decl);
1861 if (targs == TypeArguments && decl == DeclaringType)
1864 var mutated = (InflatedTypeSpec) MemberwiseClone ();
1865 if (decl != DeclaringType) {
1866 // Gets back MethodInfo in case of metaInfo was inflated
1867 //mutated.info = MemberCache.GetMember<TypeSpec> (DeclaringType.GetDefinition (), this).info;
1869 mutated.declaringType = decl;
1870 mutated.state |= StateFlags.PendingMetaInflate;
1873 if (targs != null) {
1874 mutated.targs = targs;
1875 mutated.info = null;
1884 // Tracks the type arguments when instantiating a generic type. It's used
1885 // by both type arguments and type parameters
1887 public class TypeArguments
1889 List<FullNamedExpression> args;
1892 public TypeArguments (params FullNamedExpression[] types)
1894 this.args = new List<FullNamedExpression> (types);
1897 public void Add (FullNamedExpression type)
1903 /// We may only be used after Resolve() is called and return the fully
1906 // TODO: Not needed, just return type from resolve
1907 public TypeSpec[] Arguments {
1922 public virtual bool IsEmpty {
1928 public List<FullNamedExpression> TypeExpressions {
1934 public string GetSignatureForError()
1936 StringBuilder sb = new StringBuilder ();
1937 for (int i = 0; i < Count; ++i) {
1940 sb.Append (expr.GetSignatureForError ());
1946 return sb.ToString ();
1950 /// Resolve the type arguments.
1952 public virtual bool Resolve (IMemberContext ec)
1955 return atypes.Length != 0;
1957 int count = args.Count;
1960 atypes = new TypeSpec [count];
1962 for (int i = 0; i < count; i++){
1963 var te = args[i].ResolveAsType (ec);
1972 ec.Module.Compiler.Report.Error (718, args[i].Location, "`{0}': static classes cannot be used as generic arguments",
1973 te.GetSignatureForError ());
1977 if (te.IsPointer || te.IsSpecialRuntimeType) {
1978 ec.Module.Compiler.Report.Error (306, args[i].Location,
1979 "The type `{0}' may not be used as a type argument",
1980 te.GetSignatureForError ());
1986 atypes = TypeSpec.EmptyTypes;
1991 public TypeArguments Clone ()
1993 TypeArguments copy = new TypeArguments ();
1994 foreach (var ta in args)
2001 public class UnboundTypeArguments : TypeArguments
2003 public UnboundTypeArguments (int arity)
2004 : base (new FullNamedExpression[arity])
2008 public override bool IsEmpty {
2014 public override bool Resolve (IMemberContext ec)
2016 // Nothing to be resolved
2021 public class TypeParameters
2023 List<TypeParameter> names;
2024 TypeParameterSpec[] types;
2026 public TypeParameters ()
2028 names = new List<TypeParameter> ();
2031 public TypeParameters (int count)
2033 names = new List<TypeParameter> (count);
2044 public TypeParameterSpec[] Types {
2052 public void Add (TypeParameter tparam)
2057 public void Add (TypeParameters tparams)
2059 names.AddRange (tparams.names);
2062 public void Define (GenericTypeParameterBuilder[] buiders, TypeSpec declaringType, int parentOffset, TypeContainer parent)
2064 types = new TypeParameterSpec[Count];
2065 for (int i = 0; i < types.Length; ++i) {
2068 tp.Define (buiders[i + parentOffset], declaringType, parent);
2070 types[i].DeclaredPosition = i + parentOffset;
2072 if (tp.Variance != Variance.None && !(declaringType != null && (declaringType.Kind == MemberKind.Interface || declaringType.Kind == MemberKind.Delegate))) {
2073 parent.Compiler.Report.Error (1960, tp.Location, "Variant type parameters can only be used with interfaces and delegates");
2078 public TypeParameter this[int index] {
2080 return names [index];
2083 names[index] = value;
2087 public TypeParameter Find (string name)
2089 foreach (var tp in names) {
2090 if (tp.Name == name)
2097 public string[] GetAllNames ()
2099 return names.Select (l => l.Name).ToArray ();
2102 public string GetSignatureForError ()
2104 StringBuilder sb = new StringBuilder ();
2105 for (int i = 0; i < Count; ++i) {
2109 var name = names[i];
2111 sb.Append (name.GetSignatureForError ());
2114 return sb.ToString ();
2117 public void VerifyClsCompliance ()
2119 foreach (var tp in names) {
2120 tp.VerifyClsCompliance ();
2126 // A type expression of generic type with type arguments
2128 class GenericTypeExpr : TypeExpr
2134 /// Instantiate the generic type `t' with the type arguments `args'.
2135 /// Use this constructor if you already know the fully resolved
2138 public GenericTypeExpr (TypeSpec open_type, TypeArguments args, Location l)
2140 this.open_type = open_type;
2145 public override string GetSignatureForError ()
2147 return TypeManager.CSharpName (type);
2150 public override TypeSpec ResolveAsType (IMemberContext mc)
2152 if (eclass != ExprClass.Unresolved)
2155 if (!args.Resolve (mc))
2158 TypeSpec[] atypes = args.Arguments;
2161 // Now bind the parameters
2163 var inflated = open_type.MakeGenericType (mc, atypes);
2165 eclass = ExprClass.Type;
2168 // The constraints can be checked only when full type hierarchy is known
2170 if (!inflated.HasConstraintsChecked && mc.Module.HasTypesFullyDefined) {
2171 var constraints = inflated.Constraints;
2172 if (constraints != null) {
2173 var cc = new ConstraintChecker (mc);
2174 if (cc.CheckAll (open_type, atypes, constraints, loc)) {
2175 inflated.HasConstraintsChecked = true;
2183 public override bool Equals (object obj)
2185 GenericTypeExpr cobj = obj as GenericTypeExpr;
2189 if ((type == null) || (cobj.type == null))
2192 return type == cobj.type;
2195 public override int GetHashCode ()
2197 return base.GetHashCode ();
2202 // Generic type with unbound type arguments, used for typeof (G<,,>)
2204 class GenericOpenTypeExpr : TypeExpression
2206 public GenericOpenTypeExpr (TypeSpec type, /*UnboundTypeArguments args,*/ Location loc)
2207 : base (type.GetDefinition (), loc)
2212 struct ConstraintChecker
2215 bool ignore_inferred_dynamic;
2216 bool recursive_checks;
2218 public ConstraintChecker (IMemberContext ctx)
2221 ignore_inferred_dynamic = false;
2222 recursive_checks = false;
2227 public bool IgnoreInferredDynamic {
2229 return ignore_inferred_dynamic;
2232 ignore_inferred_dynamic = value;
2239 // Checks the constraints of open generic type against type
2240 // arguments. This version is used for types which could not be
2241 // checked immediatelly during construction because the type
2242 // hierarchy was not yet fully setup (before Emit phase)
2244 public static bool Check (IMemberContext mc, TypeSpec type, Location loc)
2247 // Check declaring type first if there is any
2249 if (type.DeclaringType != null && !Check (mc, type.DeclaringType, loc))
2252 while (type is ElementTypeSpec)
2253 type = ((ElementTypeSpec) type).Element;
2255 if (type.Arity == 0)
2258 var gtype = type as InflatedTypeSpec;
2262 var constraints = gtype.Constraints;
2263 if (constraints == null)
2266 if (gtype.HasConstraintsChecked)
2269 var cc = new ConstraintChecker (mc);
2270 cc.recursive_checks = true;
2272 if (cc.CheckAll (gtype.GetDefinition (), type.TypeArguments, constraints, loc)) {
2273 gtype.HasConstraintsChecked = true;
2281 // Checks all type arguments againts type parameters constraints
2282 // NOTE: It can run in probing mode when `this.mc' is null
2284 public bool CheckAll (MemberSpec context, TypeSpec[] targs, TypeParameterSpec[] tparams, Location loc)
2286 for (int i = 0; i < tparams.Length; i++) {
2287 if (ignore_inferred_dynamic && targs[i].BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2290 var targ = targs[i];
2291 if (!CheckConstraint (context, targ, tparams [i], loc))
2294 if (!recursive_checks)
2297 if (!Check (mc, targ, loc))
2304 bool CheckConstraint (MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, Location loc)
2307 // First, check the `class' and `struct' constraints.
2309 if (tparam.HasSpecialClass && !TypeSpec.IsReferenceType (atype)) {
2311 mc.Module.Compiler.Report.Error (452, loc,
2312 "The type `{0}' must be a reference type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
2313 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2319 if (tparam.HasSpecialStruct && (!TypeSpec.IsValueType (atype) || atype.IsNullableType)) {
2321 mc.Module.Compiler.Report.Error (453, loc,
2322 "The type `{0}' must be a non-nullable value type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
2323 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2332 // Check the class constraint
2334 if (tparam.HasTypeConstraint) {
2335 var dep = tparam.BaseType.GetMissingDependencies ();
2340 ImportedTypeDefinition.Error_MissingDependency (mc, dep, loc);
2344 if (!CheckConversion (mc, context, atype, tparam, tparam.BaseType, loc)) {
2353 // Check the interfaces constraints
2355 if (tparam.Interfaces != null) {
2356 foreach (TypeSpec iface in tparam.Interfaces) {
2357 var dep = iface.GetMissingDependencies ();
2362 ImportedTypeDefinition.Error_MissingDependency (mc, dep, loc);
2365 // return immediately to avoid duplicate errors because we are scanning
2366 // expanded interface list
2370 if (!CheckConversion (mc, context, atype, tparam, iface, loc)) {
2380 // Check the type parameter constraint
2382 if (tparam.TypeArguments != null) {
2383 foreach (var ta in tparam.TypeArguments) {
2384 if (!CheckConversion (mc, context, atype, tparam, ta, loc)) {
2394 // Finally, check the constructor constraint.
2396 if (!tparam.HasSpecialConstructor)
2399 if (!HasDefaultConstructor (atype)) {
2401 mc.Module.Compiler.Report.SymbolRelatedToPreviousError (atype);
2402 mc.Module.Compiler.Report.Error (310, loc,
2403 "The type `{0}' must have a public parameterless constructor in order to use it as parameter `{1}' in the generic type or method `{2}'",
2404 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2412 static bool HasDynamicTypeArgument (TypeSpec[] targs)
2414 for (int i = 0; i < targs.Length; ++i) {
2415 var targ = targs [i];
2416 if (targ.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2419 if (HasDynamicTypeArgument (targ.TypeArguments))
2426 bool CheckConversion (IMemberContext mc, MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, TypeSpec ttype, Location loc)
2431 if (atype.IsGenericParameter) {
2432 var tps = (TypeParameterSpec) atype;
2433 if (tps.TypeArguments != null) {
2434 foreach (var targ in tps.TypeArguments) {
2435 if (TypeSpecComparer.Override.IsEqual (targ, ttype))
2440 if (Convert.ImplicitTypeParameterConversion (null, tps, ttype) != null)
2443 } else if (TypeSpec.IsValueType (atype)) {
2444 if (atype.IsNullableType) {
2446 // LAMESPEC: Only identity or base type ValueType or Object satisfy nullable type
2448 if (TypeSpec.IsBaseClass (atype, ttype, false))
2451 if (Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
2455 if (Convert.ImplicitReferenceConversionExists (atype, ttype) || Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
2460 // When partial/full type inference finds a dynamic type argument delay
2461 // the constraint check to runtime, it can succeed for real underlying
2464 if (ignore_inferred_dynamic && HasDynamicTypeArgument (ttype.TypeArguments))
2468 mc.Module.Compiler.Report.SymbolRelatedToPreviousError (tparam);
2469 if (atype.IsGenericParameter) {
2470 mc.Module.Compiler.Report.Error (314, loc,
2471 "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. There is no boxing or type parameter conversion from `{0}' to `{3}'",
2472 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2473 } else if (TypeSpec.IsValueType (atype)) {
2474 if (atype.IsNullableType) {
2475 if (ttype.IsInterface) {
2476 mc.Module.Compiler.Report.Error (313, loc,
2477 "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. The nullable type `{0}' never satisfies interface constraint `{3}'",
2478 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2480 mc.Module.Compiler.Report.Error (312, loc,
2481 "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. The nullable type `{0}' does not satisfy constraint `{3}'",
2482 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2485 mc.Module.Compiler.Report.Error (315, loc,
2486 "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. There is no boxing conversion from `{0}' to `{3}'",
2487 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2490 mc.Module.Compiler.Report.Error (311, loc,
2491 "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. There is no implicit reference conversion from `{0}' to `{3}'",
2492 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2499 static bool HasDefaultConstructor (TypeSpec atype)
2501 var tp = atype as TypeParameterSpec;
2503 return tp.HasSpecialConstructor || tp.HasSpecialStruct;
2506 if (atype.IsStruct || atype.IsEnum)
2509 if (atype.IsAbstract)
2512 var tdef = atype.GetDefinition ();
2514 var found = MemberCache.FindMember (tdef,
2515 MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters),
2516 BindingRestriction.DeclaredOnly | BindingRestriction.InstanceOnly);
2518 return found != null && (found.Modifiers & Modifiers.PUBLIC) != 0;
2522 public partial class TypeManager
2524 public static Variance CheckTypeVariance (TypeSpec t, Variance expected, IMemberContext member)
2526 var tp = t as TypeParameterSpec;
2528 Variance v = tp.Variance;
2529 if (expected == Variance.None && v != expected ||
2530 expected == Variance.Covariant && v == Variance.Contravariant ||
2531 expected == Variance.Contravariant && v == Variance.Covariant) {
2532 ((TypeParameter)tp.MemberDefinition).ErrorInvalidVariance (member, expected);
2538 if (t.TypeArguments.Length > 0) {
2539 var targs_definition = t.MemberDefinition.TypeParameters;
2540 TypeSpec[] targs = GetTypeArguments (t);
2541 for (int i = 0; i < targs.Length; ++i) {
2542 Variance v = targs_definition[i].Variance;
2543 CheckTypeVariance (targs[i], (Variance) ((int)v * (int)expected), member);
2550 return CheckTypeVariance (GetElementType (t), expected, member);
2552 return Variance.None;
2557 // Implements C# type inference
2562 // Tracks successful rate of type inference
2564 int score = int.MaxValue;
2565 readonly Arguments arguments;
2566 readonly int arg_count;
2568 public TypeInference (Arguments arguments)
2570 this.arguments = arguments;
2571 if (arguments != null)
2572 arg_count = arguments.Count;
2575 public int InferenceScore {
2581 public TypeSpec[] InferMethodArguments (ResolveContext ec, MethodSpec method)
2583 var method_generic_args = method.GenericDefinition.TypeParameters;
2584 TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2585 if (!context.UnfixedVariableExists)
2586 return TypeSpec.EmptyTypes;
2588 AParametersCollection pd = method.Parameters;
2589 if (!InferInPhases (ec, context, pd))
2592 return context.InferredTypeArguments;
2596 // Implements method type arguments inference
2598 bool InferInPhases (ResolveContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
2600 int params_arguments_start;
2601 if (methodParameters.HasParams) {
2602 params_arguments_start = methodParameters.Count - 1;
2604 params_arguments_start = arg_count;
2607 TypeSpec [] ptypes = methodParameters.Types;
2610 // The first inference phase
2612 TypeSpec method_parameter = null;
2613 for (int i = 0; i < arg_count; i++) {
2614 Argument a = arguments [i];
2618 if (i < params_arguments_start) {
2619 method_parameter = methodParameters.Types [i];
2620 } else if (i == params_arguments_start) {
2621 if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2622 method_parameter = methodParameters.Types [params_arguments_start];
2624 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2626 ptypes = (TypeSpec[]) ptypes.Clone ();
2627 ptypes [i] = method_parameter;
2631 // When a lambda expression, an anonymous method
2632 // is used an explicit argument type inference takes a place
2634 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2636 if (am.ExplicitTypeInference (ec, tic, method_parameter))
2642 score -= tic.ExactInference (a.Type, method_parameter);
2646 if (a.Expr.Type == InternalType.NullLiteral)
2649 if (TypeSpec.IsValueType (method_parameter)) {
2650 score -= tic.LowerBoundInference (a.Type, method_parameter);
2655 // Otherwise an output type inference is made
2657 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2661 // Part of the second phase but because it happens only once
2662 // we don't need to call it in cycle
2664 bool fixed_any = false;
2665 if (!tic.FixIndependentTypeArguments (ec, ptypes, ref fixed_any))
2668 return DoSecondPhase (ec, tic, ptypes, !fixed_any);
2671 bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, TypeSpec[] methodParameters, bool fixDependent)
2673 bool fixed_any = false;
2674 if (fixDependent && !tic.FixDependentTypes (ec, ref fixed_any))
2677 // If no further unfixed type variables exist, type inference succeeds
2678 if (!tic.UnfixedVariableExists)
2681 if (!fixed_any && fixDependent)
2684 // For all arguments where the corresponding argument output types
2685 // contain unfixed type variables but the input types do not,
2686 // an output type inference is made
2687 for (int i = 0; i < arg_count; i++) {
2689 // Align params arguments
2690 TypeSpec t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
2692 if (!t_i.IsDelegate) {
2693 if (!t_i.IsExpressionTreeType)
2696 t_i = TypeManager.GetTypeArguments (t_i) [0];
2699 var mi = Delegate.GetInvokeMethod (t_i);
2700 TypeSpec rtype = mi.ReturnType;
2702 if (tic.IsReturnTypeNonDependent (ec, mi, rtype)) {
2703 // It can be null for default arguments
2704 if (arguments[i] == null)
2707 score -= tic.OutputTypeInference (ec, arguments[i].Expr, t_i);
2712 return DoSecondPhase (ec, tic, methodParameters, true);
2716 public class TypeInferenceContext
2718 protected enum BoundKind
2725 protected class BoundInfo : IEquatable<BoundInfo>
2727 public readonly TypeSpec Type;
2728 public readonly BoundKind Kind;
2730 public BoundInfo (TypeSpec type, BoundKind kind)
2736 public override int GetHashCode ()
2738 return Type.GetHashCode ();
2741 public virtual Expression GetTypeExpression ()
2743 return new TypeExpression (Type, Location.Null);
2746 #region IEquatable<BoundInfo> Members
2748 public virtual bool Equals (BoundInfo other)
2750 return Type == other.Type && Kind == other.Kind;
2756 readonly TypeSpec[] tp_args;
2757 readonly TypeSpec[] fixed_types;
2758 readonly List<BoundInfo>[] bounds;
2761 // TODO MemberCache: Could it be TypeParameterSpec[] ??
2762 public TypeInferenceContext (TypeSpec[] typeArguments)
2764 if (typeArguments.Length == 0)
2765 throw new ArgumentException ("Empty generic arguments");
2767 fixed_types = new TypeSpec [typeArguments.Length];
2768 for (int i = 0; i < typeArguments.Length; ++i) {
2769 if (typeArguments [i].IsGenericParameter) {
2770 if (bounds == null) {
2771 bounds = new List<BoundInfo> [typeArguments.Length];
2772 tp_args = new TypeSpec [typeArguments.Length];
2774 tp_args [i] = typeArguments [i];
2776 fixed_types [i] = typeArguments [i];
2782 // Used together with AddCommonTypeBound fo implement
2783 // 7.4.2.13 Finding the best common type of a set of expressions
2785 public TypeInferenceContext ()
2787 fixed_types = new TypeSpec [1];
2788 tp_args = new TypeSpec [1];
2789 tp_args[0] = InternalType.Arglist; // it can be any internal type
2790 bounds = new List<BoundInfo> [1];
2793 public TypeSpec[] InferredTypeArguments {
2799 public void AddCommonTypeBound (TypeSpec type)
2801 AddToBounds (new BoundInfo (type, BoundKind.Lower), 0);
2804 protected void AddToBounds (BoundInfo bound, int index)
2807 // Some types cannot be used as type arguments
2809 if (bound.Type.Kind == MemberKind.Void || bound.Type.IsPointer || bound.Type.IsSpecialRuntimeType ||
2810 bound.Type == InternalType.MethodGroup || bound.Type == InternalType.AnonymousMethod)
2813 var a = bounds [index];
2815 a = new List<BoundInfo> (2);
2821 if (a.Contains (bound))
2827 bool AllTypesAreFixed (TypeSpec[] types)
2829 foreach (TypeSpec t in types) {
2830 if (t.IsGenericParameter) {
2836 if (TypeManager.IsGenericType (t))
2837 return AllTypesAreFixed (TypeManager.GetTypeArguments (t));
2844 // 26.3.3.8 Exact Inference
2846 public int ExactInference (TypeSpec u, TypeSpec v)
2848 // If V is an array type
2853 var ac_u = (ArrayContainer) u;
2854 var ac_v = (ArrayContainer) v;
2855 if (ac_u.Rank != ac_v.Rank)
2858 return ExactInference (ac_u.Element, ac_v.Element);
2861 // If V is constructed type and U is constructed type
2862 if (TypeManager.IsGenericType (v)) {
2863 if (!TypeManager.IsGenericType (u) || v.MemberDefinition != u.MemberDefinition)
2866 TypeSpec [] ga_u = TypeManager.GetTypeArguments (u);
2867 TypeSpec [] ga_v = TypeManager.GetTypeArguments (v);
2868 if (ga_u.Length != ga_v.Length)
2872 for (int i = 0; i < ga_u.Length; ++i)
2873 score += ExactInference (ga_u [i], ga_v [i]);
2875 return score > 0 ? 1 : 0;
2878 // If V is one of the unfixed type arguments
2879 int pos = IsUnfixed (v);
2883 AddToBounds (new BoundInfo (u, BoundKind.Exact), pos);
2887 public bool FixAllTypes (ResolveContext ec)
2889 for (int i = 0; i < tp_args.Length; ++i) {
2890 if (!FixType (ec, i))
2897 // All unfixed type variables Xi are fixed for which all of the following hold:
2898 // a, There is at least one type variable Xj that depends on Xi
2899 // b, Xi has a non-empty set of bounds
2901 public bool FixDependentTypes (ResolveContext ec, ref bool fixed_any)
2903 for (int i = 0; i < tp_args.Length; ++i) {
2904 if (fixed_types[i] != null)
2907 if (bounds[i] == null)
2910 if (!FixType (ec, i))
2920 // All unfixed type variables Xi which depend on no Xj are fixed
2922 public bool FixIndependentTypeArguments (ResolveContext ec, TypeSpec[] methodParameters, ref bool fixed_any)
2924 var types_to_fix = new List<TypeSpec> (tp_args);
2925 for (int i = 0; i < methodParameters.Length; ++i) {
2926 TypeSpec t = methodParameters[i];
2928 if (!t.IsDelegate) {
2929 if (!t.IsExpressionTreeType)
2932 t = TypeManager.GetTypeArguments (t) [0];
2935 if (t.IsGenericParameter)
2938 var invoke = Delegate.GetInvokeMethod (t);
2939 TypeSpec rtype = invoke.ReturnType;
2940 while (rtype.IsArray)
2941 rtype = ((ArrayContainer) rtype).Element;
2943 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
2946 // Remove dependent types, they cannot be fixed yet
2947 RemoveDependentTypes (types_to_fix, rtype);
2950 foreach (TypeSpec t in types_to_fix) {
2954 int idx = IsUnfixed (t);
2955 if (idx >= 0 && !FixType (ec, idx)) {
2960 fixed_any = types_to_fix.Count > 0;
2967 public bool FixType (ResolveContext ec, int i)
2969 // It's already fixed
2970 if (fixed_types[i] != null)
2971 throw new InternalErrorException ("Type argument has been already fixed");
2976 var candidates = bounds [i];
2977 if (candidates == null)
2980 if (candidates.Count == 1) {
2981 TypeSpec t = candidates[0].Type;
2982 if (t == InternalType.NullLiteral)
2985 fixed_types [i] = t;
2990 // Determines a unique type from which there is
2991 // a standard implicit conversion to all the other
2994 TypeSpec best_candidate = null;
2996 int candidates_count = candidates.Count;
2997 for (int ci = 0; ci < candidates_count; ++ci) {
2998 BoundInfo bound = candidates [ci];
2999 for (cii = 0; cii < candidates_count; ++cii) {
3003 BoundInfo cbound = candidates[cii];
3005 // Same type parameters with different bounds
3006 if (cbound.Type == bound.Type) {
3007 if (bound.Kind != BoundKind.Exact)
3013 if (bound.Kind == BoundKind.Exact || cbound.Kind == BoundKind.Exact) {
3014 if (cbound.Kind == BoundKind.Lower) {
3015 if (!Convert.ImplicitConversionExists (ec, cbound.GetTypeExpression (), bound.Type)) {
3021 if (cbound.Kind == BoundKind.Upper) {
3022 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
3029 if (bound.Kind != BoundKind.Exact) {
3030 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
3041 if (bound.Kind == BoundKind.Lower) {
3042 if (cbound.Kind == BoundKind.Lower) {
3043 if (!Convert.ImplicitConversionExists (ec, cbound.GetTypeExpression (), bound.Type)) {
3047 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
3057 if (bound.Kind == BoundKind.Upper) {
3058 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
3062 throw new NotImplementedException ("variance conversion");
3066 if (cii != candidates_count)
3070 // We already have the best candidate, break if thet are different
3072 // Dynamic is never ambiguous as we prefer dynamic over other best candidate types
3074 if (best_candidate != null) {
3076 if (best_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3079 if (bound.Type.BuiltinType != BuiltinTypeSpec.Type.Dynamic && best_candidate != bound.Type)
3083 best_candidate = bound.Type;
3086 if (best_candidate == null)
3089 fixed_types[i] = best_candidate;
3093 public bool HasBounds (int pos)
3095 return bounds[pos] != null;
3099 // Uses inferred or partially infered types to inflate delegate type argument. Returns
3100 // null when type parameter has not been fixed
3102 public TypeSpec InflateGenericArgument (IModuleContext context, TypeSpec parameter)
3104 var tp = parameter as TypeParameterSpec;
3107 // Type inference works on generic arguments (MVAR) only
3109 if (!tp.IsMethodOwned)
3113 // Ensure the type parameter belongs to same container
3115 if (tp.DeclaredPosition < tp_args.Length && tp_args[tp.DeclaredPosition] == parameter)
3116 return fixed_types[tp.DeclaredPosition] ?? parameter;
3121 var gt = parameter as InflatedTypeSpec;
3123 var inflated_targs = new TypeSpec [gt.TypeArguments.Length];
3124 for (int ii = 0; ii < inflated_targs.Length; ++ii) {
3125 var inflated = InflateGenericArgument (context, gt.TypeArguments [ii]);
3126 if (inflated == null)
3129 inflated_targs[ii] = inflated;
3132 return gt.GetDefinition ().MakeGenericType (context, inflated_targs);
3135 var ac = parameter as ArrayContainer;
3137 var inflated = InflateGenericArgument (context, ac.Element);
3138 if (inflated != ac.Element)
3139 return ArrayContainer.MakeType (context.Module, inflated);
3146 // Tests whether all delegate input arguments are fixed and generic output type
3147 // requires output type inference
3149 public bool IsReturnTypeNonDependent (ResolveContext ec, MethodSpec invoke, TypeSpec returnType)
3151 while (returnType.IsArray)
3152 returnType = ((ArrayContainer) returnType).Element;
3154 if (returnType.IsGenericParameter) {
3155 if (IsFixed (returnType))
3157 } else if (TypeManager.IsGenericType (returnType)) {
3158 if (returnType.IsDelegate) {
3159 invoke = Delegate.GetInvokeMethod (returnType);
3160 return IsReturnTypeNonDependent (ec, invoke, invoke.ReturnType);
3163 TypeSpec[] g_args = TypeManager.GetTypeArguments (returnType);
3165 // At least one unfixed return type has to exist
3166 if (AllTypesAreFixed (g_args))
3172 // All generic input arguments have to be fixed
3173 AParametersCollection d_parameters = invoke.Parameters;
3174 return AllTypesAreFixed (d_parameters.Types);
3177 bool IsFixed (TypeSpec type)
3179 return IsUnfixed (type) == -1;
3182 int IsUnfixed (TypeSpec type)
3184 if (!type.IsGenericParameter)
3187 for (int i = 0; i < tp_args.Length; ++i) {
3188 if (tp_args[i] == type) {
3189 if (fixed_types[i] != null)
3200 // 26.3.3.9 Lower-bound Inference
3202 public int LowerBoundInference (TypeSpec u, TypeSpec v)
3204 return LowerBoundInference (u, v, false);
3208 // Lower-bound (false) or Upper-bound (true) inference based on inversed argument
3210 int LowerBoundInference (TypeSpec u, TypeSpec v, bool inversed)
3212 // If V is one of the unfixed type arguments
3213 int pos = IsUnfixed (v);
3215 AddToBounds (new BoundInfo (u, inversed ? BoundKind.Upper : BoundKind.Lower), pos);
3219 // If U is an array type
3220 var u_ac = u as ArrayContainer;
3222 var v_ac = v as ArrayContainer;
3224 if (u_ac.Rank != v_ac.Rank)
3227 if (TypeSpec.IsValueType (u_ac.Element))
3228 return ExactInference (u_ac.Element, v_ac.Element);
3230 return LowerBoundInference (u_ac.Element, v_ac.Element, inversed);
3233 if (u_ac.Rank != 1 || !v.IsGenericIterateInterface)
3236 var v_i = TypeManager.GetTypeArguments (v) [0];
3237 if (TypeSpec.IsValueType (u_ac.Element))
3238 return ExactInference (u_ac.Element, v_i);
3240 return LowerBoundInference (u_ac.Element, v_i);
3243 if (v.IsGenericOrParentIsGeneric) {
3245 // if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
3246 // such that U is identical to, inherits from (directly or indirectly),
3247 // or implements (directly or indirectly) C<U1..Uk>
3249 var u_candidates = new List<TypeSpec> ();
3250 var open_v = v.MemberDefinition;
3252 for (TypeSpec t = u; t != null; t = t.BaseType) {
3253 if (open_v == t.MemberDefinition)
3254 u_candidates.Add (t);
3257 // Using this trick for dynamic type inference, the spec says the type arguments are "unknown" but
3258 // that would complicate the process a lot, instead I treat them as dynamic
3260 if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3261 u_candidates.Add (t);
3263 if (t.Interfaces != null) {
3264 foreach (var iface in t.Interfaces) {
3265 if (open_v == iface.MemberDefinition)
3266 u_candidates.Add (iface);
3271 TypeSpec[] unique_candidate_targs = null;
3272 var ga_v = TypeSpec.GetAllTypeArguments (v);
3273 foreach (TypeSpec u_candidate in u_candidates) {
3275 // The unique set of types U1..Uk means that if we have an interface I<T>,
3276 // class U : I<int>, I<long> then no type inference is made when inferring
3277 // type I<T> by applying type U because T could be int or long
3279 if (unique_candidate_targs != null) {
3280 TypeSpec[] second_unique_candidate_targs = TypeSpec.GetAllTypeArguments (u_candidate);
3281 if (TypeSpecComparer.Equals (unique_candidate_targs, second_unique_candidate_targs)) {
3282 unique_candidate_targs = second_unique_candidate_targs;
3287 // This should always cause type inference failure
3294 // A candidate is dynamic type expression, to simplify things use dynamic
3295 // for all type parameter of this type. For methods like this one
3297 // void M<T, U> (IList<T>, IList<U[]>)
3299 // dynamic becomes both T and U when the arguments are of dynamic type
3301 if (u_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
3302 unique_candidate_targs = new TypeSpec[ga_v.Length];
3303 for (int i = 0; i < unique_candidate_targs.Length; ++i)
3304 unique_candidate_targs[i] = u_candidate;
3306 unique_candidate_targs = TypeSpec.GetAllTypeArguments (u_candidate);
3310 if (unique_candidate_targs != null) {
3313 TypeParameterSpec[] tps = null;
3315 for (int i = 0; i < unique_candidate_targs.Length; ++i) {
3317 while (v.Arity == 0)
3318 v = v.DeclaringType;
3320 tps = v.MemberDefinition.TypeParameters;
3321 tp_index = tps.Length - 1;
3324 Variance variance = tps [tp_index--].Variance;
3326 TypeSpec u_i = unique_candidate_targs [i];
3327 if (variance == Variance.None || TypeSpec.IsValueType (u_i)) {
3328 if (ExactInference (u_i, ga_v [i]) == 0)
3331 bool upper_bound = (variance == Variance.Contravariant && !inversed) ||
3332 (variance == Variance.Covariant && inversed);
3334 if (LowerBoundInference (u_i, ga_v [i], upper_bound) == 0)
3347 // 26.3.3.6 Output Type Inference
3349 public int OutputTypeInference (ResolveContext ec, Expression e, TypeSpec t)
3351 // If e is a lambda or anonymous method with inferred return type
3352 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
3354 TypeSpec rt = ame.InferReturnType (ec, this, t);
3355 var invoke = Delegate.GetInvokeMethod (t);
3358 AParametersCollection pd = invoke.Parameters;
3359 return ame.Parameters.Count == pd.Count ? 1 : 0;
3362 TypeSpec rtype = invoke.ReturnType;
3363 return LowerBoundInference (rt, rtype) + 1;
3367 // if E is a method group and T is a delegate type or expression tree type
3368 // return type Tb with parameter types T1..Tk and return type Tb, and overload
3369 // resolution of E with the types T1..Tk yields a single method with return type U,
3370 // then a lower-bound inference is made from U for Tb.
3372 if (e is MethodGroupExpr) {
3373 if (!t.IsDelegate) {
3374 if (!t.IsExpressionTreeType)
3377 t = TypeManager.GetTypeArguments (t)[0];
3380 var invoke = Delegate.GetInvokeMethod (t);
3381 TypeSpec rtype = invoke.ReturnType;
3383 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
3386 // LAMESPEC: Standard does not specify that all methodgroup arguments
3387 // has to be fixed but it does not specify how to do recursive type inference
3388 // either. We choose the simple option and infer return type only
3389 // if all delegate generic arguments are fixed.
3390 TypeSpec[] param_types = new TypeSpec [invoke.Parameters.Count];
3391 for (int i = 0; i < param_types.Length; ++i) {
3392 var inflated = InflateGenericArgument (ec, invoke.Parameters.Types[i]);
3393 if (inflated == null)
3396 if (IsUnfixed (inflated) >= 0)
3399 param_types[i] = inflated;
3402 MethodGroupExpr mg = (MethodGroupExpr) e;
3403 Arguments args = DelegateCreation.CreateDelegateMethodArguments (invoke.Parameters, param_types, e.Location);
3404 mg = mg.OverloadResolve (ec, ref args, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
3408 return LowerBoundInference (mg.BestCandidateReturnType, rtype) + 1;
3412 // if e is an expression with type U, then
3413 // a lower-bound inference is made from U for T
3415 return LowerBoundInference (e.Type, t) * 2;
3418 void RemoveDependentTypes (List<TypeSpec> types, TypeSpec returnType)
3420 int idx = IsUnfixed (returnType);
3426 if (TypeManager.IsGenericType (returnType)) {
3427 foreach (TypeSpec t in TypeManager.GetTypeArguments (returnType)) {
3428 RemoveDependentTypes (types, t);
3433 public bool UnfixedVariableExists {
3435 foreach (TypeSpec ut in fixed_types) {