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 public bool IsMethodTypeParameter {
421 return spec.IsMethodOwned;
427 return MemberName.Name;
431 public string Namespace {
437 public TypeParameterSpec Type {
443 public int TypeParametersCount {
449 public TypeParameterSpec[] TypeParameters {
455 public override string[] ValidAttributeTargets {
457 return attribute_target;
461 public Variance Variance {
463 return spec.Variance;
470 // This is called for each part of a partial generic type definition.
472 // If partial type parameters constraints are not null and we don't
473 // already have constraints they become our constraints. If we already
474 // have constraints, we must check that they're the same.
476 public bool AddPartialConstraints (TypeContainer part, TypeParameter tp)
479 throw new InvalidOperationException ();
481 var new_constraints = tp.constraints;
482 if (new_constraints == null)
485 // TODO: could create spec only
486 //tp.Define (null, -1, part.Definition);
487 tp.spec.DeclaringType = part.Definition;
488 if (!tp.ResolveConstraints (part))
491 if (constraints != null)
492 return spec.HasSameConstraintsDefinition (tp.Type);
494 // Copy constraint from resolved part to partial container
495 spec.SpecialConstraint = tp.spec.SpecialConstraint;
496 spec.InterfacesDefined = tp.spec.InterfacesDefined;
497 spec.TypeArguments = tp.spec.TypeArguments;
498 spec.BaseType = tp.spec.BaseType;
503 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
505 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
508 public void CheckGenericConstraints (bool obsoleteCheck)
510 if (constraints != null)
511 constraints.CheckGenericConstraints (this, obsoleteCheck);
514 public TypeParameter CreateHoistedCopy (TypeSpec declaringSpec)
516 return new TypeParameter (spec, declaringSpec, MemberName, null);
519 public override bool Define ()
525 // This is the first method which is called during the resolving
526 // process; we're called immediately after creating the type parameters
527 // with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
530 public void Define (GenericTypeParameterBuilder type, TypeSpec declaringType, TypeContainer parent)
533 throw new InternalErrorException ();
535 // Needed to get compiler reference
536 this.Parent = parent;
538 spec.DeclaringType = declaringType;
539 spec.SetMetaInfo (type);
542 public void EmitConstraints (GenericTypeParameterBuilder builder)
544 var attr = GenericParameterAttributes.None;
545 if (spec.Variance == Variance.Contravariant)
546 attr |= GenericParameterAttributes.Contravariant;
547 else if (spec.Variance == Variance.Covariant)
548 attr |= GenericParameterAttributes.Covariant;
550 if (spec.HasSpecialClass)
551 attr |= GenericParameterAttributes.ReferenceTypeConstraint;
552 else if (spec.HasSpecialStruct)
553 attr |= GenericParameterAttributes.NotNullableValueTypeConstraint | GenericParameterAttributes.DefaultConstructorConstraint;
555 if (spec.HasSpecialConstructor)
556 attr |= GenericParameterAttributes.DefaultConstructorConstraint;
558 if (spec.BaseType.BuiltinType != BuiltinTypeSpec.Type.Object)
559 builder.SetBaseTypeConstraint (spec.BaseType.GetMetaInfo ());
561 if (spec.InterfacesDefined != null)
562 builder.SetInterfaceConstraints (spec.InterfacesDefined.Select (l => l.GetMetaInfo ()).ToArray ());
564 if (spec.TypeArguments != null)
565 builder.SetInterfaceConstraints (spec.TypeArguments.Select (l => l.GetMetaInfo ()).ToArray ());
567 builder.SetGenericParameterAttributes (attr);
570 public override void Emit ()
572 EmitConstraints (builder);
574 if (OptAttributes != null)
575 OptAttributes.Emit ();
580 public void ErrorInvalidVariance (IMemberContext mc, Variance expected)
582 Report.SymbolRelatedToPreviousError (mc.CurrentMemberDefinition);
583 string input_variance = Variance == Variance.Contravariant ? "contravariant" : "covariant";
584 string gtype_variance;
586 case Variance.Contravariant: gtype_variance = "contravariantly"; break;
587 case Variance.Covariant: gtype_variance = "covariantly"; break;
588 default: gtype_variance = "invariantly"; break;
591 Delegate d = mc as Delegate;
592 string parameters = d != null ? d.Parameters.GetSignatureForError () : "";
594 Report.Error (1961, Location,
595 "The {2} type parameter `{0}' must be {3} valid on `{1}{4}'",
596 GetSignatureForError (), mc.GetSignatureForError (), input_variance, gtype_variance, parameters);
599 public TypeSpec GetAttributeCoClass ()
604 public string GetAttributeDefaultMember ()
606 throw new NotSupportedException ();
609 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
611 throw new NotSupportedException ();
614 public override string GetSignatureForDocumentation ()
616 throw new NotImplementedException ();
619 public override string GetSignatureForError ()
621 return MemberName.Name;
624 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
626 return spec.MemberDefinition.DeclaringAssembly == assembly;
629 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
631 throw new NotSupportedException ("Not supported for compiled definition");
635 // Resolves all type parameter constraints
637 public bool ResolveConstraints (IMemberContext context)
639 if (constraints != null)
640 return constraints.Resolve (context, this);
642 if (spec.BaseType == null)
643 spec.BaseType = context.Module.Compiler.BuiltinTypes.Object;
648 public override bool IsClsComplianceRequired ()
653 public new void VerifyClsCompliance ()
655 if (constraints != null)
656 constraints.VerifyClsCompliance (Report);
659 public void WarningParentNameConflict (TypeParameter conflict)
661 conflict.Report.SymbolRelatedToPreviousError (conflict.Location, null);
662 conflict.Report.Warning (693, 3, Location,
663 "Type parameter `{0}' has the same name as the type parameter from outer type `{1}'",
664 GetSignatureForError (), conflict.CurrentType.GetSignatureForError ());
668 [System.Diagnostics.DebuggerDisplay ("{DisplayDebugInfo()}")]
669 public class TypeParameterSpec : TypeSpec
671 public static readonly new TypeParameterSpec[] EmptyTypes = new TypeParameterSpec[0];
674 SpecialConstraint spec;
677 TypeSpec[] ifaces_defined;
680 // Creates type owned type parameter
682 public TypeParameterSpec (TypeSpec declaringType, int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
683 : base (MemberKind.TypeParameter, declaringType, definition, info, Modifiers.PUBLIC)
685 this.variance = variance;
687 state &= ~StateFlags.Obsolete_Undetected;
692 // Creates method owned type parameter
694 public TypeParameterSpec (int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
695 : this (null, index, definition, spec, variance, info)
701 public int DeclaredPosition {
710 public bool HasSpecialConstructor {
712 return (spec & SpecialConstraint.Constructor) != 0;
716 public bool HasSpecialClass {
718 return (spec & SpecialConstraint.Class) != 0;
722 public bool HasSpecialStruct {
724 return (spec & SpecialConstraint.Struct) != 0;
728 public bool HasTypeConstraint {
730 var bt = BaseType.BuiltinType;
731 return bt != BuiltinTypeSpec.Type.Object && bt != BuiltinTypeSpec.Type.ValueType;
735 public override IList<TypeSpec> Interfaces {
737 if ((state & StateFlags.InterfacesExpanded) == 0) {
738 if (ifaces != null) {
739 for (int i = 0; i < ifaces.Count; ++i ) {
740 var iface_type = ifaces[i];
741 if (iface_type.Interfaces != null) {
742 if (ifaces_defined == null)
743 ifaces_defined = ifaces.ToArray ();
745 for (int ii = 0; ii < iface_type.Interfaces.Count; ++ii) {
746 var ii_iface_type = iface_type.Interfaces [ii];
748 AddInterface (ii_iface_type);
754 if (ifaces_defined == null)
755 ifaces_defined = ifaces == null ? TypeSpec.EmptyTypes : ifaces.ToArray ();
757 state |= StateFlags.InterfacesExpanded;
765 // Unexpanded interfaces list
767 public TypeSpec[] InterfacesDefined {
769 if (ifaces_defined == null) {
773 ifaces_defined = ifaces.ToArray ();
776 return ifaces_defined.Length == 0 ? null : ifaces_defined;
779 ifaces_defined = value;
780 if (value != null && value.Length != 0)
785 public bool IsConstrained {
787 return spec != SpecialConstraint.None || ifaces != null || targs != null || HasTypeConstraint;
792 // Returns whether the type parameter is known to be a reference type
794 public new bool IsReferenceType {
796 if ((spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0)
797 return (spec & SpecialConstraint.Class) != 0;
800 // Full check is needed (see IsValueType for details)
802 if (HasTypeConstraint && TypeSpec.IsReferenceType (BaseType))
806 foreach (var ta in targs) {
808 // Secondary special constraints are ignored (I am not sure why)
810 var tp = ta as TypeParameterSpec;
811 if (tp != null && (tp.spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0)
814 if (TypeSpec.IsReferenceType (ta))
824 // Returns whether the type parameter is known to be a value type
826 public new bool IsValueType {
829 // Even if structs/enums cannot be used directly as constraints
830 // they can apear as constraint type when inheriting base constraint
831 // which has dependant type parameter constraint which has been
832 // inflated using value type
834 // class A : B<int> { override void Foo<U> () {} }
835 // class B<T> { virtual void Foo<U> () where U : T {} }
837 if (HasSpecialStruct)
841 foreach (var ta in targs) {
842 if (TypeSpec.IsValueType (ta))
851 public override string Name {
853 return definition.Name;
857 public bool IsMethodOwned {
859 return DeclaringType == null;
863 public SpecialConstraint SpecialConstraint {
873 // Types used to inflate the generic type
875 public new TypeSpec[] TypeArguments {
884 public Variance Variance {
892 public string DisplayDebugInfo ()
894 var s = GetSignatureForError ();
895 return IsMethodOwned ? s + "!!" : s + "!";
899 // Finds effective base class. The effective base class is always a class-type
901 public TypeSpec GetEffectiveBase ()
903 if (HasSpecialStruct)
907 // If T has a class-type constraint C but no type-parameter constraints, its effective base class is C
909 if (BaseType != null && targs == null) {
911 // 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.
913 // LAMESPEC: Is System.ValueType always the most specific base type in this case?
915 // Note: This can never happen in an explicitly given constraint, but may occur when the constraints of a generic method
916 // are implicitly inherited by an overriding method declaration or an explicit implementation of an interface method.
918 return BaseType.IsStruct ? BaseType.BaseType : BaseType;
922 if (HasTypeConstraint) {
923 Array.Resize (ref types, types.Length + 1);
925 for (int i = 0; i < types.Length - 1; ++i) {
926 types[i] = types[i].BaseType;
929 types[types.Length - 1] = BaseType;
931 types = types.Select (l => l.BaseType).ToArray ();
935 return Convert.FindMostEncompassedType (types);
940 public override string GetSignatureForDocumentation ()
942 var prefix = IsMethodOwned ? "``" : "`";
943 return prefix + DeclaredPosition;
946 public override string GetSignatureForError ()
952 // Constraints have to match by definition but not position, used by
953 // partial classes or methods
955 public bool HasSameConstraintsDefinition (TypeParameterSpec other)
957 if (spec != other.spec)
960 if (BaseType != other.BaseType)
963 if (!TypeSpecComparer.Override.IsSame (InterfacesDefined, other.InterfacesDefined))
966 if (!TypeSpecComparer.Override.IsSame (targs, other.targs))
973 // Constraints have to match by using same set of types, used by
974 // implicit interface implementation
976 public bool HasSameConstraintsImplementation (TypeParameterSpec other)
978 if (spec != other.spec)
982 // It can be same base type or inflated type parameter
984 // interface I<T> { void Foo<U> where U : T; }
985 // class A : I<int> { void Foo<X> where X : int {} }
988 if (!TypeSpecComparer.Override.IsEqual (BaseType, other.BaseType)) {
989 if (other.targs == null)
993 foreach (var otarg in other.targs) {
994 if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
1004 // Check interfaces implementation -> definition
1005 if (InterfacesDefined != null) {
1007 // Iterate over inflated interfaces
1009 foreach (var iface in Interfaces) {
1011 if (other.InterfacesDefined != null) {
1012 foreach (var oiface in other.Interfaces) {
1013 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
1023 if (other.targs != null) {
1024 foreach (var otarg in other.targs) {
1025 if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
1037 // Check interfaces implementation <- definition
1038 if (other.InterfacesDefined != null) {
1039 if (InterfacesDefined == null)
1043 // Iterate over inflated interfaces
1045 foreach (var oiface in other.Interfaces) {
1047 foreach (var iface in Interfaces) {
1048 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
1059 // Check type parameters implementation -> definition
1060 if (targs != null) {
1061 if (other.targs == null)
1064 foreach (var targ in targs) {
1066 foreach (var otarg in other.targs) {
1067 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
1078 // Check type parameters implementation <- definition
1079 if (other.targs != null) {
1080 foreach (var otarg in other.targs) {
1081 // Ignore inflated type arguments, were checked above
1082 if (!otarg.IsGenericParameter)
1089 foreach (var targ in targs) {
1090 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
1104 public static TypeParameterSpec[] InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec[] tparams)
1106 return InflateConstraints (tparams, l => l, inflator);
1109 public static TypeParameterSpec[] InflateConstraints<T> (TypeParameterSpec[] tparams, Func<T, TypeParameterInflator> inflatorFactory, T arg)
1111 TypeParameterSpec[] constraints = null;
1112 TypeParameterInflator? inflator = null;
1114 for (int i = 0; i < tparams.Length; ++i) {
1115 var tp = tparams[i];
1116 if (tp.HasTypeConstraint || tp.InterfacesDefined != null || tp.TypeArguments != null) {
1117 if (constraints == null) {
1118 constraints = new TypeParameterSpec[tparams.Length];
1119 Array.Copy (tparams, constraints, constraints.Length);
1123 // Using a factory to avoid possibly expensive inflator build up
1125 if (inflator == null)
1126 inflator = inflatorFactory (arg);
1128 constraints[i] = (TypeParameterSpec) constraints[i].InflateMember (inflator.Value);
1132 if (constraints == null)
1133 constraints = tparams;
1138 public void InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec tps)
1140 tps.BaseType = inflator.Inflate (BaseType);
1141 if (ifaces != null) {
1142 tps.ifaces = new List<TypeSpec> (ifaces.Count);
1143 for (int i = 0; i < ifaces.Count; ++i)
1144 tps.ifaces.Add (inflator.Inflate (ifaces[i]));
1147 if (targs != null) {
1148 tps.targs = new TypeSpec[targs.Length];
1149 for (int i = 0; i < targs.Length; ++i)
1150 tps.targs[i] = inflator.Inflate (targs[i]);
1154 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1156 var tps = (TypeParameterSpec) MemberwiseClone ();
1157 InflateConstraints (inflator, tps);
1162 // Populates type parameter members using type parameter constraints
1163 // The trick here is to be called late enough but not too late to
1164 // populate member cache with all members from other types
1166 protected override void InitializeMemberCache (bool onlyTypes)
1168 cache = new MemberCache ();
1171 // For a type parameter the membercache is the union of the sets of members of the types
1172 // specified as a primary constraint or secondary constraint
1174 if (BaseType.BuiltinType != BuiltinTypeSpec.Type.Object && BaseType.BuiltinType != BuiltinTypeSpec.Type.ValueType)
1175 cache.AddBaseType (BaseType);
1177 if (ifaces != null) {
1178 foreach (var iface_type in Interfaces) {
1179 cache.AddInterface (iface_type);
1183 if (targs != null) {
1184 foreach (var ta in targs) {
1185 var b_type = ta.BaseType;
1186 if (b_type.BuiltinType != BuiltinTypeSpec.Type.Object && b_type.BuiltinType != BuiltinTypeSpec.Type.ValueType)
1187 cache.AddBaseType (b_type);
1189 if (ta.Interfaces != null) {
1190 foreach (var iface_type in ta.Interfaces) {
1191 cache.AddInterface (iface_type);
1198 public bool IsConvertibleToInterface (TypeSpec iface)
1200 if (Interfaces != null) {
1201 foreach (var t in Interfaces) {
1207 if (TypeArguments != null) {
1208 foreach (var t in TypeArguments) {
1209 if (((TypeParameterSpec) t).IsConvertibleToInterface (iface))
1217 public override TypeSpec Mutate (TypeParameterMutator mutator)
1219 return mutator.Mutate (this);
1223 public struct TypeParameterInflator
1225 readonly TypeSpec type;
1226 readonly TypeParameterSpec[] tparams;
1227 readonly TypeSpec[] targs;
1228 readonly IModuleContext context;
1230 public TypeParameterInflator (TypeParameterInflator nested, TypeSpec type)
1231 : this (nested.context, type, nested.tparams, nested.targs)
1235 public TypeParameterInflator (IModuleContext context, TypeSpec type, TypeParameterSpec[] tparams, TypeSpec[] targs)
1237 if (tparams.Length != targs.Length)
1238 throw new ArgumentException ("Invalid arguments");
1240 this.context = context;
1241 this.tparams = tparams;
1248 public IModuleContext Context {
1254 public TypeSpec TypeInstance {
1261 // Type parameters to inflate
1263 public TypeParameterSpec[] TypeParameters {
1271 public TypeSpec Inflate (TypeSpec type)
1273 var tp = type as TypeParameterSpec;
1275 return Inflate (tp);
1277 var ac = type as ArrayContainer;
1279 var et = Inflate (ac.Element);
1280 if (et != ac.Element)
1281 return ArrayContainer.MakeType (context.Module, et, ac.Rank);
1287 // When inflating a nested type, inflate its parent first
1288 // in case it's using same type parameters (was inflated within the type)
1292 if (type.IsNested) {
1293 var parent = Inflate (type.DeclaringType);
1296 // Keep the inflated type arguments
1298 targs = type.TypeArguments;
1301 // When inflating imported nested type used inside same declaring type, we get TypeSpec
1302 // because the import cache helps us to catch it. However, that means we have to look at
1303 // type definition to get type argument (they are in fact type parameter in this case)
1305 if (targs.Length == 0 && type.Arity > 0)
1306 targs = type.MemberDefinition.TypeParameters;
1309 // Parent was inflated, find the same type on inflated type
1310 // to use same cache for nested types on same generic parent
1312 type = MemberCache.FindNestedType (parent, type.Name, type.Arity);
1315 // Handle the tricky case where parent shares local type arguments
1316 // which means inflating inflated type
1319 // public static Nested<T> Foo () { return null; }
1321 // public class Nested<U> {}
1324 // return type of Test<string>.Foo() has to be Test<string>.Nested<string>
1326 if (targs.Length > 0) {
1327 var inflated_targs = new TypeSpec[targs.Length];
1328 for (; i < targs.Length; ++i)
1329 inflated_targs[i] = Inflate (targs[i]);
1331 type = type.MakeGenericType (context, inflated_targs);
1337 // Nothing to do for non-generic type
1338 if (type.Arity == 0)
1341 targs = new TypeSpec[type.Arity];
1344 // Inflating using outside type arguments, var v = new Foo<int> (), class Foo<T> {}
1346 if (type is InflatedTypeSpec) {
1347 for (; i < targs.Length; ++i)
1348 targs[i] = Inflate (type.TypeArguments[i]);
1350 type = type.GetDefinition ();
1353 // Inflating parent using inside type arguments, class Foo<T> { ITest<T> foo; }
1355 var args = type.MemberDefinition.TypeParameters;
1356 foreach (var ds_tp in args)
1357 targs[i++] = Inflate (ds_tp);
1360 return type.MakeGenericType (context, targs);
1363 public TypeSpec Inflate (TypeParameterSpec tp)
1365 for (int i = 0; i < tparams.Length; ++i)
1366 if (tparams [i] == tp)
1369 // This can happen when inflating nested types
1370 // without type arguments specified
1376 // Before emitting any code we have to change all MVAR references to VAR
1377 // when the method is of generic type and has hoisted variables
1379 public class TypeParameterMutator
1381 readonly TypeParameters mvar;
1382 readonly TypeParameters var;
1383 Dictionary<TypeSpec, TypeSpec> mutated_typespec;
1385 public TypeParameterMutator (TypeParameters mvar, TypeParameters var)
1387 if (mvar.Count != var.Count)
1388 throw new ArgumentException ();
1396 public TypeParameters MethodTypeParameters {
1404 public static TypeSpec GetMemberDeclaringType (TypeSpec type)
1406 if (type is InflatedTypeSpec) {
1407 if (type.DeclaringType == null)
1408 return type.GetDefinition ();
1410 var parent = GetMemberDeclaringType (type.DeclaringType);
1411 type = MemberCache.GetMember<TypeSpec> (parent, type);
1417 public TypeSpec Mutate (TypeSpec ts)
1420 if (mutated_typespec != null && mutated_typespec.TryGetValue (ts, out value))
1423 value = ts.Mutate (this);
1424 if (mutated_typespec == null)
1425 mutated_typespec = new Dictionary<TypeSpec, TypeSpec> ();
1427 mutated_typespec.Add (ts, value);
1431 public TypeParameterSpec Mutate (TypeParameterSpec tp)
1433 for (int i = 0; i < mvar.Count; ++i) {
1434 if (mvar[i].Type == tp)
1441 public TypeSpec[] Mutate (TypeSpec[] targs)
1443 TypeSpec[] mutated = new TypeSpec[targs.Length];
1444 bool changed = false;
1445 for (int i = 0; i < targs.Length; ++i) {
1446 mutated[i] = Mutate (targs[i]);
1447 changed |= targs[i] != mutated[i];
1450 return changed ? mutated : targs;
1455 /// A TypeExpr which already resolved to a type parameter.
1457 public class TypeParameterExpr : TypeExpression
1459 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1460 : base (type_parameter.Type, loc)
1462 this.eclass = ExprClass.TypeParameter;
1466 public class InflatedTypeSpec : TypeSpec
1469 TypeParameterSpec[] constraints;
1470 readonly TypeSpec open_type;
1471 readonly IModuleContext context;
1473 public InflatedTypeSpec (IModuleContext context, TypeSpec openType, TypeSpec declaringType, TypeSpec[] targs)
1474 : base (openType.Kind, declaringType, openType.MemberDefinition, null, openType.Modifiers)
1477 throw new ArgumentNullException ("targs");
1479 // this.state = openType.state;
1480 this.context = context;
1481 this.open_type = openType;
1484 foreach (var arg in targs) {
1485 if (arg.HasDynamicElement || arg.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1486 state |= StateFlags.HasDynamicElement;
1491 if (open_type.Kind == MemberKind.MissingType)
1492 MemberCache = MemberCache.Empty;
1494 if ((open_type.Modifiers & Modifiers.COMPILER_GENERATED) != 0)
1495 state |= StateFlags.ConstraintsChecked;
1500 public override TypeSpec BaseType {
1502 if (cache == null || (state & StateFlags.PendingBaseTypeInflate) != 0)
1503 InitializeMemberCache (true);
1505 return base.BaseType;
1510 // Inflated type parameters with constraints array, mapping with type arguments is based on index
1512 public TypeParameterSpec[] Constraints {
1514 if (constraints == null) {
1515 constraints = TypeParameterSpec.InflateConstraints (MemberDefinition.TypeParameters, l => l.CreateLocalInflator (context), this);
1523 // Used to cache expensive constraints validation on constructed types
1525 public bool HasConstraintsChecked {
1527 return (state & StateFlags.ConstraintsChecked) != 0;
1530 state = value ? state | StateFlags.ConstraintsChecked : state & ~StateFlags.ConstraintsChecked;
1534 public override IList<TypeSpec> Interfaces {
1537 InitializeMemberCache (true);
1539 return base.Interfaces;
1543 public override bool IsExpressionTreeType {
1545 return (open_type.state & StateFlags.InflatedExpressionType) != 0;
1549 public override bool IsGenericIterateInterface {
1551 return (open_type.state & StateFlags.GenericIterateInterface) != 0;
1555 public override bool IsGenericTask {
1557 return (open_type.state & StateFlags.GenericTask) != 0;
1561 public override bool IsNullableType {
1563 return (open_type.state & StateFlags.InflatedNullableType) != 0;
1568 // Types used to inflate the generic type
1570 public override TypeSpec[] TypeArguments {
1578 public static bool ContainsTypeParameter (TypeSpec type)
1580 if (type.Kind == MemberKind.TypeParameter)
1583 var element_container = type as ElementTypeSpec;
1584 if (element_container != null)
1585 return ContainsTypeParameter (element_container.Element);
1587 foreach (var t in type.TypeArguments) {
1588 if (ContainsTypeParameter (t)) {
1596 TypeParameterInflator CreateLocalInflator (IModuleContext context)
1598 TypeParameterSpec[] tparams_full;
1599 TypeSpec[] targs_full = targs;
1602 // Special case is needed when we are inflating an open type (nested type definition)
1603 // on inflated parent. Consider following case
1605 // Foo<T>.Bar<U> => Foo<string>.Bar<U>
1607 // Any later inflation of Foo<string>.Bar<U> has to also inflate T if used inside Bar<U>
1609 List<TypeSpec> merged_targs = null;
1610 List<TypeParameterSpec> merged_tparams = null;
1612 var type = DeclaringType;
1615 if (type.TypeArguments.Length > 0) {
1616 if (merged_targs == null) {
1617 merged_targs = new List<TypeSpec> ();
1618 merged_tparams = new List<TypeParameterSpec> ();
1619 if (targs.Length > 0) {
1620 merged_targs.AddRange (targs);
1621 merged_tparams.AddRange (open_type.MemberDefinition.TypeParameters);
1624 merged_tparams.AddRange (type.MemberDefinition.TypeParameters);
1625 merged_targs.AddRange (type.TypeArguments);
1627 type = type.DeclaringType;
1628 } while (type != null);
1630 if (merged_targs != null) {
1631 // Type arguments are not in the right order but it should not matter in this case
1632 targs_full = merged_targs.ToArray ();
1633 tparams_full = merged_tparams.ToArray ();
1634 } else if (targs.Length == 0) {
1635 tparams_full = TypeParameterSpec.EmptyTypes;
1637 tparams_full = open_type.MemberDefinition.TypeParameters;
1639 } else if (targs.Length == 0) {
1640 tparams_full = TypeParameterSpec.EmptyTypes;
1642 tparams_full = open_type.MemberDefinition.TypeParameters;
1645 return new TypeParameterInflator (context, this, tparams_full, targs_full);
1648 MetaType CreateMetaInfo (TypeParameterMutator mutator)
1651 // Converts nested type arguments into right order
1652 // Foo<string, bool>.Bar<int> => string, bool, int
1654 var all = new List<MetaType> ();
1655 TypeSpec type = this;
1656 TypeSpec definition = type;
1658 if (type.GetDefinition().IsGeneric) {
1660 type.TypeArguments != TypeSpec.EmptyTypes ?
1661 type.TypeArguments.Select (l => l.GetMetaInfo ()) :
1662 type.MemberDefinition.TypeParameters.Select (l => l.GetMetaInfo ()));
1665 definition = definition.GetDefinition ();
1666 type = type.DeclaringType;
1667 } while (type != null);
1669 return definition.GetMetaInfo ().MakeGenericType (all.ToArray ());
1672 public override ObsoleteAttribute GetAttributeObsolete ()
1674 return open_type.GetAttributeObsolete ();
1677 protected override bool IsNotCLSCompliant (out bool attrValue)
1679 if (base.IsNotCLSCompliant (out attrValue))
1682 foreach (var ta in TypeArguments) {
1683 if (ta.MemberDefinition.CLSAttributeValue == false)
1690 public override TypeSpec GetDefinition ()
1695 public override MetaType GetMetaInfo ()
1698 info = CreateMetaInfo (null);
1703 public override string GetSignatureForError ()
1706 return targs[0].GetSignatureForError () + "?";
1708 return base.GetSignatureForError ();
1711 protected override string GetTypeNameSignature ()
1713 if (targs.Length == 0 || MemberDefinition is AnonymousTypeClass)
1716 return "<" + TypeManager.CSharpName (targs) + ">";
1719 public bool HasDynamicArgument ()
1721 for (int i = 0; i < targs.Length; ++i) {
1722 var item = targs[i];
1724 if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1727 if (item is InflatedTypeSpec) {
1728 if (((InflatedTypeSpec) item).HasDynamicArgument ())
1735 while (item.IsArray) {
1736 item = ((ArrayContainer) item).Element;
1739 if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1747 protected override void InitializeMemberCache (bool onlyTypes)
1749 if (cache == null) {
1750 var open_cache = onlyTypes ? open_type.MemberCacheTypes : open_type.MemberCache;
1752 // Surprisingly, calling MemberCache on open type could meantime create cache on this type
1753 // for imported type parameter constraints referencing nested type of this declaration
1755 cache = new MemberCache (open_cache);
1758 var inflator = CreateLocalInflator (context);
1761 // Two stage inflate due to possible nested types recursive
1771 // When resolving type of `b' members of `B' cannot be
1772 // inflated because are not yet available in membercache
1774 if ((state & StateFlags.PendingMemberCacheMembers) == 0) {
1775 open_type.MemberCacheTypes.InflateTypes (cache, inflator);
1778 // Inflate any implemented interfaces
1780 if (open_type.Interfaces != null) {
1781 ifaces = new List<TypeSpec> (open_type.Interfaces.Count);
1782 foreach (var iface in open_type.Interfaces) {
1783 var iface_inflated = inflator.Inflate (iface);
1784 if (iface_inflated == null)
1787 AddInterface (iface_inflated);
1792 // Handles the tricky case of recursive nested base generic type
1794 // class A<T> : Base<A<T>.Nested> {
1798 // When inflating A<T>. base type is not yet known, secondary
1799 // inflation is required (not common case) once base scope
1802 if (open_type.BaseType == null) {
1804 state |= StateFlags.PendingBaseTypeInflate;
1806 BaseType = inflator.Inflate (open_type.BaseType);
1808 } else if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1810 // It can happen when resolving base type without being defined
1811 // which is not allowed to happen and will always lead to an error
1813 // class B { class N {} }
1814 // class A<T> : A<B.N> {}
1816 if (open_type.BaseType == null)
1819 BaseType = inflator.Inflate (open_type.BaseType);
1820 state &= ~StateFlags.PendingBaseTypeInflate;
1824 state |= StateFlags.PendingMemberCacheMembers;
1828 var tc = open_type.MemberDefinition as TypeContainer;
1829 if (tc != null && !tc.HasMembersDefined)
1830 throw new InternalErrorException ("Inflating MemberCache with undefined members");
1832 if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1833 BaseType = inflator.Inflate (open_type.BaseType);
1834 state &= ~StateFlags.PendingBaseTypeInflate;
1837 state &= ~StateFlags.PendingMemberCacheMembers;
1838 open_type.MemberCache.InflateMembers (cache, open_type, inflator);
1841 public override TypeSpec Mutate (TypeParameterMutator mutator)
1843 var targs = TypeArguments;
1845 targs = mutator.Mutate (targs);
1847 var decl = DeclaringType;
1848 if (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
1849 decl = mutator.Mutate (decl);
1851 if (targs == TypeArguments && decl == DeclaringType)
1854 var mutated = (InflatedTypeSpec) MemberwiseClone ();
1855 if (decl != DeclaringType) {
1856 // Gets back MethodInfo in case of metaInfo was inflated
1857 //mutated.info = MemberCache.GetMember<TypeSpec> (DeclaringType.GetDefinition (), this).info;
1859 mutated.declaringType = decl;
1860 mutated.state |= StateFlags.PendingMetaInflate;
1863 if (targs != null) {
1864 mutated.targs = targs;
1865 mutated.info = null;
1874 // Tracks the type arguments when instantiating a generic type. It's used
1875 // by both type arguments and type parameters
1877 public class TypeArguments
1879 List<FullNamedExpression> args;
1882 public TypeArguments (params FullNamedExpression[] types)
1884 this.args = new List<FullNamedExpression> (types);
1887 public void Add (FullNamedExpression type)
1893 /// We may only be used after Resolve() is called and return the fully
1896 // TODO: Not needed, just return type from resolve
1897 public TypeSpec[] Arguments {
1912 public virtual bool IsEmpty {
1918 public List<FullNamedExpression> TypeExpressions {
1924 public string GetSignatureForError()
1926 StringBuilder sb = new StringBuilder ();
1927 for (int i = 0; i < Count; ++i) {
1930 sb.Append (expr.GetSignatureForError ());
1936 return sb.ToString ();
1940 /// Resolve the type arguments.
1942 public virtual bool Resolve (IMemberContext ec)
1945 return atypes.Length != 0;
1947 int count = args.Count;
1950 atypes = new TypeSpec [count];
1952 for (int i = 0; i < count; i++){
1953 var te = args[i].ResolveAsType (ec);
1962 ec.Module.Compiler.Report.Error (718, args[i].Location, "`{0}': static classes cannot be used as generic arguments",
1963 te.GetSignatureForError ());
1967 if (te.IsPointer || te.IsSpecialRuntimeType) {
1968 ec.Module.Compiler.Report.Error (306, args[i].Location,
1969 "The type `{0}' may not be used as a type argument",
1970 te.GetSignatureForError ());
1976 atypes = TypeSpec.EmptyTypes;
1981 public TypeArguments Clone ()
1983 TypeArguments copy = new TypeArguments ();
1984 foreach (var ta in args)
1991 public class UnboundTypeArguments : TypeArguments
1993 public UnboundTypeArguments (int arity)
1994 : base (new FullNamedExpression[arity])
1998 public override bool IsEmpty {
2004 public override bool Resolve (IMemberContext ec)
2006 // Nothing to be resolved
2011 public class TypeParameters
2013 List<TypeParameter> names;
2014 TypeParameterSpec[] types;
2016 public TypeParameters ()
2018 names = new List<TypeParameter> ();
2021 public TypeParameters (int count)
2023 names = new List<TypeParameter> (count);
2034 public TypeParameterSpec[] Types {
2042 public void Add (TypeParameter tparam)
2047 public void Add (TypeParameters tparams)
2049 names.AddRange (tparams.names);
2052 public void Define (GenericTypeParameterBuilder[] buiders, TypeSpec declaringType, int parentOffset, TypeContainer parent)
2054 types = new TypeParameterSpec[Count];
2055 for (int i = 0; i < types.Length; ++i) {
2058 tp.Define (buiders[i + parentOffset], declaringType, parent);
2060 types[i].DeclaredPosition = i + parentOffset;
2062 if (tp.Variance != Variance.None && !(declaringType != null && (declaringType.Kind == MemberKind.Interface || declaringType.Kind == MemberKind.Delegate))) {
2063 parent.Compiler.Report.Error (1960, tp.Location, "Variant type parameters can only be used with interfaces and delegates");
2068 public TypeParameter this[int index] {
2070 return names [index];
2073 names[index] = value;
2077 public TypeParameter Find (string name)
2079 foreach (var tp in names) {
2080 if (tp.Name == name)
2087 public string GetSignatureForError ()
2089 StringBuilder sb = new StringBuilder ();
2090 for (int i = 0; i < Count; ++i) {
2094 var name = names[i];
2096 sb.Append (name.GetSignatureForError ());
2099 return sb.ToString ();
2102 public void VerifyClsCompliance ()
2104 foreach (var tp in names) {
2105 tp.VerifyClsCompliance ();
2111 // A type expression of generic type with type arguments
2113 class GenericTypeExpr : TypeExpr
2119 /// Instantiate the generic type `t' with the type arguments `args'.
2120 /// Use this constructor if you already know the fully resolved
2123 public GenericTypeExpr (TypeSpec open_type, TypeArguments args, Location l)
2125 this.open_type = open_type;
2130 public TypeArguments TypeArguments {
2131 get { return args; }
2134 public override string GetSignatureForError ()
2136 return TypeManager.CSharpName (type);
2139 public override TypeSpec ResolveAsType (IMemberContext mc)
2141 if (eclass != ExprClass.Unresolved)
2144 if (!args.Resolve (mc))
2147 TypeSpec[] atypes = args.Arguments;
2150 // Now bind the parameters
2152 var inflated = open_type.MakeGenericType (mc, atypes);
2154 eclass = ExprClass.Type;
2157 // The constraints can be checked only when full type hierarchy is known
2159 if (!inflated.HasConstraintsChecked && mc.Module.HasTypesFullyDefined) {
2160 var constraints = inflated.Constraints;
2161 if (constraints != null) {
2162 var cc = new ConstraintChecker (mc);
2163 if (cc.CheckAll (open_type, atypes, constraints, loc)) {
2164 inflated.HasConstraintsChecked = true;
2172 public override bool Equals (object obj)
2174 GenericTypeExpr cobj = obj as GenericTypeExpr;
2178 if ((type == null) || (cobj.type == null))
2181 return type == cobj.type;
2184 public override int GetHashCode ()
2186 return base.GetHashCode ();
2191 // Generic type with unbound type arguments, used for typeof (G<,,>)
2193 class GenericOpenTypeExpr : TypeExpression
2195 public GenericOpenTypeExpr (TypeSpec type, /*UnboundTypeArguments args,*/ Location loc)
2196 : base (type.GetDefinition (), loc)
2201 struct ConstraintChecker
2204 bool ignore_inferred_dynamic;
2205 bool recursive_checks;
2207 public ConstraintChecker (IMemberContext ctx)
2210 ignore_inferred_dynamic = false;
2211 recursive_checks = false;
2216 public bool IgnoreInferredDynamic {
2218 return ignore_inferred_dynamic;
2221 ignore_inferred_dynamic = value;
2228 // Checks the constraints of open generic type against type
2229 // arguments. This version is used for types which could not be
2230 // checked immediatelly during construction because the type
2231 // hierarchy was not yet fully setup (before Emit phase)
2233 public static bool Check (IMemberContext mc, TypeSpec type, Location loc)
2236 // Check declaring type first if there is any
2238 if (type.DeclaringType != null && !Check (mc, type.DeclaringType, loc))
2241 while (type is ElementTypeSpec)
2242 type = ((ElementTypeSpec) type).Element;
2244 if (type.Arity == 0)
2247 var gtype = type as InflatedTypeSpec;
2251 var constraints = gtype.Constraints;
2252 if (constraints == null)
2255 if (gtype.HasConstraintsChecked)
2258 var cc = new ConstraintChecker (mc);
2259 cc.recursive_checks = true;
2261 if (cc.CheckAll (gtype.GetDefinition (), type.TypeArguments, constraints, loc)) {
2262 gtype.HasConstraintsChecked = true;
2270 // Checks all type arguments againts type parameters constraints
2271 // NOTE: It can run in probing mode when `mc' is null
2273 public bool CheckAll (MemberSpec context, TypeSpec[] targs, TypeParameterSpec[] tparams, Location loc)
2275 for (int i = 0; i < tparams.Length; i++) {
2276 if (ignore_inferred_dynamic && targs[i].BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2279 var targ = targs[i];
2280 if (!CheckConstraint (context, targ, tparams [i], loc))
2283 if (!recursive_checks)
2286 if (!Check (mc, targ, loc))
2293 bool CheckConstraint (MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, Location loc)
2296 // First, check the `class' and `struct' constraints.
2298 if (tparam.HasSpecialClass && !TypeSpec.IsReferenceType (atype)) {
2300 mc.Module.Compiler.Report.Error (452, loc,
2301 "The type `{0}' must be a reference type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
2302 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2308 if (tparam.HasSpecialStruct && (!TypeSpec.IsValueType (atype) || atype.IsNullableType)) {
2310 mc.Module.Compiler.Report.Error (453, loc,
2311 "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}'",
2312 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2321 // Check the class constraint
2323 if (tparam.HasTypeConstraint) {
2324 var dep = tparam.BaseType.GetMissingDependencies ();
2329 ImportedTypeDefinition.Error_MissingDependency (mc, dep, loc);
2333 if (!CheckConversion (mc, context, atype, tparam, tparam.BaseType, loc)) {
2342 // Check the interfaces constraints
2344 if (tparam.Interfaces != null) {
2345 foreach (TypeSpec iface in tparam.Interfaces) {
2346 var dep = iface.GetMissingDependencies ();
2351 ImportedTypeDefinition.Error_MissingDependency (mc, dep, loc);
2354 // return immediately to avoid duplicate errors because we are scanning
2355 // expanded interface list
2359 if (!CheckConversion (mc, context, atype, tparam, iface, loc)) {
2369 // Check the type parameter constraint
2371 if (tparam.TypeArguments != null) {
2372 foreach (var ta in tparam.TypeArguments) {
2373 if (!CheckConversion (mc, context, atype, tparam, ta, loc)) {
2383 // Finally, check the constructor constraint.
2385 if (!tparam.HasSpecialConstructor)
2388 if (!HasDefaultConstructor (atype)) {
2390 mc.Module.Compiler.Report.SymbolRelatedToPreviousError (atype);
2391 mc.Module.Compiler.Report.Error (310, loc,
2392 "The type `{0}' must have a public parameterless constructor in order to use it as parameter `{1}' in the generic type or method `{2}'",
2393 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2401 static bool HasDynamicTypeArgument (TypeSpec[] targs)
2403 for (int i = 0; i < targs.Length; ++i) {
2404 var targ = targs [i];
2405 if (targ.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2408 if (HasDynamicTypeArgument (targ.TypeArguments))
2415 bool CheckConversion (IMemberContext mc, MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, TypeSpec ttype, Location loc)
2420 if (atype.IsGenericParameter) {
2421 var tps = (TypeParameterSpec) atype;
2422 if (tps.TypeArguments != null) {
2423 foreach (var targ in tps.TypeArguments) {
2424 if (TypeSpecComparer.Override.IsEqual (targ, ttype))
2429 if (Convert.ImplicitTypeParameterConversion (null, tps, ttype) != null)
2432 } else if (TypeSpec.IsValueType (atype)) {
2433 if (atype.IsNullableType) {
2435 // LAMESPEC: Only identity or base type ValueType or Object satisfy nullable type
2437 if (TypeSpec.IsBaseClass (atype, ttype, false))
2440 if (Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
2444 if (Convert.ImplicitReferenceConversionExists (atype, ttype) || Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
2449 // When partial/full type inference finds a dynamic type argument delay
2450 // the constraint check to runtime, it can succeed for real underlying
2453 if (ignore_inferred_dynamic && HasDynamicTypeArgument (ttype.TypeArguments))
2457 mc.Module.Compiler.Report.SymbolRelatedToPreviousError (tparam);
2458 if (atype.IsGenericParameter) {
2459 mc.Module.Compiler.Report.Error (314, loc,
2460 "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}'",
2461 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2462 } else if (TypeSpec.IsValueType (atype)) {
2463 if (atype.IsNullableType) {
2464 if (ttype.IsInterface) {
2465 mc.Module.Compiler.Report.Error (313, loc,
2466 "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}'",
2467 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2469 mc.Module.Compiler.Report.Error (312, loc,
2470 "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}'",
2471 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2474 mc.Module.Compiler.Report.Error (315, loc,
2475 "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}'",
2476 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2479 mc.Module.Compiler.Report.Error (311, loc,
2480 "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}'",
2481 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2488 bool HasDefaultConstructor (TypeSpec atype)
2490 var tp = atype as TypeParameterSpec;
2492 return tp.HasSpecialConstructor || tp.HasSpecialStruct;
2495 if (atype.IsStruct || atype.IsEnum)
2498 if (atype.IsAbstract)
2501 var tdef = atype.GetDefinition ();
2503 var found = MemberCache.FindMember (tdef,
2504 MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters),
2505 BindingRestriction.DeclaredOnly | BindingRestriction.InstanceOnly);
2507 return found != null && (found.Modifiers & Modifiers.PUBLIC) != 0;
2511 public partial class TypeManager
2513 public static Variance CheckTypeVariance (TypeSpec t, Variance expected, IMemberContext member)
2515 var tp = t as TypeParameterSpec;
2517 Variance v = tp.Variance;
2518 if (expected == Variance.None && v != expected ||
2519 expected == Variance.Covariant && v == Variance.Contravariant ||
2520 expected == Variance.Contravariant && v == Variance.Covariant) {
2521 ((TypeParameter)tp.MemberDefinition).ErrorInvalidVariance (member, expected);
2527 if (t.TypeArguments.Length > 0) {
2528 var targs_definition = t.MemberDefinition.TypeParameters;
2529 TypeSpec[] targs = GetTypeArguments (t);
2530 for (int i = 0; i < targs.Length; ++i) {
2531 Variance v = targs_definition[i].Variance;
2532 CheckTypeVariance (targs[i], (Variance) ((int)v * (int)expected), member);
2539 return CheckTypeVariance (GetElementType (t), expected, member);
2541 return Variance.None;
2546 // Implements C# type inference
2551 // Tracks successful rate of type inference
2553 int score = int.MaxValue;
2554 readonly Arguments arguments;
2555 readonly int arg_count;
2557 public TypeInference (Arguments arguments)
2559 this.arguments = arguments;
2560 if (arguments != null)
2561 arg_count = arguments.Count;
2564 public int InferenceScore {
2570 public TypeSpec[] InferMethodArguments (ResolveContext ec, MethodSpec method)
2572 var method_generic_args = method.GenericDefinition.TypeParameters;
2573 TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2574 if (!context.UnfixedVariableExists)
2575 return TypeSpec.EmptyTypes;
2577 AParametersCollection pd = method.Parameters;
2578 if (!InferInPhases (ec, context, pd))
2581 return context.InferredTypeArguments;
2585 // Implements method type arguments inference
2587 bool InferInPhases (ResolveContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
2589 int params_arguments_start;
2590 if (methodParameters.HasParams) {
2591 params_arguments_start = methodParameters.Count - 1;
2593 params_arguments_start = arg_count;
2596 TypeSpec [] ptypes = methodParameters.Types;
2599 // The first inference phase
2601 TypeSpec method_parameter = null;
2602 for (int i = 0; i < arg_count; i++) {
2603 Argument a = arguments [i];
2607 if (i < params_arguments_start) {
2608 method_parameter = methodParameters.Types [i];
2609 } else if (i == params_arguments_start) {
2610 if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2611 method_parameter = methodParameters.Types [params_arguments_start];
2613 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2615 ptypes = (TypeSpec[]) ptypes.Clone ();
2616 ptypes [i] = method_parameter;
2620 // When a lambda expression, an anonymous method
2621 // is used an explicit argument type inference takes a place
2623 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2625 if (am.ExplicitTypeInference (ec, tic, method_parameter))
2631 score -= tic.ExactInference (a.Type, method_parameter);
2635 if (a.Expr.Type == InternalType.NullLiteral)
2638 if (TypeSpec.IsValueType (method_parameter)) {
2639 score -= tic.LowerBoundInference (a.Type, method_parameter);
2644 // Otherwise an output type inference is made
2646 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2650 // Part of the second phase but because it happens only once
2651 // we don't need to call it in cycle
2653 bool fixed_any = false;
2654 if (!tic.FixIndependentTypeArguments (ec, ptypes, ref fixed_any))
2657 return DoSecondPhase (ec, tic, ptypes, !fixed_any);
2660 bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, TypeSpec[] methodParameters, bool fixDependent)
2662 bool fixed_any = false;
2663 if (fixDependent && !tic.FixDependentTypes (ec, ref fixed_any))
2666 // If no further unfixed type variables exist, type inference succeeds
2667 if (!tic.UnfixedVariableExists)
2670 if (!fixed_any && fixDependent)
2673 // For all arguments where the corresponding argument output types
2674 // contain unfixed type variables but the input types do not,
2675 // an output type inference is made
2676 for (int i = 0; i < arg_count; i++) {
2678 // Align params arguments
2679 TypeSpec t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
2681 if (!t_i.IsDelegate) {
2682 if (!t_i.IsExpressionTreeType)
2685 t_i = TypeManager.GetTypeArguments (t_i) [0];
2688 var mi = Delegate.GetInvokeMethod (t_i);
2689 TypeSpec rtype = mi.ReturnType;
2691 if (tic.IsReturnTypeNonDependent (ec, mi, rtype)) {
2692 // It can be null for default arguments
2693 if (arguments[i] == null)
2696 score -= tic.OutputTypeInference (ec, arguments[i].Expr, t_i);
2701 return DoSecondPhase (ec, tic, methodParameters, true);
2705 public class TypeInferenceContext
2707 protected enum BoundKind
2714 protected class BoundInfo : IEquatable<BoundInfo>
2716 public readonly TypeSpec Type;
2717 public readonly BoundKind Kind;
2719 public BoundInfo (TypeSpec type, BoundKind kind)
2725 public override int GetHashCode ()
2727 return Type.GetHashCode ();
2730 public virtual Expression GetTypeExpression ()
2732 return new TypeExpression (Type, Location.Null);
2735 #region IEquatable<BoundInfo> Members
2737 public virtual bool Equals (BoundInfo other)
2739 return Type == other.Type && Kind == other.Kind;
2745 readonly TypeSpec[] tp_args;
2746 readonly TypeSpec[] fixed_types;
2747 readonly List<BoundInfo>[] bounds;
2750 // TODO MemberCache: Could it be TypeParameterSpec[] ??
2751 public TypeInferenceContext (TypeSpec[] typeArguments)
2753 if (typeArguments.Length == 0)
2754 throw new ArgumentException ("Empty generic arguments");
2756 fixed_types = new TypeSpec [typeArguments.Length];
2757 for (int i = 0; i < typeArguments.Length; ++i) {
2758 if (typeArguments [i].IsGenericParameter) {
2759 if (bounds == null) {
2760 bounds = new List<BoundInfo> [typeArguments.Length];
2761 tp_args = new TypeSpec [typeArguments.Length];
2763 tp_args [i] = typeArguments [i];
2765 fixed_types [i] = typeArguments [i];
2771 // Used together with AddCommonTypeBound fo implement
2772 // 7.4.2.13 Finding the best common type of a set of expressions
2774 public TypeInferenceContext ()
2776 fixed_types = new TypeSpec [1];
2777 tp_args = new TypeSpec [1];
2778 tp_args[0] = InternalType.Arglist; // it can be any internal type
2779 bounds = new List<BoundInfo> [1];
2782 public TypeSpec[] InferredTypeArguments {
2788 public void AddCommonTypeBound (TypeSpec type)
2790 AddToBounds (new BoundInfo (type, BoundKind.Lower), 0);
2793 protected void AddToBounds (BoundInfo bound, int index)
2796 // Some types cannot be used as type arguments
2798 if (bound.Type.Kind == MemberKind.Void || bound.Type.IsPointer || bound.Type.IsSpecialRuntimeType ||
2799 bound.Type == InternalType.MethodGroup || bound.Type == InternalType.AnonymousMethod)
2802 var a = bounds [index];
2804 a = new List<BoundInfo> (2);
2810 if (a.Contains (bound))
2816 bool AllTypesAreFixed (TypeSpec[] types)
2818 foreach (TypeSpec t in types) {
2819 if (t.IsGenericParameter) {
2825 if (TypeManager.IsGenericType (t))
2826 return AllTypesAreFixed (TypeManager.GetTypeArguments (t));
2833 // 26.3.3.8 Exact Inference
2835 public int ExactInference (TypeSpec u, TypeSpec v)
2837 // If V is an array type
2842 // TODO MemberCache: GetMetaInfo ()
2843 if (u.GetMetaInfo ().GetArrayRank () != v.GetMetaInfo ().GetArrayRank ())
2846 return ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
2849 // If V is constructed type and U is constructed type
2850 if (TypeManager.IsGenericType (v)) {
2851 if (!TypeManager.IsGenericType (u))
2854 TypeSpec [] ga_u = TypeManager.GetTypeArguments (u);
2855 TypeSpec [] ga_v = TypeManager.GetTypeArguments (v);
2856 if (ga_u.Length != ga_v.Length)
2860 for (int i = 0; i < ga_u.Length; ++i)
2861 score += ExactInference (ga_u [i], ga_v [i]);
2863 return score > 0 ? 1 : 0;
2866 // If V is one of the unfixed type arguments
2867 int pos = IsUnfixed (v);
2871 AddToBounds (new BoundInfo (u, BoundKind.Exact), pos);
2875 public bool FixAllTypes (ResolveContext ec)
2877 for (int i = 0; i < tp_args.Length; ++i) {
2878 if (!FixType (ec, i))
2885 // All unfixed type variables Xi are fixed for which all of the following hold:
2886 // a, There is at least one type variable Xj that depends on Xi
2887 // b, Xi has a non-empty set of bounds
2889 public bool FixDependentTypes (ResolveContext ec, ref bool fixed_any)
2891 for (int i = 0; i < tp_args.Length; ++i) {
2892 if (fixed_types[i] != null)
2895 if (bounds[i] == null)
2898 if (!FixType (ec, i))
2908 // All unfixed type variables Xi which depend on no Xj are fixed
2910 public bool FixIndependentTypeArguments (ResolveContext ec, TypeSpec[] methodParameters, ref bool fixed_any)
2912 var types_to_fix = new List<TypeSpec> (tp_args);
2913 for (int i = 0; i < methodParameters.Length; ++i) {
2914 TypeSpec t = methodParameters[i];
2916 if (!t.IsDelegate) {
2917 if (!t.IsExpressionTreeType)
2920 t = TypeManager.GetTypeArguments (t) [0];
2923 if (t.IsGenericParameter)
2926 var invoke = Delegate.GetInvokeMethod (t);
2927 TypeSpec rtype = invoke.ReturnType;
2928 while (rtype.IsArray)
2929 rtype = ((ArrayContainer) rtype).Element;
2931 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
2934 // Remove dependent types, they cannot be fixed yet
2935 RemoveDependentTypes (types_to_fix, rtype);
2938 foreach (TypeSpec t in types_to_fix) {
2942 int idx = IsUnfixed (t);
2943 if (idx >= 0 && !FixType (ec, idx)) {
2948 fixed_any = types_to_fix.Count > 0;
2955 public bool FixType (ResolveContext ec, int i)
2957 // It's already fixed
2958 if (fixed_types[i] != null)
2959 throw new InternalErrorException ("Type argument has been already fixed");
2964 var candidates = bounds [i];
2965 if (candidates == null)
2968 if (candidates.Count == 1) {
2969 TypeSpec t = candidates[0].Type;
2970 if (t == InternalType.NullLiteral)
2973 fixed_types [i] = t;
2978 // Determines a unique type from which there is
2979 // a standard implicit conversion to all the other
2982 TypeSpec best_candidate = null;
2984 int candidates_count = candidates.Count;
2985 for (int ci = 0; ci < candidates_count; ++ci) {
2986 BoundInfo bound = candidates [ci];
2987 for (cii = 0; cii < candidates_count; ++cii) {
2991 BoundInfo cbound = candidates[cii];
2993 // Same type parameters with different bounds
2994 if (cbound.Type == bound.Type) {
2995 if (bound.Kind != BoundKind.Exact)
3001 if (bound.Kind == BoundKind.Exact || cbound.Kind == BoundKind.Exact) {
3002 if (cbound.Kind == BoundKind.Lower) {
3003 if (!Convert.ImplicitConversionExists (ec, cbound.GetTypeExpression (), bound.Type)) {
3009 if (cbound.Kind == BoundKind.Upper) {
3010 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
3017 if (bound.Kind != BoundKind.Exact) {
3018 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
3029 if (bound.Kind == BoundKind.Lower) {
3030 if (cbound.Kind == BoundKind.Lower) {
3031 if (!Convert.ImplicitConversionExists (ec, cbound.GetTypeExpression (), bound.Type)) {
3035 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
3045 if (bound.Kind == BoundKind.Upper) {
3046 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
3050 throw new NotImplementedException ("variance conversion");
3054 if (cii != candidates_count)
3058 // We already have the best candidate, break if thet are different
3060 // Dynamic is never ambiguous as we prefer dynamic over other best candidate types
3062 if (best_candidate != null) {
3064 if (best_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3067 if (bound.Type.BuiltinType != BuiltinTypeSpec.Type.Dynamic && best_candidate != bound.Type)
3071 best_candidate = bound.Type;
3074 if (best_candidate == null)
3077 fixed_types[i] = best_candidate;
3081 public bool HasBounds (int pos)
3083 return bounds[pos] != null;
3087 // Uses inferred or partially infered types to inflate delegate type argument. Returns
3088 // null when type parameter has not been fixed
3090 public TypeSpec InflateGenericArgument (IModuleContext context, TypeSpec parameter)
3092 var tp = parameter as TypeParameterSpec;
3095 // Type inference works on generic arguments (MVAR) only
3097 if (!tp.IsMethodOwned)
3101 // Ensure the type parameter belongs to same container
3103 if (tp.DeclaredPosition < tp_args.Length && tp_args[tp.DeclaredPosition] == parameter)
3104 return fixed_types[tp.DeclaredPosition] ?? parameter;
3109 var gt = parameter as InflatedTypeSpec;
3111 var inflated_targs = new TypeSpec [gt.TypeArguments.Length];
3112 for (int ii = 0; ii < inflated_targs.Length; ++ii) {
3113 var inflated = InflateGenericArgument (context, gt.TypeArguments [ii]);
3114 if (inflated == null)
3117 inflated_targs[ii] = inflated;
3120 return gt.GetDefinition ().MakeGenericType (context, inflated_targs);
3123 var ac = parameter as ArrayContainer;
3125 var inflated = InflateGenericArgument (context, ac.Element);
3126 if (inflated != ac.Element)
3127 return ArrayContainer.MakeType (context.Module, inflated);
3134 // Tests whether all delegate input arguments are fixed and generic output type
3135 // requires output type inference
3137 public bool IsReturnTypeNonDependent (ResolveContext ec, MethodSpec invoke, TypeSpec returnType)
3139 while (returnType.IsArray)
3140 returnType = ((ArrayContainer) returnType).Element;
3142 if (returnType.IsGenericParameter) {
3143 if (IsFixed (returnType))
3145 } else if (TypeManager.IsGenericType (returnType)) {
3146 if (returnType.IsDelegate) {
3147 invoke = Delegate.GetInvokeMethod (returnType);
3148 return IsReturnTypeNonDependent (ec, invoke, invoke.ReturnType);
3151 TypeSpec[] g_args = TypeManager.GetTypeArguments (returnType);
3153 // At least one unfixed return type has to exist
3154 if (AllTypesAreFixed (g_args))
3160 // All generic input arguments have to be fixed
3161 AParametersCollection d_parameters = invoke.Parameters;
3162 return AllTypesAreFixed (d_parameters.Types);
3165 bool IsFixed (TypeSpec type)
3167 return IsUnfixed (type) == -1;
3170 int IsUnfixed (TypeSpec type)
3172 if (!type.IsGenericParameter)
3175 for (int i = 0; i < tp_args.Length; ++i) {
3176 if (tp_args[i] == type) {
3177 if (fixed_types[i] != null)
3188 // 26.3.3.9 Lower-bound Inference
3190 public int LowerBoundInference (TypeSpec u, TypeSpec v)
3192 return LowerBoundInference (u, v, false);
3196 // Lower-bound (false) or Upper-bound (true) inference based on inversed argument
3198 int LowerBoundInference (TypeSpec u, TypeSpec v, bool inversed)
3200 // If V is one of the unfixed type arguments
3201 int pos = IsUnfixed (v);
3203 AddToBounds (new BoundInfo (u, inversed ? BoundKind.Upper : BoundKind.Lower), pos);
3207 // If U is an array type
3208 var u_ac = u as ArrayContainer;
3210 var v_ac = v as ArrayContainer;
3212 if (u_ac.Rank != v_ac.Rank)
3215 if (TypeSpec.IsValueType (u_ac.Element))
3216 return ExactInference (u_ac.Element, v_ac.Element);
3218 return LowerBoundInference (u_ac.Element, v_ac.Element, inversed);
3221 if (u_ac.Rank != 1 || !v.IsGenericIterateInterface)
3224 var v_i = TypeManager.GetTypeArguments (v) [0];
3225 if (TypeSpec.IsValueType (u_ac.Element))
3226 return ExactInference (u_ac.Element, v_i);
3228 return LowerBoundInference (u_ac.Element, v_i);
3231 if (v.IsGenericOrParentIsGeneric) {
3233 // if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
3234 // such that U is identical to, inherits from (directly or indirectly),
3235 // or implements (directly or indirectly) C<U1..Uk>
3237 var u_candidates = new List<TypeSpec> ();
3238 var open_v = v.MemberDefinition;
3240 for (TypeSpec t = u; t != null; t = t.BaseType) {
3241 if (open_v == t.MemberDefinition)
3242 u_candidates.Add (t);
3245 // Using this trick for dynamic type inference, the spec says the type arguments are "unknown" but
3246 // that would complicate the process a lot, instead I treat them as dynamic
3248 if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3249 u_candidates.Add (t);
3251 if (t.Interfaces != null) {
3252 foreach (var iface in t.Interfaces) {
3253 if (open_v == iface.MemberDefinition)
3254 u_candidates.Add (iface);
3259 TypeSpec[] unique_candidate_targs = null;
3260 var ga_v = TypeSpec.GetAllTypeArguments (v);
3261 foreach (TypeSpec u_candidate in u_candidates) {
3263 // The unique set of types U1..Uk means that if we have an interface I<T>,
3264 // class U : I<int>, I<long> then no type inference is made when inferring
3265 // type I<T> by applying type U because T could be int or long
3267 if (unique_candidate_targs != null) {
3268 TypeSpec[] second_unique_candidate_targs = TypeSpec.GetAllTypeArguments (u_candidate);
3269 if (TypeSpecComparer.Equals (unique_candidate_targs, second_unique_candidate_targs)) {
3270 unique_candidate_targs = second_unique_candidate_targs;
3275 // This should always cause type inference failure
3282 // A candidate is dynamic type expression, to simplify things use dynamic
3283 // for all type parameter of this type. For methods like this one
3285 // void M<T, U> (IList<T>, IList<U[]>)
3287 // dynamic becomes both T and U when the arguments are of dynamic type
3289 if (u_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
3290 unique_candidate_targs = new TypeSpec[ga_v.Length];
3291 for (int i = 0; i < unique_candidate_targs.Length; ++i)
3292 unique_candidate_targs[i] = u_candidate;
3294 unique_candidate_targs = TypeSpec.GetAllTypeArguments (u_candidate);
3298 if (unique_candidate_targs != null) {
3301 TypeParameterSpec[] tps = null;
3303 for (int i = 0; i < unique_candidate_targs.Length; ++i) {
3305 while (v.Arity == 0)
3306 v = v.DeclaringType;
3308 tps = v.MemberDefinition.TypeParameters;
3309 tp_index = tps.Length - 1;
3312 Variance variance = tps [tp_index--].Variance;
3314 TypeSpec u_i = unique_candidate_targs [i];
3315 if (variance == Variance.None || TypeSpec.IsValueType (u_i)) {
3316 if (ExactInference (u_i, ga_v [i]) == 0)
3319 bool upper_bound = (variance == Variance.Contravariant && !inversed) ||
3320 (variance == Variance.Covariant && inversed);
3322 if (LowerBoundInference (u_i, ga_v [i], upper_bound) == 0)
3335 // 26.3.3.6 Output Type Inference
3337 public int OutputTypeInference (ResolveContext ec, Expression e, TypeSpec t)
3339 // If e is a lambda or anonymous method with inferred return type
3340 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
3342 TypeSpec rt = ame.InferReturnType (ec, this, t);
3343 var invoke = Delegate.GetInvokeMethod (t);
3346 AParametersCollection pd = invoke.Parameters;
3347 return ame.Parameters.Count == pd.Count ? 1 : 0;
3350 TypeSpec rtype = invoke.ReturnType;
3351 return LowerBoundInference (rt, rtype) + 1;
3355 // if E is a method group and T is a delegate type or expression tree type
3356 // return type Tb with parameter types T1..Tk and return type Tb, and overload
3357 // resolution of E with the types T1..Tk yields a single method with return type U,
3358 // then a lower-bound inference is made from U for Tb.
3360 if (e is MethodGroupExpr) {
3361 if (!t.IsDelegate) {
3362 if (!t.IsExpressionTreeType)
3365 t = TypeManager.GetTypeArguments (t)[0];
3368 var invoke = Delegate.GetInvokeMethod (t);
3369 TypeSpec rtype = invoke.ReturnType;
3371 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
3374 // LAMESPEC: Standard does not specify that all methodgroup arguments
3375 // has to be fixed but it does not specify how to do recursive type inference
3376 // either. We choose the simple option and infer return type only
3377 // if all delegate generic arguments are fixed.
3378 TypeSpec[] param_types = new TypeSpec [invoke.Parameters.Count];
3379 for (int i = 0; i < param_types.Length; ++i) {
3380 var inflated = InflateGenericArgument (ec, invoke.Parameters.Types[i]);
3381 if (inflated == null)
3384 if (IsUnfixed (inflated) >= 0)
3387 param_types[i] = inflated;
3390 MethodGroupExpr mg = (MethodGroupExpr) e;
3391 Arguments args = DelegateCreation.CreateDelegateMethodArguments (invoke.Parameters, param_types, e.Location);
3392 mg = mg.OverloadResolve (ec, ref args, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
3396 return LowerBoundInference (mg.BestCandidateReturnType, rtype) + 1;
3400 // if e is an expression with type U, then
3401 // a lower-bound inference is made from U for T
3403 return LowerBoundInference (e.Type, t) * 2;
3406 void RemoveDependentTypes (List<TypeSpec> types, TypeSpec returnType)
3408 int idx = IsUnfixed (returnType);
3414 if (TypeManager.IsGenericType (returnType)) {
3415 foreach (TypeSpec t in TypeManager.GetTypeArguments (returnType)) {
3416 RemoveDependentTypes (types, t);
3421 public bool UnfixedVariableExists {
3423 foreach (TypeSpec ut in fixed_types) {