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 Location Location {
97 public SimpleMemberName TypeParameter {
105 public static bool CheckConflictingInheritedConstraint (TypeParameterSpec spec, TypeSpec bb, IMemberContext context, Location loc)
107 if (spec.HasSpecialClass && bb.IsStruct) {
108 context.Module.Compiler.Report.Error (455, loc,
109 "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
110 spec.Name, "class", bb.GetSignatureForError ());
115 return CheckConflictingInheritedConstraint (spec, spec.BaseType, bb, context, loc);
118 static bool CheckConflictingInheritedConstraint (TypeParameterSpec spec, TypeSpec ba, TypeSpec bb, IMemberContext context, Location loc)
123 if (TypeSpec.IsBaseClass (ba, bb, false) || TypeSpec.IsBaseClass (bb, ba, false))
126 context.Module.Compiler.Report.Error (455, loc,
127 "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
128 spec.Name, ba.GetSignatureForError (), bb.GetSignatureForError ());
132 public void CheckGenericConstraints (IMemberContext context, bool obsoleteCheck)
134 foreach (var c in constraints) {
143 ObsoleteAttribute obsolete_attr = t.GetAttributeObsolete ();
144 if (obsolete_attr != null)
145 AttributeTester.Report_ObsoleteMessage (obsolete_attr, t.GetSignatureForError (), c.Location, context.Module.Compiler.Report);
148 ConstraintChecker.Check (context, t, c.Location);
153 // Resolve the constraints types with only possible early checks, return
154 // value `false' is reserved for recursive failure
156 public bool Resolve (IMemberContext context, TypeParameter tp)
166 List<TypeParameterSpec> tparam_types = null;
167 bool iface_found = false;
169 spec.BaseType = context.Module.Compiler.BuiltinTypes.Object;
171 for (int i = 0; i < constraints.Count; ++i) {
172 var constraint = constraints[i];
174 if (constraint is SpecialContraintExpr) {
175 spec.SpecialConstraint |= ((SpecialContraintExpr) constraint).Constraint;
176 if (spec.HasSpecialStruct)
177 spec.BaseType = context.Module.Compiler.BuiltinTypes.ValueType;
179 // Set to null as it does not have a type
180 constraints[i] = null;
184 var type = constraint.ResolveAsType (context);
188 if (type.Arity > 0 && ((InflatedTypeSpec) type).HasDynamicArgument ()) {
189 context.Module.Compiler.Report.Error (1968, constraint.Location,
190 "A constraint cannot be the dynamic type `{0}'", type.GetSignatureForError ());
194 if (!context.CurrentMemberDefinition.IsAccessibleAs (type)) {
195 context.Module.Compiler.Report.SymbolRelatedToPreviousError (type);
196 context.Module.Compiler.Report.Error (703, loc,
197 "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
198 type.GetSignatureForError (), context.GetSignatureForError ());
201 if (type.IsInterface) {
202 if (!spec.AddInterface (type)) {
203 context.Module.Compiler.Report.Error (405, constraint.Location,
204 "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
212 var constraint_tp = type as TypeParameterSpec;
213 if (constraint_tp != null) {
214 if (tparam_types == null) {
215 tparam_types = new List<TypeParameterSpec> (2);
216 } else if (tparam_types.Contains (constraint_tp)) {
217 context.Module.Compiler.Report.Error (405, constraint.Location,
218 "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
223 // Checks whether each generic method parameter constraint type
224 // is valid with respect to T
226 if (tp.IsMethodTypeParameter) {
227 TypeManager.CheckTypeVariance (type, Variance.Contravariant, context);
230 var tp_def = constraint_tp.MemberDefinition as TypeParameter;
231 if (tp_def != null && !tp_def.ResolveConstraints (context)) {
232 context.Module.Compiler.Report.Error (454, constraint.Location,
233 "Circular constraint dependency involving `{0}' and `{1}'",
234 constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
239 // Checks whether there are no conflicts between type parameter constraints
245 // A and B are not convertible and only 1 class constraint is allowed
247 if (constraint_tp.HasTypeConstraint) {
248 if (spec.HasTypeConstraint || spec.HasSpecialStruct) {
249 if (!CheckConflictingInheritedConstraint (spec, constraint_tp.BaseType, context, constraint.Location))
252 for (int ii = 0; ii < tparam_types.Count; ++ii) {
253 if (!tparam_types[ii].HasTypeConstraint)
256 if (!CheckConflictingInheritedConstraint (spec, tparam_types[ii].BaseType, constraint_tp.BaseType, context, constraint.Location))
262 if (constraint_tp.HasSpecialStruct) {
263 context.Module.Compiler.Report.Error (456, constraint.Location,
264 "Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
265 constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
269 tparam_types.Add (constraint_tp);
273 if (iface_found || spec.HasTypeConstraint) {
274 context.Module.Compiler.Report.Error (406, constraint.Location,
275 "The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
276 type.GetSignatureForError ());
279 if (spec.HasSpecialStruct || spec.HasSpecialClass) {
280 context.Module.Compiler.Report.Error (450, constraint.Location,
281 "`{0}': cannot specify both a constraint class and the `class' or `struct' constraint",
282 type.GetSignatureForError ());
285 switch (type.BuiltinType) {
286 case BuiltinTypeSpec.Type.Array:
287 case BuiltinTypeSpec.Type.Delegate:
288 case BuiltinTypeSpec.Type.MulticastDelegate:
289 case BuiltinTypeSpec.Type.Enum:
290 case BuiltinTypeSpec.Type.ValueType:
291 case BuiltinTypeSpec.Type.Object:
292 context.Module.Compiler.Report.Error (702, constraint.Location,
293 "A constraint cannot be special class `{0}'", type.GetSignatureForError ());
295 case BuiltinTypeSpec.Type.Dynamic:
296 context.Module.Compiler.Report.Error (1967, constraint.Location,
297 "A constraint cannot be the dynamic type");
301 if (type.IsSealed || !type.IsClass) {
302 context.Module.Compiler.Report.Error (701, loc,
303 "`{0}' is not a valid constraint. A constraint must be an interface, a non-sealed class or a type parameter",
304 TypeManager.CSharpName (type));
309 context.Module.Compiler.Report.Error (717, constraint.Location,
310 "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
311 type.GetSignatureForError ());
314 spec.BaseType = type;
317 if (tparam_types != null)
318 spec.TypeArguments = tparam_types.ToArray ();
325 public void VerifyClsCompliance (Report report)
327 foreach (var c in constraints)
332 if (!c.Type.IsCLSCompliant ()) {
333 report.SymbolRelatedToPreviousError (c.Type);
334 report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
335 c.Type.GetSignatureForError ());
342 // A type parameter for a generic type or generic method definition
344 public class TypeParameter : MemberCore, ITypeDefinition
346 static readonly string[] attribute_target = new string [] { "type parameter" };
348 Constraints constraints;
349 GenericTypeParameterBuilder builder;
350 TypeParameterSpec spec;
352 public TypeParameter (DeclSpace parent, int index, MemberName name, Constraints constraints, Attributes attrs, Variance variance)
353 : base (parent, name, attrs)
355 this.constraints = constraints;
356 this.spec = new TypeParameterSpec (null, index, this, SpecialConstraint.None, variance, null);
359 public TypeParameter (TypeParameterSpec spec, DeclSpace parent, TypeSpec parentSpec, MemberName name, Attributes attrs)
360 : base (parent, name, attrs)
362 this.spec = new TypeParameterSpec (parentSpec, spec.DeclaredPosition, spec.MemberDefinition, spec.SpecialConstraint, spec.Variance, null) {
363 BaseType = spec.BaseType,
364 InterfacesDefined = spec.InterfacesDefined,
365 TypeArguments = spec.TypeArguments
371 public override AttributeTargets AttributeTargets {
373 return AttributeTargets.GenericParameter;
377 public IAssemblyDefinition DeclaringAssembly {
379 return Module.DeclaringAssembly;
383 public override string DocCommentHeader {
385 throw new InvalidOperationException (
386 "Unexpected attempt to get doc comment from " + this.GetType ());
390 public bool IsMethodTypeParameter {
392 return spec.IsMethodOwned;
396 public string Namespace {
402 public TypeParameterSpec Type {
408 public int TypeParametersCount {
414 public TypeParameterSpec[] TypeParameters {
420 public override string[] ValidAttributeTargets {
422 return attribute_target;
426 public Variance Variance {
428 return spec.Variance;
435 // This is called for each part of a partial generic type definition.
437 // If partial type parameters constraints are not null and we don't
438 // already have constraints they become our constraints. If we already
439 // have constraints, we must check that they're the same.
441 public bool AddPartialConstraints (TypeContainer part, TypeParameter tp)
444 throw new InvalidOperationException ();
446 var new_constraints = tp.constraints;
447 if (new_constraints == null)
450 // TODO: could create spec only
451 //tp.Define (null, -1, part.Definition);
452 tp.spec.DeclaringType = part.Definition;
453 if (!tp.ResolveConstraints (part))
456 if (constraints != null)
457 return spec.HasSameConstraintsDefinition (tp.Type);
459 // Copy constraint from resolved part to partial container
460 spec.SpecialConstraint = tp.spec.SpecialConstraint;
461 spec.InterfacesDefined = tp.spec.InterfacesDefined;
462 spec.TypeArguments = tp.spec.TypeArguments;
463 spec.BaseType = tp.spec.BaseType;
468 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
470 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
473 public void CheckGenericConstraints (bool obsoleteCheck)
475 if (constraints != null)
476 constraints.CheckGenericConstraints (this, obsoleteCheck);
479 public TypeParameter CreateHoistedCopy (TypeContainer declaringType, TypeSpec declaringSpec)
481 return new TypeParameter (spec, declaringType, declaringSpec, MemberName, null);
484 public override bool Define ()
490 // This is the first method which is called during the resolving
491 // process; we're called immediately after creating the type parameters
492 // with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
495 public void Define (GenericTypeParameterBuilder type, TypeSpec declaringType)
498 throw new InternalErrorException ();
501 spec.DeclaringType = declaringType;
502 spec.SetMetaInfo (type);
505 public void EmitConstraints (GenericTypeParameterBuilder builder)
507 var attr = GenericParameterAttributes.None;
508 if (spec.Variance == Variance.Contravariant)
509 attr |= GenericParameterAttributes.Contravariant;
510 else if (spec.Variance == Variance.Covariant)
511 attr |= GenericParameterAttributes.Covariant;
513 if (spec.HasSpecialClass)
514 attr |= GenericParameterAttributes.ReferenceTypeConstraint;
515 else if (spec.HasSpecialStruct)
516 attr |= GenericParameterAttributes.NotNullableValueTypeConstraint | GenericParameterAttributes.DefaultConstructorConstraint;
518 if (spec.HasSpecialConstructor)
519 attr |= GenericParameterAttributes.DefaultConstructorConstraint;
521 if (spec.BaseType.BuiltinType != BuiltinTypeSpec.Type.Object)
522 builder.SetBaseTypeConstraint (spec.BaseType.GetMetaInfo ());
524 if (spec.InterfacesDefined != null)
525 builder.SetInterfaceConstraints (spec.InterfacesDefined.Select (l => l.GetMetaInfo ()).ToArray ());
527 if (spec.TypeArguments != null)
528 builder.SetInterfaceConstraints (spec.TypeArguments.Select (l => l.GetMetaInfo ()).ToArray ());
530 builder.SetGenericParameterAttributes (attr);
533 public override void Emit ()
535 EmitConstraints (builder);
537 if (OptAttributes != null)
538 OptAttributes.Emit ();
543 public void ErrorInvalidVariance (IMemberContext mc, Variance expected)
545 Report.SymbolRelatedToPreviousError (mc.CurrentMemberDefinition);
546 string input_variance = Variance == Variance.Contravariant ? "contravariant" : "covariant";
547 string gtype_variance;
549 case Variance.Contravariant: gtype_variance = "contravariantly"; break;
550 case Variance.Covariant: gtype_variance = "covariantly"; break;
551 default: gtype_variance = "invariantly"; break;
554 Delegate d = mc as Delegate;
555 string parameters = d != null ? d.Parameters.GetSignatureForError () : "";
557 Report.Error (1961, Location,
558 "The {2} type parameter `{0}' must be {3} valid on `{1}{4}'",
559 GetSignatureForError (), mc.GetSignatureForError (), input_variance, gtype_variance, parameters);
562 public TypeSpec GetAttributeCoClass ()
567 public string GetAttributeDefaultMember ()
569 throw new NotSupportedException ();
572 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
574 throw new NotSupportedException ();
577 public override string GetSignatureForDocumentation ()
579 throw new NotImplementedException ();
582 public override string GetSignatureForError ()
584 return MemberName.Name;
587 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
589 return spec.MemberDefinition.DeclaringAssembly == assembly;
592 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
594 throw new NotSupportedException ("Not supported for compiled definition");
598 // Resolves all type parameter constraints
600 public bool ResolveConstraints (IMemberContext context)
602 if (constraints != null)
603 return constraints.Resolve (context, this);
605 if (spec.BaseType == null)
606 spec.BaseType = context.Module.Compiler.BuiltinTypes.Object;
611 public static TypeParameter FindTypeParameter (TypeParameter[] tparams, string name)
613 foreach (var tp in tparams) {
621 public override bool IsClsComplianceRequired ()
626 public new void VerifyClsCompliance ()
628 if (constraints != null)
629 constraints.VerifyClsCompliance (Report);
633 [System.Diagnostics.DebuggerDisplay ("{DisplayDebugInfo()}")]
634 public class TypeParameterSpec : TypeSpec
636 public static readonly new TypeParameterSpec[] EmptyTypes = new TypeParameterSpec[0];
639 SpecialConstraint spec;
642 TypeSpec[] ifaces_defined;
645 // Creates type owned type parameter
647 public TypeParameterSpec (TypeSpec declaringType, int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
648 : base (MemberKind.TypeParameter, declaringType, definition, info, Modifiers.PUBLIC)
650 this.variance = variance;
652 state &= ~StateFlags.Obsolete_Undetected;
657 // Creates method owned type parameter
659 public TypeParameterSpec (int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
660 : this (null, index, definition, spec, variance, info)
666 public int DeclaredPosition {
672 public bool HasSpecialConstructor {
674 return (spec & SpecialConstraint.Constructor) != 0;
678 public bool HasSpecialClass {
680 return (spec & SpecialConstraint.Class) != 0;
684 public bool HasSpecialStruct {
686 return (spec & SpecialConstraint.Struct) != 0;
690 public bool HasTypeConstraint {
692 var bt = BaseType.BuiltinType;
693 return bt != BuiltinTypeSpec.Type.Object && bt != BuiltinTypeSpec.Type.ValueType;
697 public override IList<TypeSpec> Interfaces {
699 if ((state & StateFlags.InterfacesExpanded) == 0) {
700 if (ifaces != null) {
701 for (int i = 0; i < ifaces.Count; ++i ) {
702 var iface_type = ifaces[i];
703 if (iface_type.Interfaces != null) {
704 if (ifaces_defined == null)
705 ifaces_defined = ifaces.ToArray ();
707 for (int ii = 0; ii < iface_type.Interfaces.Count; ++ii) {
708 var ii_iface_type = iface_type.Interfaces [ii];
710 AddInterface (ii_iface_type);
716 if (ifaces_defined == null && ifaces != null)
717 ifaces_defined = ifaces.ToArray ();
719 state |= StateFlags.InterfacesExpanded;
727 // Unexpanded interfaces list
729 public TypeSpec[] InterfacesDefined {
731 if (ifaces_defined == null && ifaces != null)
732 ifaces_defined = ifaces.ToArray ();
734 return ifaces_defined;
737 ifaces = ifaces_defined = value;
741 public bool IsConstrained {
743 return spec != SpecialConstraint.None || ifaces != null || targs != null || HasTypeConstraint;
748 // Returns whether the type parameter is known to be a reference type
750 public new bool IsReferenceType {
752 if ((spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0)
753 return (spec & SpecialConstraint.Class) != 0;
756 // Full check is needed (see IsValueType for details)
758 if (HasTypeConstraint && TypeSpec.IsReferenceType (BaseType))
762 foreach (var ta in targs) {
764 // Secondary special constraints are ignored (I am not sure why)
766 var tp = ta as TypeParameterSpec;
767 if (tp != null && (tp.spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0)
770 if (TypeSpec.IsReferenceType (ta))
780 // Returns whether the type parameter is known to be a value type
782 public new bool IsValueType {
785 // Even if structs/enums cannot be used directly as constraints
786 // they can apear as constraint type when inheriting base constraint
787 // which has dependant type parameter constraint which has been
788 // inflated using value type
790 // class A : B<int> { override void Foo<U> () {} }
791 // class B<T> { virtual void Foo<U> () where U : T {} }
793 return HasSpecialStruct || TypeSpec.IsValueType (BaseType);
797 public override string Name {
799 return definition.Name;
803 public bool IsMethodOwned {
805 return DeclaringType == null;
809 public SpecialConstraint SpecialConstraint {
819 // Types used to inflate the generic type
821 public new TypeSpec[] TypeArguments {
830 public Variance Variance {
838 public void ChangeTypeArgumentToBaseType (int index)
840 BaseType = targs [index];
841 if (targs.Length == 1) {
844 var copy = new TypeSpec[targs.Length - 1];
846 Array.Copy (targs, copy, index);
848 Array.Copy (targs, index + 1, copy, index, targs.Length - index - 1);
853 public string DisplayDebugInfo ()
855 var s = GetSignatureForError ();
856 return IsMethodOwned ? s + "!!" : s + "!";
860 // Finds effective base class. The effective base class is always a class-type
862 public TypeSpec GetEffectiveBase ()
864 if (HasSpecialStruct)
868 // If T has a class-type constraint C but no type-parameter constraints, its effective base class is C
870 if (BaseType != null && targs == null) {
872 // 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.
874 // LAMESPEC: Is System.ValueType always the most specific base type in this case?
876 // Note: This can never happen in an explicitly given constraint, but may occur when the constraints of a generic method
877 // are implicitly inherited by an overriding method declaration or an explicit implementation of an interface method.
879 return BaseType.IsStruct ? BaseType.BaseType : BaseType;
883 if (HasTypeConstraint) {
884 Array.Resize (ref types, types.Length + 1);
885 types[types.Length - 1] = BaseType;
889 return Convert.FindMostEncompassedType (types.Select (l => l.BaseType));
894 public override string GetSignatureForDocumentation ()
897 var type = DeclaringType;
898 while (type != null && type.DeclaringType != null) {
899 type = type.DeclaringType;
900 c += type.MemberDefinition.TypeParametersCount;
903 var prefix = IsMethodOwned ? "``" : "`";
904 return prefix + (c + DeclaredPosition);
907 public override string GetSignatureForError ()
913 // Constraints have to match by definition but not position, used by
914 // partial classes or methods
916 public bool HasSameConstraintsDefinition (TypeParameterSpec other)
918 if (spec != other.spec)
921 if (BaseType != other.BaseType)
924 if (!TypeSpecComparer.Override.IsSame (InterfacesDefined, other.InterfacesDefined))
927 if (!TypeSpecComparer.Override.IsSame (targs, other.targs))
934 // Constraints have to match by using same set of types, used by
935 // implicit interface implementation
937 public bool HasSameConstraintsImplementation (TypeParameterSpec other)
939 if (spec != other.spec)
943 // It can be same base type or inflated type parameter
945 // interface I<T> { void Foo<U> where U : T; }
946 // class A : I<int> { void Foo<X> where X : int {} }
949 if (!TypeSpecComparer.Override.IsEqual (BaseType, other.BaseType)) {
950 if (other.targs == null)
954 foreach (var otarg in other.targs) {
955 if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
965 // Check interfaces implementation -> definition
966 if (InterfacesDefined != null) {
968 // Iterate over inflated interfaces
970 foreach (var iface in Interfaces) {
972 if (other.InterfacesDefined != null) {
973 foreach (var oiface in other.Interfaces) {
974 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
984 if (other.targs != null) {
985 foreach (var otarg in other.targs) {
986 if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
998 // Check interfaces implementation <- definition
999 if (other.InterfacesDefined != null) {
1000 if (InterfacesDefined == null)
1004 // Iterate over inflated interfaces
1006 foreach (var oiface in other.Interfaces) {
1008 foreach (var iface in Interfaces) {
1009 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
1020 // Check type parameters implementation -> definition
1021 if (targs != null) {
1022 if (other.targs == null)
1025 foreach (var targ in targs) {
1027 foreach (var otarg in other.targs) {
1028 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
1039 // Check type parameters implementation <- definition
1040 if (other.targs != null) {
1041 foreach (var otarg in other.targs) {
1042 // Ignore inflated type arguments, were checked above
1043 if (!otarg.IsGenericParameter)
1050 foreach (var targ in targs) {
1051 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
1065 public static TypeParameterSpec[] InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec[] tparams)
1067 return InflateConstraints (tparams, l => l, inflator);
1070 public static TypeParameterSpec[] InflateConstraints<T> (TypeParameterSpec[] tparams, Func<T, TypeParameterInflator> inflatorFactory, T arg)
1072 TypeParameterSpec[] constraints = null;
1073 TypeParameterInflator? inflator = null;
1075 for (int i = 0; i < tparams.Length; ++i) {
1076 var tp = tparams[i];
1077 if (tp.HasTypeConstraint || tp.InterfacesDefined != null || tp.TypeArguments != null) {
1078 if (constraints == null) {
1079 constraints = new TypeParameterSpec[tparams.Length];
1080 Array.Copy (tparams, constraints, constraints.Length);
1084 // Using a factory to avoid possibly expensive inflator build up
1086 if (inflator == null)
1087 inflator = inflatorFactory (arg);
1089 constraints[i] = (TypeParameterSpec) constraints[i].InflateMember (inflator.Value);
1093 if (constraints == null)
1094 constraints = tparams;
1099 public void InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec tps)
1101 tps.BaseType = inflator.Inflate (BaseType);
1102 if (ifaces != null) {
1103 tps.ifaces = new List<TypeSpec> (ifaces.Count);
1104 for (int i = 0; i < ifaces.Count; ++i)
1105 tps.ifaces.Add (inflator.Inflate (ifaces[i]));
1108 if (targs != null) {
1109 tps.targs = new TypeSpec[targs.Length];
1110 for (int i = 0; i < targs.Length; ++i)
1111 tps.targs[i] = inflator.Inflate (targs[i]);
1115 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1117 var tps = (TypeParameterSpec) MemberwiseClone ();
1118 InflateConstraints (inflator, tps);
1123 // Populates type parameter members using type parameter constraints
1124 // The trick here is to be called late enough but not too late to
1125 // populate member cache with all members from other types
1127 protected override void InitializeMemberCache (bool onlyTypes)
1129 cache = new MemberCache ();
1132 // For a type parameter the membercache is the union of the sets of members of the types
1133 // specified as a primary constraint or secondary constraint
1135 if (BaseType.BuiltinType != BuiltinTypeSpec.Type.Object && BaseType.BuiltinType != BuiltinTypeSpec.Type.ValueType)
1136 cache.AddBaseType (BaseType);
1138 if (ifaces != null) {
1139 foreach (var iface_type in Interfaces) {
1140 cache.AddInterface (iface_type);
1144 if (targs != null) {
1145 foreach (var ta in targs) {
1146 var b_type = ta.BaseType;
1147 if (b_type.BuiltinType != BuiltinTypeSpec.Type.Object && b_type.BuiltinType != BuiltinTypeSpec.Type.ValueType)
1148 cache.AddBaseType (b_type);
1150 if (ta.Interfaces != null) {
1151 foreach (var iface_type in ta.Interfaces) {
1152 cache.AddInterface (iface_type);
1159 public bool IsConvertibleToInterface (TypeSpec iface)
1161 if (Interfaces != null) {
1162 foreach (var t in Interfaces) {
1168 if (TypeArguments != null) {
1169 foreach (var t in TypeArguments) {
1170 if (((TypeParameterSpec) t).IsConvertibleToInterface (iface))
1178 public override TypeSpec Mutate (TypeParameterMutator mutator)
1180 return mutator.Mutate (this);
1184 public struct TypeParameterInflator
1186 readonly TypeSpec type;
1187 readonly TypeParameterSpec[] tparams;
1188 readonly TypeSpec[] targs;
1189 readonly IModuleContext context;
1191 public TypeParameterInflator (TypeParameterInflator nested, TypeSpec type)
1192 : this (nested.context, type, nested.tparams, nested.targs)
1196 public TypeParameterInflator (IModuleContext context, TypeSpec type, TypeParameterSpec[] tparams, TypeSpec[] targs)
1198 if (tparams.Length != targs.Length)
1199 throw new ArgumentException ("Invalid arguments");
1201 this.context = context;
1202 this.tparams = tparams;
1209 public IModuleContext Context {
1215 public TypeSpec TypeInstance {
1222 // Type parameters to inflate
1224 public TypeParameterSpec[] TypeParameters {
1232 public TypeSpec Inflate (TypeSpec type)
1234 var tp = type as TypeParameterSpec;
1236 return Inflate (tp);
1238 var ac = type as ArrayContainer;
1240 var et = Inflate (ac.Element);
1241 if (et != ac.Element)
1242 return ArrayContainer.MakeType (context.Module, et, ac.Rank);
1248 // When inflating a nested type, inflate its parent first
1249 // in case it's using same type parameters (was inflated within the type)
1253 if (type.IsNested) {
1254 var parent = Inflate (type.DeclaringType);
1257 // Keep the inflated type arguments
1259 targs = type.TypeArguments;
1262 // When inflating imported nested type used inside same declaring type, we get TypeSpec
1263 // because the import cache helps us to catch it. However, that means we have to look at
1264 // type definition to get type argument (they are in fact type parameter in this case)
1266 if (targs.Length == 0 && type.Arity > 0)
1267 targs = type.MemberDefinition.TypeParameters;
1270 // Parent was inflated, find the same type on inflated type
1271 // to use same cache for nested types on same generic parent
1273 type = MemberCache.FindNestedType (parent, type.Name, type.Arity);
1276 // Handle the tricky case where parent shares local type arguments
1277 // which means inflating inflated type
1280 // public static Nested<T> Foo () { return null; }
1282 // public class Nested<U> {}
1285 // return type of Test<string>.Foo() has to be Test<string>.Nested<string>
1287 if (targs.Length > 0) {
1288 var inflated_targs = new TypeSpec[targs.Length];
1289 for (; i < targs.Length; ++i)
1290 inflated_targs[i] = Inflate (targs[i]);
1292 type = type.MakeGenericType (context, inflated_targs);
1298 // Nothing to do for non-generic type
1299 if (type.Arity == 0)
1302 targs = new TypeSpec[type.Arity];
1305 // Inflating using outside type arguments, var v = new Foo<int> (), class Foo<T> {}
1307 if (type is InflatedTypeSpec) {
1308 for (; i < targs.Length; ++i)
1309 targs[i] = Inflate (type.TypeArguments[i]);
1311 type = type.GetDefinition ();
1314 // Inflating parent using inside type arguments, class Foo<T> { ITest<T> foo; }
1316 var args = type.MemberDefinition.TypeParameters;
1317 foreach (var ds_tp in args)
1318 targs[i++] = Inflate (ds_tp);
1321 return type.MakeGenericType (context, targs);
1324 public TypeSpec Inflate (TypeParameterSpec tp)
1326 for (int i = 0; i < tparams.Length; ++i)
1327 if (tparams [i] == tp)
1330 // This can happen when inflating nested types
1331 // without type arguments specified
1337 // Before emitting any code we have to change all MVAR references to VAR
1338 // when the method is of generic type and has hoisted variables
1340 public class TypeParameterMutator
1342 readonly TypeParameter[] mvar;
1343 readonly TypeParameter[] var;
1344 Dictionary<TypeSpec, TypeSpec> mutated_typespec;
1346 public TypeParameterMutator (TypeParameter[] mvar, TypeParameter[] var)
1348 if (mvar.Length != var.Length)
1349 throw new ArgumentException ();
1357 public TypeParameter[] MethodTypeParameters {
1365 public static TypeSpec GetMemberDeclaringType (TypeSpec type)
1367 if (type is InflatedTypeSpec) {
1368 if (type.DeclaringType == null)
1369 return type.GetDefinition ();
1371 var parent = GetMemberDeclaringType (type.DeclaringType);
1372 type = MemberCache.GetMember<TypeSpec> (parent, type);
1378 public TypeSpec Mutate (TypeSpec ts)
1381 if (mutated_typespec != null && mutated_typespec.TryGetValue (ts, out value))
1384 value = ts.Mutate (this);
1385 if (mutated_typespec == null)
1386 mutated_typespec = new Dictionary<TypeSpec, TypeSpec> ();
1388 mutated_typespec.Add (ts, value);
1392 public TypeParameterSpec Mutate (TypeParameterSpec tp)
1394 for (int i = 0; i < mvar.Length; ++i) {
1395 if (mvar[i].Type == tp)
1402 public TypeSpec[] Mutate (TypeSpec[] targs)
1404 TypeSpec[] mutated = new TypeSpec[targs.Length];
1405 bool changed = false;
1406 for (int i = 0; i < targs.Length; ++i) {
1407 mutated[i] = Mutate (targs[i]);
1408 changed |= targs[i] != mutated[i];
1411 return changed ? mutated : targs;
1416 /// A TypeExpr which already resolved to a type parameter.
1418 public class TypeParameterExpr : TypeExpression
1420 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1421 : base (type_parameter.Type, loc)
1423 this.eclass = ExprClass.TypeParameter;
1427 public class InflatedTypeSpec : TypeSpec
1430 TypeParameterSpec[] constraints;
1431 readonly TypeSpec open_type;
1432 readonly IModuleContext context;
1434 public InflatedTypeSpec (IModuleContext context, TypeSpec openType, TypeSpec declaringType, TypeSpec[] targs)
1435 : base (openType.Kind, declaringType, openType.MemberDefinition, null, openType.Modifiers)
1438 throw new ArgumentNullException ("targs");
1440 // this.state = openType.state;
1441 this.context = context;
1442 this.open_type = openType;
1445 foreach (var arg in targs) {
1446 if (arg.HasDynamicElement || arg.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1447 state |= StateFlags.HasDynamicElement;
1452 if (open_type.Kind == MemberKind.MissingType)
1453 MemberCache = MemberCache.Empty;
1455 if ((open_type.Modifiers & Modifiers.COMPILER_GENERATED) != 0)
1456 state |= StateFlags.ConstraintsChecked;
1461 public override TypeSpec BaseType {
1463 if (cache == null || (state & StateFlags.PendingBaseTypeInflate) != 0)
1464 InitializeMemberCache (true);
1466 return base.BaseType;
1471 // Inflated type parameters with constraints array, mapping with type arguments is based on index
1473 public TypeParameterSpec[] Constraints {
1475 if (constraints == null) {
1476 constraints = TypeParameterSpec.InflateConstraints (MemberDefinition.TypeParameters, l => l.CreateLocalInflator (context), this);
1484 // Used to cache expensive constraints validation on constructed types
1486 public bool HasConstraintsChecked {
1488 return (state & StateFlags.ConstraintsChecked) != 0;
1491 state = value ? state | StateFlags.ConstraintsChecked : state & ~StateFlags.ConstraintsChecked;
1495 public override IList<TypeSpec> Interfaces {
1498 InitializeMemberCache (true);
1500 return base.Interfaces;
1504 public override bool IsExpressionTreeType {
1506 return (open_type.state & StateFlags.InflatedExpressionType) != 0;
1510 public override bool IsGenericIterateInterface {
1512 return (open_type.state & StateFlags.GenericIterateInterface) != 0;
1516 public override bool IsGenericTask {
1518 return (open_type.state & StateFlags.GenericTask) != 0;
1522 public override bool IsNullableType {
1524 return (open_type.state & StateFlags.InflatedNullableType) != 0;
1529 // Types used to inflate the generic type
1531 public override TypeSpec[] TypeArguments {
1539 public static bool ContainsTypeParameter (TypeSpec type)
1541 if (type.Kind == MemberKind.TypeParameter)
1544 var element_container = type as ElementTypeSpec;
1545 if (element_container != null)
1546 return ContainsTypeParameter (element_container.Element);
1548 foreach (var t in type.TypeArguments) {
1549 if (ContainsTypeParameter (t)) {
1557 TypeParameterInflator CreateLocalInflator (IModuleContext context)
1559 TypeParameterSpec[] tparams_full;
1560 TypeSpec[] targs_full = targs;
1563 // Special case is needed when we are inflating an open type (nested type definition)
1564 // on inflated parent. Consider following case
1566 // Foo<T>.Bar<U> => Foo<string>.Bar<U>
1568 // Any later inflation of Foo<string>.Bar<U> has to also inflate T if used inside Bar<U>
1570 List<TypeSpec> merged_targs = null;
1571 List<TypeParameterSpec> merged_tparams = null;
1573 var type = DeclaringType;
1576 if (type.TypeArguments.Length > 0) {
1577 if (merged_targs == null) {
1578 merged_targs = new List<TypeSpec> ();
1579 merged_tparams = new List<TypeParameterSpec> ();
1580 if (targs.Length > 0) {
1581 merged_targs.AddRange (targs);
1582 merged_tparams.AddRange (open_type.MemberDefinition.TypeParameters);
1585 merged_tparams.AddRange (type.MemberDefinition.TypeParameters);
1586 merged_targs.AddRange (type.TypeArguments);
1588 type = type.DeclaringType;
1589 } while (type != null);
1591 if (merged_targs != null) {
1592 // Type arguments are not in the right order but it should not matter in this case
1593 targs_full = merged_targs.ToArray ();
1594 tparams_full = merged_tparams.ToArray ();
1595 } else if (targs.Length == 0) {
1596 tparams_full = TypeParameterSpec.EmptyTypes;
1598 tparams_full = open_type.MemberDefinition.TypeParameters;
1600 } else if (targs.Length == 0) {
1601 tparams_full = TypeParameterSpec.EmptyTypes;
1603 tparams_full = open_type.MemberDefinition.TypeParameters;
1606 return new TypeParameterInflator (context, this, tparams_full, targs_full);
1609 MetaType CreateMetaInfo (TypeParameterMutator mutator)
1612 // Converts nested type arguments into right order
1613 // Foo<string, bool>.Bar<int> => string, bool, int
1615 var all = new List<MetaType> ();
1616 TypeSpec type = this;
1617 TypeSpec definition = type;
1619 if (type.GetDefinition().IsGeneric) {
1621 type.TypeArguments != TypeSpec.EmptyTypes ?
1622 type.TypeArguments.Select (l => l.GetMetaInfo ()) :
1623 type.MemberDefinition.TypeParameters.Select (l => l.GetMetaInfo ()));
1626 definition = definition.GetDefinition ();
1627 type = type.DeclaringType;
1628 } while (type != null);
1630 return definition.GetMetaInfo ().MakeGenericType (all.ToArray ());
1633 public override ObsoleteAttribute GetAttributeObsolete ()
1635 return open_type.GetAttributeObsolete ();
1638 protected override bool IsNotCLSCompliant (out bool attrValue)
1640 if (base.IsNotCLSCompliant (out attrValue))
1643 foreach (var ta in TypeArguments) {
1644 if (ta.MemberDefinition.CLSAttributeValue == false)
1651 public override TypeSpec GetDefinition ()
1656 public override MetaType GetMetaInfo ()
1659 info = CreateMetaInfo (null);
1664 public override string GetSignatureForError ()
1667 return targs[0].GetSignatureForError () + "?";
1669 return base.GetSignatureForError ();
1672 protected override string GetTypeNameSignature ()
1674 if (targs.Length == 0 || MemberDefinition is AnonymousTypeClass)
1677 return "<" + TypeManager.CSharpName (targs) + ">";
1680 public bool HasDynamicArgument ()
1682 for (int i = 0; i < targs.Length; ++i) {
1683 var item = targs[i];
1685 if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1688 if (item is InflatedTypeSpec) {
1689 if (((InflatedTypeSpec) item).HasDynamicArgument ())
1696 while (item.IsArray) {
1697 item = ((ArrayContainer) item).Element;
1700 if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1708 protected override void InitializeMemberCache (bool onlyTypes)
1710 if (cache == null) {
1711 var open_cache = onlyTypes ? open_type.MemberCacheTypes : open_type.MemberCache;
1713 // Surprisingly, calling MemberCache on open type could meantime create cache on this type
1714 // for imported type parameter constraints referencing nested type of this declaration
1716 cache = new MemberCache (open_cache);
1719 var inflator = CreateLocalInflator (context);
1722 // Two stage inflate due to possible nested types recursive
1732 // When resolving type of `b' members of `B' cannot be
1733 // inflated because are not yet available in membercache
1735 if ((state & StateFlags.PendingMemberCacheMembers) == 0) {
1736 open_type.MemberCacheTypes.InflateTypes (cache, inflator);
1739 // Inflate any implemented interfaces
1741 if (open_type.Interfaces != null) {
1742 ifaces = new List<TypeSpec> (open_type.Interfaces.Count);
1743 foreach (var iface in open_type.Interfaces) {
1744 var iface_inflated = inflator.Inflate (iface);
1745 if (iface_inflated == null)
1748 AddInterface (iface_inflated);
1753 // Handles the tricky case of recursive nested base generic type
1755 // class A<T> : Base<A<T>.Nested> {
1759 // When inflating A<T>. base type is not yet known, secondary
1760 // inflation is required (not common case) once base scope
1763 if (open_type.BaseType == null) {
1765 state |= StateFlags.PendingBaseTypeInflate;
1767 BaseType = inflator.Inflate (open_type.BaseType);
1769 } else if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1770 BaseType = inflator.Inflate (open_type.BaseType);
1771 state &= ~StateFlags.PendingBaseTypeInflate;
1775 state |= StateFlags.PendingMemberCacheMembers;
1779 var tc = open_type.MemberDefinition as TypeContainer;
1780 if (tc != null && !tc.HasMembersDefined)
1781 throw new InternalErrorException ("Inflating MemberCache with undefined members");
1783 if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1784 BaseType = inflator.Inflate (open_type.BaseType);
1785 state &= ~StateFlags.PendingBaseTypeInflate;
1788 state &= ~StateFlags.PendingMemberCacheMembers;
1789 open_type.MemberCache.InflateMembers (cache, open_type, inflator);
1792 public override TypeSpec Mutate (TypeParameterMutator mutator)
1794 var targs = TypeArguments;
1796 targs = mutator.Mutate (targs);
1798 var decl = DeclaringType;
1799 if (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
1800 decl = mutator.Mutate (decl);
1802 if (targs == TypeArguments && decl == DeclaringType)
1805 var mutated = (InflatedTypeSpec) MemberwiseClone ();
1806 if (decl != DeclaringType) {
1807 // Gets back MethodInfo in case of metaInfo was inflated
1808 //mutated.info = MemberCache.GetMember<TypeSpec> (DeclaringType.GetDefinition (), this).info;
1810 mutated.declaringType = decl;
1811 mutated.state |= StateFlags.PendingMetaInflate;
1814 if (targs != null) {
1815 mutated.targs = targs;
1816 mutated.info = null;
1825 // Tracks the type arguments when instantiating a generic type. It's used
1826 // by both type arguments and type parameters
1828 public class TypeArguments
1830 List<FullNamedExpression> args;
1833 public TypeArguments (params FullNamedExpression[] types)
1835 this.args = new List<FullNamedExpression> (types);
1838 public void Add (FullNamedExpression type)
1843 // TODO: Kill this monster
1844 public TypeParameterName[] GetDeclarations ()
1846 return args.ConvertAll (i => (TypeParameterName) i).ToArray ();
1850 /// We may only be used after Resolve() is called and return the fully
1853 // TODO: Not needed, just return type from resolve
1854 public TypeSpec[] Arguments {
1869 public virtual bool IsEmpty {
1875 public string GetSignatureForError()
1877 StringBuilder sb = new StringBuilder ();
1878 for (int i = 0; i < Count; ++i) {
1881 sb.Append (expr.GetSignatureForError ());
1887 return sb.ToString ();
1891 /// Resolve the type arguments.
1893 public virtual bool Resolve (IMemberContext ec)
1896 return atypes.Length != 0;
1898 int count = args.Count;
1901 atypes = new TypeSpec [count];
1903 for (int i = 0; i < count; i++){
1904 var te = args[i].ResolveAsType (ec);
1913 ec.Module.Compiler.Report.Error (718, args[i].Location, "`{0}': static classes cannot be used as generic arguments",
1914 te.GetSignatureForError ());
1918 if (te.IsPointer || te.IsSpecialRuntimeType) {
1919 ec.Module.Compiler.Report.Error (306, args[i].Location,
1920 "The type `{0}' may not be used as a type argument",
1921 te.GetSignatureForError ());
1927 atypes = TypeSpec.EmptyTypes;
1932 public TypeArguments Clone ()
1934 TypeArguments copy = new TypeArguments ();
1935 foreach (var ta in args)
1942 public class UnboundTypeArguments : TypeArguments
1944 public UnboundTypeArguments (int arity)
1945 : base (new FullNamedExpression[arity])
1949 public override bool IsEmpty {
1955 public override bool Resolve (IMemberContext ec)
1957 // Nothing to be resolved
1962 public class TypeParameterName : SimpleName
1964 Attributes attributes;
1967 public TypeParameterName (string name, Attributes attrs, Location loc)
1968 : this (name, attrs, Variance.None, loc)
1972 public TypeParameterName (string name, Attributes attrs, Variance variance, Location loc)
1976 this.variance = variance;
1979 public Attributes OptAttributes {
1985 public Variance Variance {
1993 // A type expression of generic type with type arguments
1995 class GenericTypeExpr : TypeExpr
2001 /// Instantiate the generic type `t' with the type arguments `args'.
2002 /// Use this constructor if you already know the fully resolved
2005 public GenericTypeExpr (TypeSpec open_type, TypeArguments args, Location l)
2007 this.open_type = open_type;
2012 public TypeArguments TypeArguments {
2013 get { return args; }
2016 public override string GetSignatureForError ()
2018 return TypeManager.CSharpName (type);
2021 public override TypeSpec ResolveAsType (IMemberContext mc)
2023 if (eclass != ExprClass.Unresolved)
2026 if (!args.Resolve (mc))
2029 TypeSpec[] atypes = args.Arguments;
2032 // Now bind the parameters
2034 var inflated = open_type.MakeGenericType (mc, atypes);
2036 eclass = ExprClass.Type;
2039 // The constraints can be checked only when full type hierarchy is known
2041 if (!inflated.HasConstraintsChecked && mc.Module.HasTypesFullyDefined) {
2042 var constraints = inflated.Constraints;
2043 if (constraints != null) {
2044 var cc = new ConstraintChecker (mc);
2045 if (cc.CheckAll (open_type, atypes, constraints, loc)) {
2046 inflated.HasConstraintsChecked = true;
2054 public override bool Equals (object obj)
2056 GenericTypeExpr cobj = obj as GenericTypeExpr;
2060 if ((type == null) || (cobj.type == null))
2063 return type == cobj.type;
2066 public override int GetHashCode ()
2068 return base.GetHashCode ();
2073 // Generic type with unbound type arguments, used for typeof (G<,,>)
2075 class GenericOpenTypeExpr : TypeExpression
2077 public GenericOpenTypeExpr (TypeSpec type, /*UnboundTypeArguments args,*/ Location loc)
2078 : base (type.GetDefinition (), loc)
2083 struct ConstraintChecker
2086 bool ignore_inferred_dynamic;
2087 bool recursive_checks;
2089 public ConstraintChecker (IMemberContext ctx)
2092 ignore_inferred_dynamic = false;
2093 recursive_checks = false;
2098 public bool IgnoreInferredDynamic {
2100 return ignore_inferred_dynamic;
2103 ignore_inferred_dynamic = value;
2110 // Checks the constraints of open generic type against type
2111 // arguments. This version is used for types which could not be
2112 // checked immediatelly during construction because the type
2113 // hierarchy was not yet fully setup (before Emit phase)
2115 public static bool Check (IMemberContext mc, TypeSpec type, Location loc)
2118 // Check declaring type first if there is any
2120 if (type.DeclaringType != null && !Check (mc, type.DeclaringType, loc))
2123 while (type is ElementTypeSpec)
2124 type = ((ElementTypeSpec) type).Element;
2126 if (type.Arity == 0)
2129 var gtype = type as InflatedTypeSpec;
2133 var constraints = gtype.Constraints;
2134 if (constraints == null)
2137 if (gtype.HasConstraintsChecked)
2140 var cc = new ConstraintChecker (mc);
2141 cc.recursive_checks = true;
2143 if (cc.CheckAll (gtype.GetDefinition (), type.TypeArguments, constraints, loc)) {
2144 gtype.HasConstraintsChecked = true;
2152 // Checks all type arguments againts type parameters constraints
2153 // NOTE: It can run in probing mode when `mc' is null
2155 public bool CheckAll (MemberSpec context, TypeSpec[] targs, TypeParameterSpec[] tparams, Location loc)
2157 for (int i = 0; i < tparams.Length; i++) {
2158 if (ignore_inferred_dynamic && targs[i].BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2161 var targ = targs[i];
2162 if (!CheckConstraint (context, targ, tparams [i], loc))
2165 if (!recursive_checks)
2168 if (!Check (mc, targ, loc))
2175 bool CheckConstraint (MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, Location loc)
2178 // First, check the `class' and `struct' constraints.
2180 if (tparam.HasSpecialClass && !TypeSpec.IsReferenceType (atype)) {
2182 mc.Module.Compiler.Report.Error (452, loc,
2183 "The type `{0}' must be a reference type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
2184 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2190 if (tparam.HasSpecialStruct && (!TypeSpec.IsValueType (atype) || atype.IsNullableType)) {
2192 mc.Module.Compiler.Report.Error (453, loc,
2193 "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}'",
2194 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2203 // Check the class constraint
2205 if (tparam.HasTypeConstraint) {
2206 var dep = tparam.BaseType.GetMissingDependencies ();
2211 ImportedTypeDefinition.Error_MissingDependency (mc, dep, loc);
2215 if (!CheckConversion (mc, context, atype, tparam, tparam.BaseType, loc)) {
2224 // Check the interfaces constraints
2226 if (tparam.Interfaces != null) {
2227 if (atype.IsNullableType) {
2231 mc.Module.Compiler.Report.Error (313, loc,
2232 "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",
2233 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
2236 foreach (TypeSpec iface in tparam.Interfaces) {
2237 var dep = iface.GetMissingDependencies ();
2242 ImportedTypeDefinition.Error_MissingDependency (mc, dep, loc);
2245 // return immediately to avoid duplicate errors because we are scanning
2246 // expanded interface list
2250 if (!CheckConversion (mc, context, atype, tparam, iface, loc)) {
2261 // Check the type parameter constraint
2263 if (tparam.TypeArguments != null) {
2264 foreach (var ta in tparam.TypeArguments) {
2265 if (!CheckConversion (mc, context, atype, tparam, ta, loc)) {
2275 // Finally, check the constructor constraint.
2277 if (!tparam.HasSpecialConstructor)
2280 if (!HasDefaultConstructor (atype)) {
2282 mc.Module.Compiler.Report.SymbolRelatedToPreviousError (atype);
2283 mc.Module.Compiler.Report.Error (310, loc,
2284 "The type `{0}' must have a public parameterless constructor in order to use it as parameter `{1}' in the generic type or method `{2}'",
2285 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2293 static bool HasDynamicTypeArgument (TypeSpec[] targs)
2295 for (int i = 0; i < targs.Length; ++i) {
2296 var targ = targs [i];
2297 if (targ.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2300 if (HasDynamicTypeArgument (targ.TypeArguments))
2307 bool CheckConversion (IMemberContext mc, MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, TypeSpec ttype, Location loc)
2312 if (atype.IsGenericParameter) {
2313 var tps = (TypeParameterSpec) atype;
2314 if (Convert.ImplicitTypeParameterConversion (null, tps, ttype) != null)
2318 // LAMESPEC: Identity conversion with inflated type parameter
2319 // It's not clear from the spec what rule should apply to inherited
2320 // inflated type parameter. The specification allows only type parameter
2321 // conversion but that's clearly not enough
2323 if (tps.HasTypeConstraint && tps.BaseType == ttype)
2326 } else if (TypeSpec.IsValueType (atype)) {
2327 if (Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
2330 var expr = new EmptyExpression (atype);
2331 if (Convert.ImplicitStandardConversionExists (expr, ttype))
2336 // When partial/full type inference finds a dynamic type argument delay
2337 // the constraint check to runtime, it can succeed for real underlying
2340 if (ignore_inferred_dynamic && HasDynamicTypeArgument (ttype.TypeArguments))
2344 mc.Module.Compiler.Report.SymbolRelatedToPreviousError (tparam);
2345 if (atype.IsGenericParameter) {
2346 mc.Module.Compiler.Report.Error (314, loc,
2347 "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}'",
2348 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2349 } else if (TypeSpec.IsValueType (atype)) {
2350 mc.Module.Compiler.Report.Error (315, loc,
2351 "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}'",
2352 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2354 mc.Module.Compiler.Report.Error (311, loc,
2355 "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}'",
2356 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2363 bool HasDefaultConstructor (TypeSpec atype)
2365 var tp = atype as TypeParameterSpec;
2367 return tp.HasSpecialConstructor || tp.HasSpecialStruct;
2370 if (atype.IsStruct || atype.IsEnum)
2373 if (atype.IsAbstract)
2376 var tdef = atype.GetDefinition ();
2378 var found = MemberCache.FindMember (tdef,
2379 MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters),
2380 BindingRestriction.DeclaredOnly | BindingRestriction.InstanceOnly);
2382 return found != null && (found.Modifiers & Modifiers.PUBLIC) != 0;
2387 /// A generic method definition.
2389 public class GenericMethod : DeclSpace
2391 ParametersCompiled parameters;
2393 public GenericMethod (NamespaceContainer ns, DeclSpace parent, MemberName name,
2394 FullNamedExpression return_type, ParametersCompiled parameters)
2395 : base (ns, parent, name, null)
2397 this.parameters = parameters;
2400 public GenericMethod (NamespaceContainer ns, DeclSpace parent, MemberName name, TypeParameter[] tparams,
2401 FullNamedExpression return_type, ParametersCompiled parameters)
2402 : this (ns, parent, name, return_type, parameters)
2404 this.type_params = tparams;
2407 public override TypeParameter[] CurrentTypeParameters {
2409 return base.type_params;
2413 protected override TypeAttributes TypeAttr {
2415 throw new NotSupportedException ();
2419 public override void DefineType ()
2421 throw new Exception ();
2424 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2426 throw new NotSupportedException ();
2429 public override bool Define ()
2431 throw new NotSupportedException ();
2435 /// Define and resolve the type parameters.
2436 /// We're called from Method.Define().
2438 public bool Define (MethodOrOperator m)
2440 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
2441 string[] snames = new string [names.Length];
2442 var block = m.Block;
2443 for (int i = 0; i < names.Length; i++) {
2444 string type_argument_name = names[i].Name;
2446 if (block == null) {
2447 int idx = parameters.GetParameterIndexByName (type_argument_name);
2451 b = new ToplevelBlock (Compiler, Location);
2453 b.Error_AlreadyDeclaredTypeParameter (type_argument_name, parameters[i].Location);
2456 INamedBlockVariable variable = null;
2457 block.GetLocalName (type_argument_name, m.Block, ref variable);
2458 if (variable != null)
2459 variable.Block.Error_AlreadyDeclaredTypeParameter (type_argument_name, variable.Location);
2462 snames[i] = type_argument_name;
2465 GenericTypeParameterBuilder[] gen_params = m.MethodBuilder.DefineGenericParameters (snames);
2466 for (int i = 0; i < TypeParameters.Length; i++)
2467 TypeParameters [i].Define (gen_params [i], null);
2472 public void EmitAttributes ()
2474 if (OptAttributes != null)
2475 OptAttributes.Emit ();
2478 public override string GetSignatureForError ()
2480 return base.GetSignatureForError () + parameters.GetSignatureForError ();
2483 public override AttributeTargets AttributeTargets {
2485 return AttributeTargets.Method | AttributeTargets.ReturnValue;
2489 public override string DocCommentHeader {
2490 get { return "M:"; }
2493 public new void VerifyClsCompliance ()
2495 foreach (TypeParameter tp in TypeParameters) {
2496 tp.VerifyClsCompliance ();
2501 public partial class TypeManager
2503 public static Variance CheckTypeVariance (TypeSpec t, Variance expected, IMemberContext member)
2505 var tp = t as TypeParameterSpec;
2507 Variance v = tp.Variance;
2508 if (expected == Variance.None && v != expected ||
2509 expected == Variance.Covariant && v == Variance.Contravariant ||
2510 expected == Variance.Contravariant && v == Variance.Covariant) {
2511 ((TypeParameter)tp.MemberDefinition).ErrorInvalidVariance (member, expected);
2517 if (t.TypeArguments.Length > 0) {
2518 var targs_definition = t.MemberDefinition.TypeParameters;
2519 TypeSpec[] targs = GetTypeArguments (t);
2520 for (int i = 0; i < targs.Length; ++i) {
2521 Variance v = targs_definition[i].Variance;
2522 CheckTypeVariance (targs[i], (Variance) ((int)v * (int)expected), member);
2529 return CheckTypeVariance (GetElementType (t), expected, member);
2531 return Variance.None;
2536 // Implements C# type inference
2541 // Tracks successful rate of type inference
2543 int score = int.MaxValue;
2544 readonly Arguments arguments;
2545 readonly int arg_count;
2547 public TypeInference (Arguments arguments)
2549 this.arguments = arguments;
2550 if (arguments != null)
2551 arg_count = arguments.Count;
2554 public int InferenceScore {
2560 public TypeSpec[] InferMethodArguments (ResolveContext ec, MethodSpec method)
2562 var method_generic_args = method.GenericDefinition.TypeParameters;
2563 TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2564 if (!context.UnfixedVariableExists)
2565 return TypeSpec.EmptyTypes;
2567 AParametersCollection pd = method.Parameters;
2568 if (!InferInPhases (ec, context, pd))
2571 return context.InferredTypeArguments;
2575 // Implements method type arguments inference
2577 bool InferInPhases (ResolveContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
2579 int params_arguments_start;
2580 if (methodParameters.HasParams) {
2581 params_arguments_start = methodParameters.Count - 1;
2583 params_arguments_start = arg_count;
2586 TypeSpec [] ptypes = methodParameters.Types;
2589 // The first inference phase
2591 TypeSpec method_parameter = null;
2592 for (int i = 0; i < arg_count; i++) {
2593 Argument a = arguments [i];
2597 if (i < params_arguments_start) {
2598 method_parameter = methodParameters.Types [i];
2599 } else if (i == params_arguments_start) {
2600 if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2601 method_parameter = methodParameters.Types [params_arguments_start];
2603 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2605 ptypes = (TypeSpec[]) ptypes.Clone ();
2606 ptypes [i] = method_parameter;
2610 // When a lambda expression, an anonymous method
2611 // is used an explicit argument type inference takes a place
2613 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2615 if (am.ExplicitTypeInference (ec, tic, method_parameter))
2621 score -= tic.ExactInference (a.Type, method_parameter);
2625 if (a.Expr.Type == InternalType.NullLiteral)
2628 if (TypeSpec.IsValueType (method_parameter)) {
2629 score -= tic.LowerBoundInference (a.Type, method_parameter);
2634 // Otherwise an output type inference is made
2636 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2640 // Part of the second phase but because it happens only once
2641 // we don't need to call it in cycle
2643 bool fixed_any = false;
2644 if (!tic.FixIndependentTypeArguments (ec, ptypes, ref fixed_any))
2647 return DoSecondPhase (ec, tic, ptypes, !fixed_any);
2650 bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, TypeSpec[] methodParameters, bool fixDependent)
2652 bool fixed_any = false;
2653 if (fixDependent && !tic.FixDependentTypes (ec, ref fixed_any))
2656 // If no further unfixed type variables exist, type inference succeeds
2657 if (!tic.UnfixedVariableExists)
2660 if (!fixed_any && fixDependent)
2663 // For all arguments where the corresponding argument output types
2664 // contain unfixed type variables but the input types do not,
2665 // an output type inference is made
2666 for (int i = 0; i < arg_count; i++) {
2668 // Align params arguments
2669 TypeSpec t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
2671 if (!TypeManager.IsDelegateType (t_i)) {
2672 if (!t_i.IsExpressionTreeType)
2675 t_i = TypeManager.GetTypeArguments (t_i) [0];
2678 var mi = Delegate.GetInvokeMethod (t_i);
2679 TypeSpec rtype = mi.ReturnType;
2681 if (tic.IsReturnTypeNonDependent (ec, mi, rtype))
2682 score -= tic.OutputTypeInference (ec, arguments [i].Expr, t_i);
2686 return DoSecondPhase (ec, tic, methodParameters, true);
2690 public class TypeInferenceContext
2692 protected enum BoundKind
2699 protected class BoundInfo : IEquatable<BoundInfo>
2701 public readonly TypeSpec Type;
2702 public readonly BoundKind Kind;
2704 public BoundInfo (TypeSpec type, BoundKind kind)
2710 public override int GetHashCode ()
2712 return Type.GetHashCode ();
2715 public virtual Expression GetTypeExpression ()
2717 return new TypeExpression (Type, Location.Null);
2720 #region IEquatable<BoundInfo> Members
2722 public virtual bool Equals (BoundInfo other)
2724 return Type == other.Type && Kind == other.Kind;
2730 readonly TypeSpec[] tp_args;
2731 readonly TypeSpec[] fixed_types;
2732 readonly List<BoundInfo>[] bounds;
2735 // TODO MemberCache: Could it be TypeParameterSpec[] ??
2736 public TypeInferenceContext (TypeSpec[] typeArguments)
2738 if (typeArguments.Length == 0)
2739 throw new ArgumentException ("Empty generic arguments");
2741 fixed_types = new TypeSpec [typeArguments.Length];
2742 for (int i = 0; i < typeArguments.Length; ++i) {
2743 if (typeArguments [i].IsGenericParameter) {
2744 if (bounds == null) {
2745 bounds = new List<BoundInfo> [typeArguments.Length];
2746 tp_args = new TypeSpec [typeArguments.Length];
2748 tp_args [i] = typeArguments [i];
2750 fixed_types [i] = typeArguments [i];
2756 // Used together with AddCommonTypeBound fo implement
2757 // 7.4.2.13 Finding the best common type of a set of expressions
2759 public TypeInferenceContext ()
2761 fixed_types = new TypeSpec [1];
2762 tp_args = new TypeSpec [1];
2763 tp_args[0] = InternalType.Arglist; // it can be any internal type
2764 bounds = new List<BoundInfo> [1];
2767 public TypeSpec[] InferredTypeArguments {
2773 public void AddCommonTypeBound (TypeSpec type)
2775 AddToBounds (new BoundInfo (type, BoundKind.Lower), 0);
2778 protected void AddToBounds (BoundInfo bound, int index)
2781 // Some types cannot be used as type arguments
2783 if (bound.Type.Kind == MemberKind.Void || bound.Type.IsPointer || bound.Type.IsSpecialRuntimeType ||
2784 bound.Type == InternalType.MethodGroup || bound.Type == InternalType.AnonymousMethod)
2787 var a = bounds [index];
2789 a = new List<BoundInfo> (2);
2795 if (a.Contains (bound))
2801 bool AllTypesAreFixed (TypeSpec[] types)
2803 foreach (TypeSpec t in types) {
2804 if (t.IsGenericParameter) {
2810 if (TypeManager.IsGenericType (t))
2811 return AllTypesAreFixed (TypeManager.GetTypeArguments (t));
2818 // 26.3.3.8 Exact Inference
2820 public int ExactInference (TypeSpec u, TypeSpec v)
2822 // If V is an array type
2827 // TODO MemberCache: GetMetaInfo ()
2828 if (u.GetMetaInfo ().GetArrayRank () != v.GetMetaInfo ().GetArrayRank ())
2831 return ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
2834 // If V is constructed type and U is constructed type
2835 if (TypeManager.IsGenericType (v)) {
2836 if (!TypeManager.IsGenericType (u))
2839 TypeSpec [] ga_u = TypeManager.GetTypeArguments (u);
2840 TypeSpec [] ga_v = TypeManager.GetTypeArguments (v);
2841 if (ga_u.Length != ga_v.Length)
2845 for (int i = 0; i < ga_u.Length; ++i)
2846 score += ExactInference (ga_u [i], ga_v [i]);
2848 return score > 0 ? 1 : 0;
2851 // If V is one of the unfixed type arguments
2852 int pos = IsUnfixed (v);
2856 AddToBounds (new BoundInfo (u, BoundKind.Exact), pos);
2860 public bool FixAllTypes (ResolveContext ec)
2862 for (int i = 0; i < tp_args.Length; ++i) {
2863 if (!FixType (ec, i))
2870 // All unfixed type variables Xi are fixed for which all of the following hold:
2871 // a, There is at least one type variable Xj that depends on Xi
2872 // b, Xi has a non-empty set of bounds
2874 public bool FixDependentTypes (ResolveContext ec, ref bool fixed_any)
2876 for (int i = 0; i < tp_args.Length; ++i) {
2877 if (fixed_types[i] != null)
2880 if (bounds[i] == null)
2883 if (!FixType (ec, i))
2893 // All unfixed type variables Xi which depend on no Xj are fixed
2895 public bool FixIndependentTypeArguments (ResolveContext ec, TypeSpec[] methodParameters, ref bool fixed_any)
2897 var types_to_fix = new List<TypeSpec> (tp_args);
2898 for (int i = 0; i < methodParameters.Length; ++i) {
2899 TypeSpec t = methodParameters[i];
2901 if (!TypeManager.IsDelegateType (t)) {
2902 if (!t.IsExpressionTreeType)
2905 t = TypeManager.GetTypeArguments (t) [0];
2908 if (t.IsGenericParameter)
2911 var invoke = Delegate.GetInvokeMethod (t);
2912 TypeSpec rtype = invoke.ReturnType;
2913 while (rtype.IsArray)
2914 rtype = ((ArrayContainer) rtype).Element;
2916 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
2919 // Remove dependent types, they cannot be fixed yet
2920 RemoveDependentTypes (types_to_fix, rtype);
2923 foreach (TypeSpec t in types_to_fix) {
2927 int idx = IsUnfixed (t);
2928 if (idx >= 0 && !FixType (ec, idx)) {
2933 fixed_any = types_to_fix.Count > 0;
2940 public bool FixType (ResolveContext ec, int i)
2942 // It's already fixed
2943 if (fixed_types[i] != null)
2944 throw new InternalErrorException ("Type argument has been already fixed");
2949 var candidates = bounds [i];
2950 if (candidates == null)
2953 if (candidates.Count == 1) {
2954 TypeSpec t = candidates[0].Type;
2955 if (t == InternalType.NullLiteral)
2958 fixed_types [i] = t;
2963 // Determines a unique type from which there is
2964 // a standard implicit conversion to all the other
2967 TypeSpec best_candidate = null;
2969 int candidates_count = candidates.Count;
2970 for (int ci = 0; ci < candidates_count; ++ci) {
2971 BoundInfo bound = candidates [ci];
2972 for (cii = 0; cii < candidates_count; ++cii) {
2976 BoundInfo cbound = candidates[cii];
2978 // Same type parameters with different bounds
2979 if (cbound.Type == bound.Type) {
2980 if (bound.Kind != BoundKind.Exact)
2986 if (bound.Kind == BoundKind.Exact || cbound.Kind == BoundKind.Exact) {
2987 if (cbound.Kind == BoundKind.Lower) {
2988 if (!Convert.ImplicitConversionExists (ec, cbound.GetTypeExpression (), bound.Type)) {
2994 if (cbound.Kind == BoundKind.Upper) {
2995 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
3002 if (bound.Kind != BoundKind.Exact) {
3003 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
3014 if (bound.Kind == BoundKind.Lower) {
3015 if (cbound.Kind == BoundKind.Lower) {
3016 if (!Convert.ImplicitConversionExists (ec, cbound.GetTypeExpression (), bound.Type)) {
3020 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
3030 if (bound.Kind == BoundKind.Upper) {
3031 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
3035 throw new NotImplementedException ("variance conversion");
3039 if (cii != candidates_count)
3043 // We already have the best candidate, break if thet are different
3045 // Dynamic is never ambiguous as we prefer dynamic over other best candidate types
3047 if (best_candidate != null) {
3049 if (best_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3052 if (bound.Type.BuiltinType != BuiltinTypeSpec.Type.Dynamic && best_candidate != bound.Type)
3056 best_candidate = bound.Type;
3059 if (best_candidate == null)
3062 fixed_types[i] = best_candidate;
3066 public bool HasBounds (int pos)
3068 return bounds[pos] != null;
3072 // Uses inferred or partially infered types to inflate delegate type argument. Returns
3073 // null when type parameter has not been fixed
3075 public TypeSpec InflateGenericArgument (IModuleContext context, TypeSpec parameter)
3077 var tp = parameter as TypeParameterSpec;
3080 // Type inference works on generic arguments (MVAR) only
3082 if (!tp.IsMethodOwned)
3086 // Ensure the type parameter belongs to same container
3088 if (tp.DeclaredPosition < tp_args.Length && tp_args[tp.DeclaredPosition] == parameter)
3089 return fixed_types[tp.DeclaredPosition] ?? parameter;
3094 var gt = parameter as InflatedTypeSpec;
3096 var inflated_targs = new TypeSpec [gt.TypeArguments.Length];
3097 for (int ii = 0; ii < inflated_targs.Length; ++ii) {
3098 var inflated = InflateGenericArgument (context, gt.TypeArguments [ii]);
3099 if (inflated == null)
3102 inflated_targs[ii] = inflated;
3105 return gt.GetDefinition ().MakeGenericType (context, inflated_targs);
3112 // Tests whether all delegate input arguments are fixed and generic output type
3113 // requires output type inference
3115 public bool IsReturnTypeNonDependent (ResolveContext ec, MethodSpec invoke, TypeSpec returnType)
3117 while (returnType.IsArray)
3118 returnType = ((ArrayContainer) returnType).Element;
3120 if (returnType.IsGenericParameter) {
3121 if (IsFixed (returnType))
3123 } else if (TypeManager.IsGenericType (returnType)) {
3124 if (TypeManager.IsDelegateType (returnType)) {
3125 invoke = Delegate.GetInvokeMethod (returnType);
3126 return IsReturnTypeNonDependent (ec, invoke, invoke.ReturnType);
3129 TypeSpec[] g_args = TypeManager.GetTypeArguments (returnType);
3131 // At least one unfixed return type has to exist
3132 if (AllTypesAreFixed (g_args))
3138 // All generic input arguments have to be fixed
3139 AParametersCollection d_parameters = invoke.Parameters;
3140 return AllTypesAreFixed (d_parameters.Types);
3143 bool IsFixed (TypeSpec type)
3145 return IsUnfixed (type) == -1;
3148 int IsUnfixed (TypeSpec type)
3150 if (!type.IsGenericParameter)
3153 for (int i = 0; i < tp_args.Length; ++i) {
3154 if (tp_args[i] == type) {
3155 if (fixed_types[i] != null)
3166 // 26.3.3.9 Lower-bound Inference
3168 public int LowerBoundInference (TypeSpec u, TypeSpec v)
3170 return LowerBoundInference (u, v, false);
3174 // Lower-bound (false) or Upper-bound (true) inference based on inversed argument
3176 int LowerBoundInference (TypeSpec u, TypeSpec v, bool inversed)
3178 // If V is one of the unfixed type arguments
3179 int pos = IsUnfixed (v);
3181 AddToBounds (new BoundInfo (u, inversed ? BoundKind.Upper : BoundKind.Lower), pos);
3185 // If U is an array type
3186 var u_ac = u as ArrayContainer;
3188 var v_ac = v as ArrayContainer;
3190 if (u_ac.Rank != v_ac.Rank)
3193 if (TypeSpec.IsValueType (u_ac.Element))
3194 return ExactInference (u_ac.Element, v_ac.Element);
3196 return LowerBoundInference (u_ac.Element, v_ac.Element, inversed);
3199 if (u_ac.Rank != 1 || !v.IsGenericIterateInterface)
3202 var v_i = TypeManager.GetTypeArguments (v) [0];
3203 if (TypeSpec.IsValueType (u_ac.Element))
3204 return ExactInference (u_ac.Element, v_i);
3206 return LowerBoundInference (u_ac.Element, v_i);
3209 if (TypeManager.IsGenericType (v)) {
3211 // if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
3212 // such that U is identical to, inherits from (directly or indirectly),
3213 // or implements (directly or indirectly) C<U1..Uk>
3215 var u_candidates = new List<TypeSpec> ();
3216 var open_v = v.MemberDefinition;
3218 for (TypeSpec t = u; t != null; t = t.BaseType) {
3219 if (open_v == t.MemberDefinition)
3220 u_candidates.Add (t);
3223 // Using this trick for dynamic type inference, the spec says the type arguments are "unknown" but
3224 // that would complicate the process a lot, instead I treat them as dynamic
3226 if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3227 u_candidates.Add (t);
3229 if (t.Interfaces != null) {
3230 foreach (var iface in t.Interfaces) {
3231 if (open_v == iface.MemberDefinition)
3232 u_candidates.Add (iface);
3237 TypeSpec [] unique_candidate_targs = null;
3238 TypeSpec[] ga_v = TypeManager.GetTypeArguments (v);
3239 foreach (TypeSpec u_candidate in u_candidates) {
3241 // The unique set of types U1..Uk means that if we have an interface I<T>,
3242 // class U : I<int>, I<long> then no type inference is made when inferring
3243 // type I<T> by applying type U because T could be int or long
3245 if (unique_candidate_targs != null) {
3246 TypeSpec[] second_unique_candidate_targs = TypeManager.GetTypeArguments (u_candidate);
3247 if (TypeSpecComparer.Equals (unique_candidate_targs, second_unique_candidate_targs)) {
3248 unique_candidate_targs = second_unique_candidate_targs;
3253 // This should always cause type inference failure
3260 // A candidate is dynamic type expression, to simplify things use dynamic
3261 // for all type parameter of this type. For methods like this one
3263 // void M<T, U> (IList<T>, IList<U[]>)
3265 // dynamic becomes both T and U when the arguments are of dynamic type
3267 if (u_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
3268 unique_candidate_targs = new TypeSpec[ga_v.Length];
3269 for (int i = 0; i < unique_candidate_targs.Length; ++i)
3270 unique_candidate_targs[i] = u_candidate;
3272 unique_candidate_targs = TypeManager.GetTypeArguments (u_candidate);
3276 if (unique_candidate_targs != null) {
3277 var ga_open_v = open_v.TypeParameters;
3279 for (int i = 0; i < unique_candidate_targs.Length; ++i) {
3280 Variance variance = ga_open_v [i].Variance;
3282 TypeSpec u_i = unique_candidate_targs [i];
3283 if (variance == Variance.None || TypeSpec.IsValueType (u_i)) {
3284 if (ExactInference (u_i, ga_v [i]) == 0)
3287 bool upper_bound = (variance == Variance.Contravariant && !inversed) ||
3288 (variance == Variance.Covariant && inversed);
3290 if (LowerBoundInference (u_i, ga_v [i], upper_bound) == 0)
3302 // 26.3.3.6 Output Type Inference
3304 public int OutputTypeInference (ResolveContext ec, Expression e, TypeSpec t)
3306 // If e is a lambda or anonymous method with inferred return type
3307 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
3309 TypeSpec rt = ame.InferReturnType (ec, this, t);
3310 var invoke = Delegate.GetInvokeMethod (t);
3313 AParametersCollection pd = invoke.Parameters;
3314 return ame.Parameters.Count == pd.Count ? 1 : 0;
3317 TypeSpec rtype = invoke.ReturnType;
3318 return LowerBoundInference (rt, rtype) + 1;
3322 // if E is a method group and T is a delegate type or expression tree type
3323 // return type Tb with parameter types T1..Tk and return type Tb, and overload
3324 // resolution of E with the types T1..Tk yields a single method with return type U,
3325 // then a lower-bound inference is made from U for Tb.
3327 if (e is MethodGroupExpr) {
3328 if (!TypeManager.IsDelegateType (t)) {
3329 if (!t.IsExpressionTreeType)
3332 t = TypeManager.GetTypeArguments (t)[0];
3335 var invoke = Delegate.GetInvokeMethod (t);
3336 TypeSpec rtype = invoke.ReturnType;
3338 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
3341 // LAMESPEC: Standard does not specify that all methodgroup arguments
3342 // has to be fixed but it does not specify how to do recursive type inference
3343 // either. We choose the simple option and infer return type only
3344 // if all delegate generic arguments are fixed.
3345 TypeSpec[] param_types = new TypeSpec [invoke.Parameters.Count];
3346 for (int i = 0; i < param_types.Length; ++i) {
3347 var inflated = InflateGenericArgument (ec, invoke.Parameters.Types[i]);
3348 if (inflated == null)
3351 if (IsUnfixed (inflated) >= 0)
3354 param_types[i] = inflated;
3357 MethodGroupExpr mg = (MethodGroupExpr) e;
3358 Arguments args = DelegateCreation.CreateDelegateMethodArguments (invoke.Parameters, param_types, e.Location);
3359 mg = mg.OverloadResolve (ec, ref args, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
3363 return LowerBoundInference (mg.BestCandidateReturnType, rtype) + 1;
3367 // if e is an expression with type U, then
3368 // a lower-bound inference is made from U for T
3370 return LowerBoundInference (e.Type, t) * 2;
3373 void RemoveDependentTypes (List<TypeSpec> types, TypeSpec returnType)
3375 int idx = IsUnfixed (returnType);
3381 if (TypeManager.IsGenericType (returnType)) {
3382 foreach (TypeSpec t in TypeManager.GetTypeArguments (returnType)) {
3383 RemoveDependentTypes (types, t);
3388 public bool UnfixedVariableExists {
3390 foreach (TypeSpec ut in fixed_types) {