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 {
31 public class VarianceDecl
33 public VarianceDecl (Variance variance, Location loc)
35 this.Variance = variance;
39 public Variance Variance { get; private set; }
40 public Location Location { get; private set; }
42 public static Variance CheckTypeVariance (TypeSpec t, Variance expected, IMemberContext member)
44 var tp = t as TypeParameterSpec;
47 if (expected == Variance.None && v != expected ||
48 expected == Variance.Covariant && v == Variance.Contravariant ||
49 expected == Variance.Contravariant && v == Variance.Covariant) {
50 ((TypeParameter) tp.MemberDefinition).ErrorInvalidVariance (member, expected);
56 if (t.TypeArguments.Length > 0) {
57 var targs_definition = t.MemberDefinition.TypeParameters;
58 TypeSpec[] targs = TypeManager.GetTypeArguments (t);
59 for (int i = 0; i < targs.Length; ++i) {
60 var v = targs_definition[i].Variance;
61 CheckTypeVariance (targs[i], (Variance) ((int) v * (int) expected), member);
67 var ac = t as ArrayContainer;
69 return CheckTypeVariance (ac.Element, expected, member);
78 // Don't add or modify internal values, they are used as -/+ calculation signs
86 public enum SpecialConstraint
94 public class SpecialContraintExpr : FullNamedExpression
96 public SpecialContraintExpr (SpecialConstraint constraint, Location loc)
99 this.Constraint = constraint;
102 public SpecialConstraint Constraint { get; private set; }
104 protected override Expression DoResolve (ResolveContext rc)
106 throw new NotImplementedException ();
109 public override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext ec)
111 throw new NotImplementedException ();
116 // A set of parsed constraints for a type parameter
118 public class Constraints
120 readonly SimpleMemberName tparam;
121 readonly List<FullNamedExpression> constraints;
122 readonly Location loc;
126 public Constraints (SimpleMemberName tparam, List<FullNamedExpression> constraints, Location loc)
128 this.tparam = tparam;
129 this.constraints = constraints;
135 public List<FullNamedExpression> TypeExpressions {
141 public Location Location {
147 public SimpleMemberName TypeParameter {
155 public static bool CheckConflictingInheritedConstraint (TypeParameterSpec spec, TypeSpec bb, IMemberContext context, Location loc)
157 if (spec.HasSpecialClass && bb.IsStruct) {
158 context.Module.Compiler.Report.Error (455, loc,
159 "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
160 spec.Name, "class", bb.GetSignatureForError ());
165 return CheckConflictingInheritedConstraint (spec, spec.BaseType, bb, context, loc);
168 static bool CheckConflictingInheritedConstraint (TypeParameterSpec spec, TypeSpec ba, TypeSpec bb, IMemberContext context, Location loc)
173 if (TypeSpec.IsBaseClass (ba, bb, false) || TypeSpec.IsBaseClass (bb, ba, false))
176 Error_ConflictingConstraints (context, spec, ba, bb, loc);
180 public static void Error_ConflictingConstraints (IMemberContext context, TypeParameterSpec tp, TypeSpec ba, TypeSpec bb, Location loc)
182 context.Module.Compiler.Report.Error (455, loc,
183 "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
184 tp.Name, ba.GetSignatureForError (), bb.GetSignatureForError ());
187 public void CheckGenericConstraints (IMemberContext context, bool obsoleteCheck)
189 foreach (var c in constraints) {
198 ObsoleteAttribute obsolete_attr = t.GetAttributeObsolete ();
199 if (obsolete_attr != null)
200 AttributeTester.Report_ObsoleteMessage (obsolete_attr, t.GetSignatureForError (), c.Location, context.Module.Compiler.Report);
203 ConstraintChecker.Check (context, t, c.Location);
208 // Resolve the constraints types with only possible early checks, return
209 // value `false' is reserved for recursive failure
211 public bool Resolve (IMemberContext context, TypeParameter tp)
221 List<TypeParameterSpec> tparam_types = null;
222 bool iface_found = false;
224 spec.BaseType = context.Module.Compiler.BuiltinTypes.Object;
226 for (int i = 0; i < constraints.Count; ++i) {
227 var constraint = constraints[i];
229 if (constraint is SpecialContraintExpr) {
230 spec.SpecialConstraint |= ((SpecialContraintExpr) constraint).Constraint;
231 if (spec.HasSpecialStruct)
232 spec.BaseType = context.Module.Compiler.BuiltinTypes.ValueType;
234 // Set to null as it does not have a type
235 constraints[i] = null;
239 var type = constraint.ResolveAsType (context);
243 if (type.Arity > 0 && ((InflatedTypeSpec) type).HasDynamicArgument ()) {
244 context.Module.Compiler.Report.Error (1968, constraint.Location,
245 "A constraint cannot be the dynamic type `{0}'", type.GetSignatureForError ());
249 if (!context.CurrentMemberDefinition.IsAccessibleAs (type)) {
250 context.Module.Compiler.Report.SymbolRelatedToPreviousError (type);
251 context.Module.Compiler.Report.Error (703, loc,
252 "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
253 type.GetSignatureForError (), context.GetSignatureForError ());
256 if (type.IsInterface) {
257 if (!spec.AddInterface (type)) {
258 context.Module.Compiler.Report.Error (405, constraint.Location,
259 "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
267 var constraint_tp = type as TypeParameterSpec;
268 if (constraint_tp != null) {
269 if (tparam_types == null) {
270 tparam_types = new List<TypeParameterSpec> (2);
271 } else if (tparam_types.Contains (constraint_tp)) {
272 context.Module.Compiler.Report.Error (405, constraint.Location,
273 "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
278 // Checks whether each generic method parameter constraint type
279 // is valid with respect to T
281 if (tp.IsMethodTypeParameter) {
282 VarianceDecl.CheckTypeVariance (type, Variance.Contravariant, context);
285 var tp_def = constraint_tp.MemberDefinition as TypeParameter;
286 if (tp_def != null && !tp_def.ResolveConstraints (context)) {
287 context.Module.Compiler.Report.Error (454, constraint.Location,
288 "Circular constraint dependency involving `{0}' and `{1}'",
289 constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
294 // Checks whether there are no conflicts between type parameter constraints
300 // A and B are not convertible and only 1 class constraint is allowed
302 if (constraint_tp.HasTypeConstraint) {
303 if (spec.HasTypeConstraint || spec.HasSpecialStruct) {
304 if (!CheckConflictingInheritedConstraint (spec, constraint_tp.BaseType, context, constraint.Location))
307 for (int ii = 0; ii < tparam_types.Count; ++ii) {
308 if (!tparam_types[ii].HasTypeConstraint)
311 if (!CheckConflictingInheritedConstraint (spec, tparam_types[ii].BaseType, constraint_tp.BaseType, context, constraint.Location))
317 if (constraint_tp.HasSpecialStruct) {
318 context.Module.Compiler.Report.Error (456, constraint.Location,
319 "Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
320 constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
324 tparam_types.Add (constraint_tp);
328 if (iface_found || spec.HasTypeConstraint) {
329 context.Module.Compiler.Report.Error (406, constraint.Location,
330 "The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
331 type.GetSignatureForError ());
334 if (spec.HasSpecialStruct || spec.HasSpecialClass) {
335 context.Module.Compiler.Report.Error (450, constraint.Location,
336 "`{0}': cannot specify both a constraint class and the `class' or `struct' constraint",
337 type.GetSignatureForError ());
340 switch (type.BuiltinType) {
341 case BuiltinTypeSpec.Type.Array:
342 case BuiltinTypeSpec.Type.Delegate:
343 case BuiltinTypeSpec.Type.MulticastDelegate:
344 case BuiltinTypeSpec.Type.Enum:
345 case BuiltinTypeSpec.Type.ValueType:
346 case BuiltinTypeSpec.Type.Object:
347 context.Module.Compiler.Report.Error (702, constraint.Location,
348 "A constraint cannot be special class `{0}'", type.GetSignatureForError ());
350 case BuiltinTypeSpec.Type.Dynamic:
351 context.Module.Compiler.Report.Error (1967, constraint.Location,
352 "A constraint cannot be the dynamic type");
356 if (type.IsSealed || !type.IsClass) {
357 context.Module.Compiler.Report.Error (701, loc,
358 "`{0}' is not a valid constraint. A constraint must be an interface, a non-sealed class or a type parameter",
359 type.GetSignatureForError ());
364 context.Module.Compiler.Report.Error (717, constraint.Location,
365 "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
366 type.GetSignatureForError ());
369 spec.BaseType = type;
372 if (tparam_types != null)
373 spec.TypeArguments = tparam_types.ToArray ();
380 public void VerifyClsCompliance (Report report)
382 foreach (var c in constraints)
387 if (!c.Type.IsCLSCompliant ()) {
388 report.SymbolRelatedToPreviousError (c.Type);
389 report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
390 c.Type.GetSignatureForError ());
397 // A type parameter for a generic type or generic method definition
399 public class TypeParameter : MemberCore, ITypeDefinition
401 static readonly string[] attribute_target = { "type parameter" };
403 Constraints constraints;
404 GenericTypeParameterBuilder builder;
405 readonly TypeParameterSpec spec;
407 public TypeParameter (int index, MemberName name, Constraints constraints, Attributes attrs, Variance Variance)
408 : base (null, name, attrs)
410 this.constraints = constraints;
411 this.spec = new TypeParameterSpec (null, index, this, SpecialConstraint.None, Variance, null);
417 public TypeParameter (MemberName name, Attributes attrs, VarianceDecl variance)
418 : base (null, name, attrs)
420 var var = variance == null ? Variance.None : variance.Variance;
421 this.spec = new TypeParameterSpec (null, -1, this, SpecialConstraint.None, var, null);
422 this.VarianceDecl = variance;
425 public TypeParameter (TypeParameterSpec spec, TypeSpec parentSpec, MemberName name, Attributes attrs)
426 : base (null, name, attrs)
428 this.spec = new TypeParameterSpec (parentSpec, spec.DeclaredPosition, spec.MemberDefinition, spec.SpecialConstraint, spec.Variance, null) {
429 BaseType = spec.BaseType,
430 InterfacesDefined = spec.InterfacesDefined,
431 TypeArguments = spec.TypeArguments
437 public override AttributeTargets AttributeTargets {
439 return AttributeTargets.GenericParameter;
443 public Constraints Constraints {
452 public IAssemblyDefinition DeclaringAssembly {
454 return Module.DeclaringAssembly;
458 public override string DocCommentHeader {
460 throw new InvalidOperationException (
461 "Unexpected attempt to get doc comment from " + this.GetType ());
465 bool ITypeDefinition.IsComImport {
471 bool ITypeDefinition.IsPartial {
477 public bool IsMethodTypeParameter {
479 return spec.IsMethodOwned;
483 bool ITypeDefinition.IsTypeForwarder {
491 return MemberName.Name;
495 public string Namespace {
501 public TypeParameterSpec Type {
507 public int TypeParametersCount {
513 public TypeParameterSpec[] TypeParameters {
519 public override string[] ValidAttributeTargets {
521 return attribute_target;
525 public Variance Variance {
527 return spec.Variance;
531 public VarianceDecl VarianceDecl { get; private set; }
536 // This is called for each part of a partial generic type definition.
538 // If partial type parameters constraints are not null and we don't
539 // already have constraints they become our constraints. If we already
540 // have constraints, we must check that they're same.
542 public bool AddPartialConstraints (TypeDefinition part, TypeParameter tp)
545 throw new InvalidOperationException ();
547 var new_constraints = tp.constraints;
548 if (new_constraints == null)
551 // TODO: could create spec only
552 //tp.Define (null, -1, part.Definition);
553 tp.spec.DeclaringType = part.Definition;
554 if (!tp.ResolveConstraints (part))
557 if (constraints != null)
558 return spec.HasSameConstraintsDefinition (tp.Type);
560 // Copy constraint from resolved part to partial container
561 spec.SpecialConstraint = tp.spec.SpecialConstraint;
562 spec.InterfacesDefined = tp.spec.InterfacesDefined;
563 spec.TypeArguments = tp.spec.TypeArguments;
564 spec.BaseType = tp.spec.BaseType;
569 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
571 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
574 public void CheckGenericConstraints (bool obsoleteCheck)
576 if (constraints != null)
577 constraints.CheckGenericConstraints (this, obsoleteCheck);
580 public TypeParameter CreateHoistedCopy (TypeSpec declaringSpec)
582 return new TypeParameter (spec, declaringSpec, MemberName, null);
585 public override bool Define ()
591 // This is the first method which is called during the resolving
592 // process; we're called immediately after creating the type parameters
593 // with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
596 public void Create (TypeSpec declaringType, TypeContainer parent)
599 throw new InternalErrorException ();
601 // Needed to get compiler reference
602 this.Parent = parent;
603 spec.DeclaringType = declaringType;
606 public void Define (GenericTypeParameterBuilder type)
609 spec.SetMetaInfo (type);
612 public void EmitConstraints (GenericTypeParameterBuilder builder)
614 var attr = GenericParameterAttributes.None;
615 if (spec.Variance == Variance.Contravariant)
616 attr |= GenericParameterAttributes.Contravariant;
617 else if (spec.Variance == Variance.Covariant)
618 attr |= GenericParameterAttributes.Covariant;
620 if (spec.HasSpecialClass)
621 attr |= GenericParameterAttributes.ReferenceTypeConstraint;
622 else if (spec.HasSpecialStruct)
623 attr |= GenericParameterAttributes.NotNullableValueTypeConstraint | GenericParameterAttributes.DefaultConstructorConstraint;
625 if (spec.HasSpecialConstructor)
626 attr |= GenericParameterAttributes.DefaultConstructorConstraint;
628 if (spec.BaseType.BuiltinType != BuiltinTypeSpec.Type.Object)
629 builder.SetBaseTypeConstraint (spec.BaseType.GetMetaInfo ());
631 if (spec.InterfacesDefined != null)
632 builder.SetInterfaceConstraints (spec.InterfacesDefined.Select (l => l.GetMetaInfo ()).ToArray ());
634 if (spec.TypeArguments != null) {
635 var meta_constraints = new List<MetaType> (spec.TypeArguments.Length);
636 foreach (var c in spec.TypeArguments) {
638 // Inflated type parameters can collide with special constraint types, don't
639 // emit any such type parameter.
641 if (c.BuiltinType == BuiltinTypeSpec.Type.Object || c.BuiltinType == BuiltinTypeSpec.Type.ValueType)
644 meta_constraints.Add (c.GetMetaInfo ());
647 builder.SetInterfaceConstraints (meta_constraints.ToArray ());
650 builder.SetGenericParameterAttributes (attr);
653 public override void Emit ()
655 EmitConstraints (builder);
657 if (OptAttributes != null)
658 OptAttributes.Emit ();
663 public void ErrorInvalidVariance (IMemberContext mc, Variance expected)
665 Report.SymbolRelatedToPreviousError (mc.CurrentMemberDefinition);
666 string input_variance = Variance == Variance.Contravariant ? "contravariant" : "covariant";
667 string gtype_variance;
669 case Variance.Contravariant: gtype_variance = "contravariantly"; break;
670 case Variance.Covariant: gtype_variance = "covariantly"; break;
671 default: gtype_variance = "invariantly"; break;
674 Delegate d = mc as Delegate;
675 string parameters = d != null ? d.Parameters.GetSignatureForError () : "";
677 Report.Error (1961, Location,
678 "The {2} type parameter `{0}' must be {3} valid on `{1}{4}'",
679 GetSignatureForError (), mc.GetSignatureForError (), input_variance, gtype_variance, parameters);
682 public TypeSpec GetAttributeCoClass ()
687 public string GetAttributeDefaultMember ()
689 throw new NotSupportedException ();
692 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
694 throw new NotSupportedException ();
697 public override string GetSignatureForDocumentation ()
699 throw new NotImplementedException ();
702 public override string GetSignatureForError ()
704 return MemberName.Name;
707 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
709 return spec.MemberDefinition.DeclaringAssembly == assembly;
712 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
714 throw new NotSupportedException ("Not supported for compiled definition");
718 // Resolves all type parameter constraints
720 public bool ResolveConstraints (IMemberContext context)
722 if (constraints != null)
723 return constraints.Resolve (context, this);
725 if (spec.BaseType == null)
726 spec.BaseType = context.Module.Compiler.BuiltinTypes.Object;
731 public override bool IsClsComplianceRequired ()
736 public new void VerifyClsCompliance ()
738 if (constraints != null)
739 constraints.VerifyClsCompliance (Report);
742 public void WarningParentNameConflict (TypeParameter conflict)
744 conflict.Report.SymbolRelatedToPreviousError (conflict.Location, null);
745 conflict.Report.Warning (693, 3, Location,
746 "Type parameter `{0}' has the same name as the type parameter from outer type `{1}'",
747 GetSignatureForError (), conflict.CurrentType.GetSignatureForError ());
751 [System.Diagnostics.DebuggerDisplay ("{DisplayDebugInfo()}")]
752 public class TypeParameterSpec : TypeSpec
754 public static readonly new TypeParameterSpec[] EmptyTypes = new TypeParameterSpec[0];
757 SpecialConstraint spec;
760 TypeSpec[] ifaces_defined;
763 // Creates type owned type parameter
765 public TypeParameterSpec (TypeSpec declaringType, int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
766 : base (MemberKind.TypeParameter, declaringType, definition, info, Modifiers.PUBLIC)
768 this.variance = variance;
770 state &= ~StateFlags.Obsolete_Undetected;
775 // Creates method owned type parameter
777 public TypeParameterSpec (int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
778 : this (null, index, definition, spec, variance, info)
784 public int DeclaredPosition {
793 public bool HasSpecialConstructor {
795 return (spec & SpecialConstraint.Constructor) != 0;
799 public bool HasSpecialClass {
801 return (spec & SpecialConstraint.Class) != 0;
805 public bool HasSpecialStruct {
807 return (spec & SpecialConstraint.Struct) != 0;
811 public bool HasAnyTypeConstraint {
813 return (spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0 || ifaces != null || targs != null || HasTypeConstraint;
817 public bool HasTypeConstraint {
819 var bt = BaseType.BuiltinType;
820 return bt != BuiltinTypeSpec.Type.Object && bt != BuiltinTypeSpec.Type.ValueType;
824 public override IList<TypeSpec> Interfaces {
826 if ((state & StateFlags.InterfacesExpanded) == 0) {
827 if (ifaces != null) {
828 if (ifaces_defined == null)
829 ifaces_defined = ifaces.ToArray ();
831 for (int i = 0; i < ifaces_defined.Length; ++i ) {
832 var iface_type = ifaces_defined[i];
833 var td = iface_type.MemberDefinition as TypeDefinition;
835 td.DoExpandBaseInterfaces ();
837 if (iface_type.Interfaces != null) {
838 for (int ii = 0; ii < iface_type.Interfaces.Count; ++ii) {
839 var ii_iface_type = iface_type.Interfaces [ii];
840 AddInterface (ii_iface_type);
844 } else if (ifaces_defined == null) {
845 ifaces_defined = ifaces == null ? TypeSpec.EmptyTypes : ifaces.ToArray ();
849 // Include all base type interfaces too, see ImportTypeBase for details
851 if (BaseType != null) {
852 var td = BaseType.MemberDefinition as TypeDefinition;
854 td.DoExpandBaseInterfaces ();
856 if (BaseType.Interfaces != null) {
857 foreach (var iface in BaseType.Interfaces) {
858 AddInterface (iface);
863 state |= StateFlags.InterfacesExpanded;
871 // Unexpanded interfaces list
873 public TypeSpec[] InterfacesDefined {
875 if (ifaces_defined == null) {
876 ifaces_defined = ifaces == null ? TypeSpec.EmptyTypes : ifaces.ToArray ();
879 return ifaces_defined.Length == 0 ? null : ifaces_defined;
882 ifaces_defined = value;
883 if (value != null && value.Length != 0)
884 ifaces = new List<TypeSpec> (value);
888 public bool IsConstrained {
890 return spec != SpecialConstraint.None || ifaces != null || targs != null || HasTypeConstraint;
895 // Returns whether the type parameter is known to be a reference type
897 public new bool IsReferenceType {
899 if ((spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0)
900 return (spec & SpecialConstraint.Class) != 0;
903 // Full check is needed (see IsValueType for details)
905 if (HasTypeConstraint && TypeSpec.IsReferenceType (BaseType))
909 foreach (var ta in targs) {
911 // Secondary special constraints are ignored (I am not sure why)
913 var tp = ta as TypeParameterSpec;
914 if (tp != null && (tp.spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0)
917 if (TypeSpec.IsReferenceType (ta))
927 // Returns whether the type parameter is known to be a value type
929 public new bool IsValueType {
932 // Even if structs/enums cannot be used directly as constraints
933 // they can apear as constraint type when inheriting base constraint
934 // which has dependant type parameter constraint which has been
935 // inflated using value type
937 // class A : B<int> { override void Foo<U> () {} }
938 // class B<T> { virtual void Foo<U> () where U : T {} }
940 if (HasSpecialStruct)
944 foreach (var ta in targs) {
945 if (TypeSpec.IsValueType (ta))
954 public override string Name {
956 return definition.Name;
960 public bool IsMethodOwned {
962 return DeclaringType == null;
966 public SpecialConstraint SpecialConstraint {
976 // Types used to inflate the generic type
978 public new TypeSpec[] TypeArguments {
987 public Variance Variance {
995 public string DisplayDebugInfo ()
997 var s = GetSignatureForError ();
998 return IsMethodOwned ? s + "!!" : s + "!";
1002 // Finds effective base class. The effective base class is always a class-type
1004 public TypeSpec GetEffectiveBase ()
1006 if (HasSpecialStruct)
1010 // If T has a class-type constraint C but no type-parameter constraints, its effective base class is C
1012 if (BaseType != null && targs == null) {
1014 // 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.
1016 // LAMESPEC: Is System.ValueType always the most specific base type in this case?
1018 // Note: This can never happen in an explicitly given constraint, but may occur when the constraints of a generic method
1019 // are implicitly inherited by an overriding method declaration or an explicit implementation of an interface method.
1021 return BaseType.IsStruct ? BaseType.BaseType : BaseType;
1025 if (HasTypeConstraint) {
1026 Array.Resize (ref types, types.Length + 1);
1028 for (int i = 0; i < types.Length - 1; ++i) {
1029 types[i] = types[i].BaseType;
1032 types[types.Length - 1] = BaseType;
1034 types = types.Select (l => l.BaseType).ToArray ();
1038 return Convert.FindMostEncompassedType (types);
1043 public override string GetSignatureForDocumentation ()
1045 var prefix = IsMethodOwned ? "``" : "`";
1046 return prefix + DeclaredPosition;
1049 public override string GetSignatureForError ()
1055 // Constraints have to match by definition but not position, used by
1056 // partial classes or methods
1058 public bool HasSameConstraintsDefinition (TypeParameterSpec other)
1060 if (spec != other.spec)
1063 if (BaseType != other.BaseType)
1066 if (!TypeSpecComparer.Override.IsSame (InterfacesDefined, other.InterfacesDefined))
1069 if (!TypeSpecComparer.Override.IsSame (targs, other.targs))
1076 // Constraints have to match by using same set of types, used by
1077 // implicit interface implementation
1079 public bool HasSameConstraintsImplementation (TypeParameterSpec other)
1081 if (spec != other.spec)
1085 // It can be same base type or inflated type parameter
1087 // interface I<T> { void Foo<U> where U : T; }
1088 // class A : I<int> { void Foo<X> where X : int {} }
1091 if (!TypeSpecComparer.Override.IsEqual (BaseType, other.BaseType)) {
1092 if (other.targs == null)
1096 foreach (var otarg in other.targs) {
1097 if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
1107 // Check interfaces implementation -> definition
1108 if (InterfacesDefined != null) {
1110 // Iterate over inflated interfaces
1112 foreach (var iface in Interfaces) {
1114 if (other.InterfacesDefined != null) {
1115 foreach (var oiface in other.Interfaces) {
1116 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
1126 if (other.targs != null) {
1127 foreach (var otarg in other.targs) {
1128 if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
1140 // Check interfaces implementation <- definition
1141 if (other.InterfacesDefined != null) {
1142 if (InterfacesDefined == null)
1146 // Iterate over inflated interfaces
1148 foreach (var oiface in other.Interfaces) {
1150 foreach (var iface in Interfaces) {
1151 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
1162 // Check type parameters implementation -> definition
1163 if (targs != null) {
1164 if (other.targs == null)
1167 foreach (var targ in targs) {
1169 foreach (var otarg in other.targs) {
1170 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
1181 // Check type parameters implementation <- definition
1182 if (other.targs != null) {
1183 foreach (var otarg in other.targs) {
1184 // Ignore inflated type arguments, were checked above
1185 if (!otarg.IsGenericParameter)
1192 foreach (var targ in targs) {
1193 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
1207 public static TypeParameterSpec[] InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec[] tparams)
1209 return InflateConstraints (tparams, l => l, inflator);
1212 public static TypeParameterSpec[] InflateConstraints<T> (TypeParameterSpec[] tparams, Func<T, TypeParameterInflator> inflatorFactory, T arg)
1214 TypeParameterSpec[] constraints = null;
1215 TypeParameterInflator? inflator = null;
1217 for (int i = 0; i < tparams.Length; ++i) {
1218 var tp = tparams[i];
1219 if (tp.HasTypeConstraint || tp.InterfacesDefined != null || tp.TypeArguments != null) {
1220 if (constraints == null) {
1221 constraints = new TypeParameterSpec[tparams.Length];
1222 Array.Copy (tparams, constraints, constraints.Length);
1226 // Using a factory to avoid possibly expensive inflator build up
1228 if (inflator == null)
1229 inflator = inflatorFactory (arg);
1231 constraints[i] = (TypeParameterSpec) constraints[i].InflateMember (inflator.Value);
1235 if (constraints == null)
1236 constraints = tparams;
1241 public void InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec tps)
1243 tps.BaseType = inflator.Inflate (BaseType);
1245 var defined = InterfacesDefined;
1246 if (defined != null) {
1247 tps.ifaces_defined = new TypeSpec[defined.Length];
1248 for (int i = 0; i < defined.Length; ++i)
1249 tps.ifaces_defined [i] = inflator.Inflate (defined[i]);
1250 } else if (ifaces_defined == TypeSpec.EmptyTypes) {
1251 tps.ifaces_defined = TypeSpec.EmptyTypes;
1254 var ifaces = Interfaces;
1255 if (ifaces != null) {
1256 tps.ifaces = new List<TypeSpec> (ifaces.Count);
1257 for (int i = 0; i < ifaces.Count; ++i)
1258 tps.ifaces.Add (inflator.Inflate (ifaces[i]));
1259 tps.state |= StateFlags.InterfacesExpanded;
1262 if (targs != null) {
1263 tps.targs = new TypeSpec[targs.Length];
1264 for (int i = 0; i < targs.Length; ++i)
1265 tps.targs[i] = inflator.Inflate (targs[i]);
1269 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1271 var tps = (TypeParameterSpec) MemberwiseClone ();
1276 InflateConstraints (inflator, tps);
1281 // Populates type parameter members using type parameter constraints
1282 // The trick here is to be called late enough but not too late to
1283 // populate member cache with all members from other types
1285 protected override void InitializeMemberCache (bool onlyTypes)
1287 cache = new MemberCache ();
1290 // For a type parameter the membercache is the union of the sets of members of the types
1291 // specified as a primary constraint or secondary constraint
1293 if (BaseType.BuiltinType != BuiltinTypeSpec.Type.Object && BaseType.BuiltinType != BuiltinTypeSpec.Type.ValueType)
1294 cache.AddBaseType (BaseType);
1296 if (InterfacesDefined != null) {
1297 foreach (var iface_type in InterfacesDefined) {
1298 cache.AddInterface (iface_type);
1302 if (targs != null) {
1303 foreach (var ta in targs) {
1304 var b_type = ta.BaseType;
1305 if (b_type.BuiltinType != BuiltinTypeSpec.Type.Object && b_type.BuiltinType != BuiltinTypeSpec.Type.ValueType)
1306 cache.AddBaseType (b_type);
1308 var tps = ta as TypeParameterSpec;
1309 var ifaces = tps != null ? tps.InterfacesDefined : ta.Interfaces;
1311 if (ifaces != null) {
1312 foreach (var iface_type in ifaces) {
1313 cache.AddInterface (iface_type);
1320 public bool IsConvertibleToInterface (TypeSpec iface)
1322 if (Interfaces != null) {
1323 foreach (var t in Interfaces) {
1329 if (TypeArguments != null) {
1330 foreach (var t in TypeArguments) {
1331 if (((TypeParameterSpec) t).IsConvertibleToInterface (iface))
1339 public static bool HasAnyTypeParameterTypeConstrained (IGenericMethodDefinition md)
1341 var tps = md.TypeParameters;
1342 for (int i = 0; i < md.TypeParametersCount; ++i) {
1343 if (tps[i].HasAnyTypeConstraint) {
1351 public static bool HasAnyTypeParameterConstrained (IGenericMethodDefinition md)
1353 var tps = md.TypeParameters;
1354 for (int i = 0; i < md.TypeParametersCount; ++i) {
1355 if (tps[i].IsConstrained) {
1363 public bool HasDependencyOn (TypeSpec type)
1365 if (TypeArguments != null) {
1366 foreach (var targ in TypeArguments) {
1367 if (TypeSpecComparer.Override.IsEqual (targ, type))
1370 var tps = targ as TypeParameterSpec;
1371 if (tps != null && tps.HasDependencyOn (type))
1379 public override TypeSpec Mutate (TypeParameterMutator mutator)
1381 return mutator.Mutate (this);
1385 public struct TypeParameterInflator
1387 readonly TypeSpec type;
1388 readonly TypeParameterSpec[] tparams;
1389 readonly TypeSpec[] targs;
1390 readonly IModuleContext context;
1392 public TypeParameterInflator (TypeParameterInflator nested, TypeSpec type)
1393 : this (nested.context, type, nested.tparams, nested.targs)
1397 public TypeParameterInflator (IModuleContext context, TypeSpec type, TypeParameterSpec[] tparams, TypeSpec[] targs)
1399 if (tparams.Length != targs.Length)
1400 throw new ArgumentException ("Invalid arguments");
1402 this.context = context;
1403 this.tparams = tparams;
1410 public IModuleContext Context {
1416 public TypeSpec TypeInstance {
1423 // Type parameters to inflate
1425 public TypeParameterSpec[] TypeParameters {
1433 public TypeSpec Inflate (TypeSpec type)
1435 var tp = type as TypeParameterSpec;
1437 return Inflate (tp);
1439 var ac = type as ArrayContainer;
1441 var et = Inflate (ac.Element);
1442 if (et != ac.Element)
1443 return ArrayContainer.MakeType (context.Module, et, ac.Rank);
1448 if (type.Kind == MemberKind.MissingType)
1452 // When inflating a nested type, inflate its parent first
1453 // in case it's using same type parameters (was inflated within the type)
1457 if (type.IsNested) {
1458 var parent = Inflate (type.DeclaringType);
1461 // Keep the inflated type arguments
1463 targs = type.TypeArguments;
1466 // When inflating imported nested type used inside same declaring type, we get TypeSpec
1467 // because the import cache helps us to catch it. However, that means we have to look at
1468 // type definition to get type argument (they are in fact type parameter in this case)
1470 if (targs.Length == 0 && type.Arity > 0)
1471 targs = type.MemberDefinition.TypeParameters;
1474 // Parent was inflated, find the same type on inflated type
1475 // to use same cache for nested types on same generic parent
1477 type = MemberCache.FindNestedType (parent, type.Name, type.Arity);
1480 // Handle the tricky case where parent shares local type arguments
1481 // which means inflating inflated type
1484 // public static Nested<T> Foo () { return null; }
1486 // public class Nested<U> {}
1489 // return type of Test<string>.Foo() has to be Test<string>.Nested<string>
1491 if (targs.Length > 0) {
1492 var inflated_targs = new TypeSpec[targs.Length];
1493 for (; i < targs.Length; ++i)
1494 inflated_targs[i] = Inflate (targs[i]);
1496 type = type.MakeGenericType (context, inflated_targs);
1502 // Nothing to do for non-generic type
1503 if (type.Arity == 0)
1506 targs = new TypeSpec[type.Arity];
1509 // Inflating using outside type arguments, var v = new Foo<int> (), class Foo<T> {}
1511 if (type is InflatedTypeSpec) {
1512 for (; i < targs.Length; ++i)
1513 targs[i] = Inflate (type.TypeArguments[i]);
1515 type = type.GetDefinition ();
1518 // Inflating parent using inside type arguments, class Foo<T> { ITest<T> foo; }
1520 var args = type.MemberDefinition.TypeParameters;
1521 foreach (var ds_tp in args)
1522 targs[i++] = Inflate (ds_tp);
1525 return type.MakeGenericType (context, targs);
1528 public TypeSpec Inflate (TypeParameterSpec tp)
1530 for (int i = 0; i < tparams.Length; ++i)
1531 if (tparams [i] == tp)
1534 // This can happen when inflating nested types
1535 // without type arguments specified
1541 // Before emitting any code we have to change all MVAR references to VAR
1542 // when the method is of generic type and has hoisted variables
1544 public class TypeParameterMutator
1546 readonly TypeParameters mvar;
1547 readonly TypeParameters var;
1548 readonly TypeParameterSpec[] src;
1549 Dictionary<TypeSpec, TypeSpec> mutated_typespec;
1551 public TypeParameterMutator (TypeParameters mvar, TypeParameters var)
1553 if (mvar.Count != var.Count)
1554 throw new ArgumentException ();
1560 public TypeParameterMutator (TypeParameterSpec[] srcVar, TypeParameters destVar)
1562 if (srcVar.Length != destVar.Count)
1563 throw new ArgumentException ();
1571 public TypeParameters MethodTypeParameters {
1579 public static TypeSpec GetMemberDeclaringType (TypeSpec type)
1581 if (type is InflatedTypeSpec) {
1582 if (type.DeclaringType == null)
1583 return type.GetDefinition ();
1585 var parent = GetMemberDeclaringType (type.DeclaringType);
1586 type = MemberCache.GetMember<TypeSpec> (parent, type);
1592 public TypeSpec Mutate (TypeSpec ts)
1595 if (mutated_typespec != null && mutated_typespec.TryGetValue (ts, out value))
1598 value = ts.Mutate (this);
1599 if (mutated_typespec == null)
1600 mutated_typespec = new Dictionary<TypeSpec, TypeSpec> ();
1602 mutated_typespec.Add (ts, value);
1606 public TypeParameterSpec Mutate (TypeParameterSpec tp)
1609 for (int i = 0; i < mvar.Count; ++i) {
1610 if (mvar[i].Type == tp)
1614 for (int i = 0; i < src.Length; ++i) {
1623 public TypeSpec[] Mutate (TypeSpec[] targs)
1625 TypeSpec[] mutated = new TypeSpec[targs.Length];
1626 bool changed = false;
1627 for (int i = 0; i < targs.Length; ++i) {
1628 mutated[i] = Mutate (targs[i]);
1629 changed |= targs[i] != mutated[i];
1632 return changed ? mutated : targs;
1637 /// A TypeExpr which already resolved to a type parameter.
1639 public class TypeParameterExpr : TypeExpression
1641 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1642 : base (type_parameter.Type, loc)
1644 this.eclass = ExprClass.TypeParameter;
1648 public class InflatedTypeSpec : TypeSpec
1651 TypeParameterSpec[] constraints;
1652 readonly TypeSpec open_type;
1653 readonly IModuleContext context;
1655 public InflatedTypeSpec (IModuleContext context, TypeSpec openType, TypeSpec declaringType, TypeSpec[] targs)
1656 : base (openType.Kind, declaringType, openType.MemberDefinition, null, openType.Modifiers)
1659 throw new ArgumentNullException ("targs");
1661 this.state &= ~SharedStateFlags;
1662 this.state |= (openType.state & SharedStateFlags);
1664 this.context = context;
1665 this.open_type = openType;
1668 foreach (var arg in targs) {
1669 if (arg.HasDynamicElement || arg.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1670 state |= StateFlags.HasDynamicElement;
1675 if (open_type.Kind == MemberKind.MissingType)
1676 MemberCache = MemberCache.Empty;
1678 if ((open_type.Modifiers & Modifiers.COMPILER_GENERATED) != 0)
1679 state |= StateFlags.ConstraintsChecked;
1684 public override TypeSpec BaseType {
1686 if (cache == null || (state & StateFlags.PendingBaseTypeInflate) != 0)
1687 InitializeMemberCache (true);
1689 return base.BaseType;
1694 // Inflated type parameters with constraints array, mapping with type arguments is based on index
1696 public TypeParameterSpec[] Constraints {
1698 if (constraints == null) {
1699 constraints = TypeParameterSpec.InflateConstraints (MemberDefinition.TypeParameters, l => l.CreateLocalInflator (context), this);
1707 // Used to cache expensive constraints validation on constructed types
1709 public bool HasConstraintsChecked {
1711 return (state & StateFlags.ConstraintsChecked) != 0;
1714 state = value ? state | StateFlags.ConstraintsChecked : state & ~StateFlags.ConstraintsChecked;
1718 public override IList<TypeSpec> Interfaces {
1721 InitializeMemberCache (true);
1723 return base.Interfaces;
1727 public override bool IsExpressionTreeType {
1729 return (open_type.state & StateFlags.InflatedExpressionType) != 0;
1733 public override bool IsArrayGenericInterface {
1735 return (open_type.state & StateFlags.GenericIterateInterface) != 0;
1739 public override bool IsGenericTask {
1741 return (open_type.state & StateFlags.GenericTask) != 0;
1745 public override bool IsNullableType {
1747 return (open_type.state & StateFlags.InflatedNullableType) != 0;
1752 // Types used to inflate the generic type
1754 public override TypeSpec[] TypeArguments {
1762 public override bool AddInterface (TypeSpec iface)
1764 var inflator = CreateLocalInflator (context);
1765 iface = inflator.Inflate (iface);
1769 return base.AddInterface (iface);
1772 public static bool ContainsTypeParameter (TypeSpec type)
1774 if (type.Kind == MemberKind.TypeParameter)
1777 var element_container = type as ElementTypeSpec;
1778 if (element_container != null)
1779 return ContainsTypeParameter (element_container.Element);
1781 foreach (var t in type.TypeArguments) {
1782 if (ContainsTypeParameter (t)) {
1790 public TypeParameterInflator CreateLocalInflator (IModuleContext context)
1792 TypeParameterSpec[] tparams_full;
1793 TypeSpec[] targs_full = targs;
1796 // Special case is needed when we are inflating an open type (nested type definition)
1797 // on inflated parent. Consider following case
1799 // Foo<T>.Bar<U> => Foo<string>.Bar<U>
1801 // Any later inflation of Foo<string>.Bar<U> has to also inflate T if used inside Bar<U>
1803 List<TypeSpec> merged_targs = null;
1804 List<TypeParameterSpec> merged_tparams = null;
1806 var type = DeclaringType;
1809 if (type.TypeArguments.Length > 0) {
1810 if (merged_targs == null) {
1811 merged_targs = new List<TypeSpec> ();
1812 merged_tparams = new List<TypeParameterSpec> ();
1813 if (targs.Length > 0) {
1814 merged_targs.AddRange (targs);
1815 merged_tparams.AddRange (open_type.MemberDefinition.TypeParameters);
1818 merged_tparams.AddRange (type.MemberDefinition.TypeParameters);
1819 merged_targs.AddRange (type.TypeArguments);
1821 type = type.DeclaringType;
1822 } while (type != null);
1824 if (merged_targs != null) {
1825 // Type arguments are not in the right order but it should not matter in this case
1826 targs_full = merged_targs.ToArray ();
1827 tparams_full = merged_tparams.ToArray ();
1828 } else if (targs.Length == 0) {
1829 tparams_full = TypeParameterSpec.EmptyTypes;
1831 tparams_full = open_type.MemberDefinition.TypeParameters;
1833 } else if (targs.Length == 0) {
1834 tparams_full = TypeParameterSpec.EmptyTypes;
1836 tparams_full = open_type.MemberDefinition.TypeParameters;
1839 return new TypeParameterInflator (context, this, tparams_full, targs_full);
1842 MetaType CreateMetaInfo ()
1845 // Converts nested type arguments into right order
1846 // Foo<string, bool>.Bar<int> => string, bool, int
1848 var all = new List<MetaType> ();
1849 TypeSpec type = this;
1850 TypeSpec definition = type;
1852 if (type.GetDefinition().IsGeneric) {
1854 type.TypeArguments != TypeSpec.EmptyTypes ?
1855 type.TypeArguments.Select (l => l.GetMetaInfo ()) :
1856 type.MemberDefinition.TypeParameters.Select (l => l.GetMetaInfo ()));
1859 definition = definition.GetDefinition ();
1860 type = type.DeclaringType;
1861 } while (type != null);
1863 return definition.GetMetaInfo ().MakeGenericType (all.ToArray ());
1866 public override ObsoleteAttribute GetAttributeObsolete ()
1868 return open_type.GetAttributeObsolete ();
1871 protected override bool IsNotCLSCompliant (out bool attrValue)
1873 if (base.IsNotCLSCompliant (out attrValue))
1876 foreach (var ta in TypeArguments) {
1877 if (ta.MemberDefinition.CLSAttributeValue == false)
1884 public override TypeSpec GetDefinition ()
1889 public override MetaType GetMetaInfo ()
1892 info = CreateMetaInfo ();
1897 public override string GetSignatureForError ()
1900 return targs[0].GetSignatureForError () + "?";
1902 return base.GetSignatureForError ();
1905 protected override string GetTypeNameSignature ()
1907 if (targs.Length == 0 || MemberDefinition is AnonymousTypeClass)
1910 return "<" + TypeManager.CSharpName (targs) + ">";
1913 public bool HasDynamicArgument ()
1915 for (int i = 0; i < targs.Length; ++i) {
1916 var item = targs[i];
1918 if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1921 if (item is InflatedTypeSpec) {
1922 if (((InflatedTypeSpec) item).HasDynamicArgument ())
1929 while (item.IsArray) {
1930 item = ((ArrayContainer) item).Element;
1933 if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1941 protected override void InitializeMemberCache (bool onlyTypes)
1943 if (cache == null) {
1944 var open_cache = onlyTypes ? open_type.MemberCacheTypes : open_type.MemberCache;
1946 // Surprisingly, calling MemberCache on open type could meantime create cache on this type
1947 // for imported type parameter constraints referencing nested type of this declaration
1949 cache = new MemberCache (open_cache);
1952 var inflator = CreateLocalInflator (context);
1955 // Two stage inflate due to possible nested types recursive
1965 // When resolving type of `b' members of `B' cannot be
1966 // inflated because are not yet available in membercache
1968 if ((state & StateFlags.PendingMemberCacheMembers) == 0) {
1969 open_type.MemberCacheTypes.InflateTypes (cache, inflator);
1972 // Inflate any implemented interfaces
1974 if (open_type.Interfaces != null) {
1975 ifaces = new List<TypeSpec> (open_type.Interfaces.Count);
1976 foreach (var iface in open_type.Interfaces) {
1977 var iface_inflated = inflator.Inflate (iface);
1978 if (iface_inflated == null)
1981 base.AddInterface (iface_inflated);
1986 // Handles the tricky case of recursive nested base generic type
1988 // class A<T> : Base<A<T>.Nested> {
1992 // When inflating A<T>. base type is not yet known, secondary
1993 // inflation is required (not common case) once base scope
1996 if (open_type.BaseType == null) {
1998 state |= StateFlags.PendingBaseTypeInflate;
2000 BaseType = inflator.Inflate (open_type.BaseType);
2002 } else if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
2004 // It can happen when resolving base type without being defined
2005 // which is not allowed to happen and will always lead to an error
2007 // class B { class N {} }
2008 // class A<T> : A<B.N> {}
2010 if (open_type.BaseType == null)
2013 BaseType = inflator.Inflate (open_type.BaseType);
2014 state &= ~StateFlags.PendingBaseTypeInflate;
2018 state |= StateFlags.PendingMemberCacheMembers;
2022 var tc = open_type.MemberDefinition as TypeDefinition;
2023 if (tc != null && !tc.HasMembersDefined) {
2025 // Inflating MemberCache with undefined members
2030 if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
2031 BaseType = inflator.Inflate (open_type.BaseType);
2032 state &= ~StateFlags.PendingBaseTypeInflate;
2035 state &= ~StateFlags.PendingMemberCacheMembers;
2036 open_type.MemberCache.InflateMembers (cache, open_type, inflator);
2039 public override TypeSpec Mutate (TypeParameterMutator mutator)
2041 var targs = TypeArguments;
2043 targs = mutator.Mutate (targs);
2045 var decl = DeclaringType;
2046 if (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
2047 decl = mutator.Mutate (decl);
2049 if (targs == TypeArguments && decl == DeclaringType)
2052 var mutated = (InflatedTypeSpec) MemberwiseClone ();
2053 if (decl != DeclaringType) {
2054 // Gets back MethodInfo in case of metaInfo was inflated
2055 //mutated.info = MemberCache.GetMember<TypeSpec> (DeclaringType.GetDefinition (), this).info;
2057 mutated.declaringType = decl;
2058 mutated.state |= StateFlags.PendingMetaInflate;
2061 if (targs != null) {
2062 mutated.targs = targs;
2063 mutated.info = null;
2072 // Tracks the type arguments when instantiating a generic type. It's used
2073 // by both type arguments and type parameters
2075 public class TypeArguments
2077 List<FullNamedExpression> args;
2080 public TypeArguments (params FullNamedExpression[] types)
2082 this.args = new List<FullNamedExpression> (types);
2085 public void Add (FullNamedExpression type)
2091 /// We may only be used after Resolve() is called and return the fully
2094 // TODO: Not needed, just return type from resolve
2095 public TypeSpec[] Arguments {
2110 public virtual bool IsEmpty {
2116 public List<FullNamedExpression> TypeExpressions {
2122 public string GetSignatureForError()
2124 StringBuilder sb = new StringBuilder ();
2125 for (int i = 0; i < Count; ++i) {
2128 sb.Append (expr.GetSignatureForError ());
2134 return sb.ToString ();
2138 /// Resolve the type arguments.
2140 public virtual bool Resolve (IMemberContext ec)
2143 return atypes.Length != 0;
2145 int count = args.Count;
2148 atypes = new TypeSpec [count];
2150 for (int i = 0; i < count; i++){
2151 var te = args[i].ResolveAsType (ec);
2160 ec.Module.Compiler.Report.Error (718, args[i].Location, "`{0}': static classes cannot be used as generic arguments",
2161 te.GetSignatureForError ());
2165 if (te.IsPointer || te.IsSpecialRuntimeType) {
2166 ec.Module.Compiler.Report.Error (306, args[i].Location,
2167 "The type `{0}' may not be used as a type argument",
2168 te.GetSignatureForError ());
2174 atypes = TypeSpec.EmptyTypes;
2179 public TypeArguments Clone ()
2181 TypeArguments copy = new TypeArguments ();
2182 foreach (var ta in args)
2189 public class UnboundTypeArguments : TypeArguments
2191 public UnboundTypeArguments (int arity)
2192 : base (new FullNamedExpression[arity])
2196 public override bool IsEmpty {
2202 public override bool Resolve (IMemberContext ec)
2204 // Nothing to be resolved
2209 public class TypeParameters
2211 List<TypeParameter> names;
2212 TypeParameterSpec[] types;
2214 public TypeParameters ()
2216 names = new List<TypeParameter> ();
2219 public TypeParameters (int count)
2221 names = new List<TypeParameter> (count);
2232 public TypeParameterSpec[] Types {
2240 public void Add (TypeParameter tparam)
2245 public void Add (TypeParameters tparams)
2247 names.AddRange (tparams.names);
2250 public void Create (TypeSpec declaringType, int parentOffset, TypeContainer parent)
2252 types = new TypeParameterSpec[Count];
2253 for (int i = 0; i < types.Length; ++i) {
2256 tp.Create (declaringType, parent);
2258 types[i].DeclaredPosition = i + parentOffset;
2260 if (tp.Variance != Variance.None && !(declaringType != null && (declaringType.Kind == MemberKind.Interface || declaringType.Kind == MemberKind.Delegate))) {
2261 parent.Compiler.Report.Error (1960, tp.Location, "Variant type parameters can only be used with interfaces and delegates");
2266 public void Define (GenericTypeParameterBuilder[] builders)
2268 for (int i = 0; i < types.Length; ++i) {
2270 tp.Define (builders [types [i].DeclaredPosition]);
2274 public TypeParameter this[int index] {
2276 return names [index];
2279 names[index] = value;
2283 public TypeParameter Find (string name)
2285 foreach (var tp in names) {
2286 if (tp.Name == name)
2293 public string[] GetAllNames ()
2295 return names.Select (l => l.Name).ToArray ();
2298 public string GetSignatureForError ()
2300 StringBuilder sb = new StringBuilder ();
2301 for (int i = 0; i < Count; ++i) {
2305 var name = names[i];
2307 sb.Append (name.GetSignatureForError ());
2310 return sb.ToString ();
2314 public void CheckPartialConstraints (Method part)
2316 var partTypeParameters = part.CurrentTypeParameters;
2318 for (int i = 0; i < Count; i++) {
2319 var tp_a = names[i];
2320 var tp_b = partTypeParameters [i];
2321 if (tp_a.Constraints == null) {
2322 if (tp_b.Constraints == null)
2324 } else if (tp_b.Constraints != null && tp_a.Type.HasSameConstraintsDefinition (tp_b.Type)) {
2328 part.Compiler.Report.SymbolRelatedToPreviousError (this[i].CurrentMemberDefinition.Location, "");
2329 part.Compiler.Report.Error (761, part.Location,
2330 "Partial method declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
2331 part.GetSignatureForError (), partTypeParameters[i].GetSignatureForError ());
2335 public void UpdateConstraints (TypeDefinition part)
2337 var partTypeParameters = part.MemberName.TypeParameters;
2339 for (int i = 0; i < Count; i++) {
2341 if (tp.AddPartialConstraints (part, partTypeParameters [i]))
2344 part.Compiler.Report.SymbolRelatedToPreviousError (this[i].CurrentMemberDefinition);
2345 part.Compiler.Report.Error (265, part.Location,
2346 "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
2347 part.GetSignatureForError (), tp.GetSignatureForError ());
2351 public void VerifyClsCompliance ()
2353 foreach (var tp in names) {
2354 tp.VerifyClsCompliance ();
2360 // A type expression of generic type with type arguments
2362 class GenericTypeExpr : TypeExpr
2368 /// Instantiate the generic type `t' with the type arguments `args'.
2369 /// Use this constructor if you already know the fully resolved
2372 public GenericTypeExpr (TypeSpec open_type, TypeArguments args, Location l)
2374 this.open_type = open_type;
2379 public override string GetSignatureForError ()
2381 return type.GetSignatureForError ();
2384 public override TypeSpec ResolveAsType (IMemberContext mc)
2386 if (eclass != ExprClass.Unresolved)
2389 if (!args.Resolve (mc))
2392 TypeSpec[] atypes = args.Arguments;
2395 // Now bind the parameters
2397 var inflated = open_type.MakeGenericType (mc, atypes);
2399 eclass = ExprClass.Type;
2402 // The constraints can be checked only when full type hierarchy is known
2404 if (!inflated.HasConstraintsChecked && mc.Module.HasTypesFullyDefined) {
2405 var constraints = inflated.Constraints;
2406 if (constraints != null) {
2407 var cc = new ConstraintChecker (mc);
2408 if (cc.CheckAll (open_type, atypes, constraints, loc)) {
2409 inflated.HasConstraintsChecked = true;
2417 public override bool Equals (object obj)
2419 GenericTypeExpr cobj = obj as GenericTypeExpr;
2423 if ((type == null) || (cobj.type == null))
2426 return type == cobj.type;
2429 public override int GetHashCode ()
2431 return base.GetHashCode ();
2436 // Generic type with unbound type arguments, used for typeof (G<,,>)
2438 class GenericOpenTypeExpr : TypeExpression
2440 public GenericOpenTypeExpr (TypeSpec type, /*UnboundTypeArguments args,*/ Location loc)
2441 : base (type.GetDefinition (), loc)
2446 struct ConstraintChecker
2449 bool recursive_checks;
2451 public ConstraintChecker (IMemberContext ctx)
2454 recursive_checks = false;
2458 // Checks the constraints of open generic type against type
2459 // arguments. This version is used for types which could not be
2460 // checked immediatelly during construction because the type
2461 // hierarchy was not yet fully setup (before Emit phase)
2463 public static bool Check (IMemberContext mc, TypeSpec type, Location loc)
2466 // Check declaring type first if there is any
2468 if (type.DeclaringType != null && !Check (mc, type.DeclaringType, loc))
2471 while (type is ElementTypeSpec)
2472 type = ((ElementTypeSpec) type).Element;
2474 if (type.Arity == 0)
2477 var gtype = type as InflatedTypeSpec;
2481 var constraints = gtype.Constraints;
2482 if (constraints == null)
2485 if (gtype.HasConstraintsChecked)
2488 var cc = new ConstraintChecker (mc);
2489 cc.recursive_checks = true;
2491 if (cc.CheckAll (gtype.GetDefinition (), type.TypeArguments, constraints, loc)) {
2492 gtype.HasConstraintsChecked = true;
2500 // Checks all type arguments againts type parameters constraints
2501 // NOTE: It can run in probing mode when `this.mc' is null
2503 public bool CheckAll (MemberSpec context, TypeSpec[] targs, TypeParameterSpec[] tparams, Location loc)
2505 for (int i = 0; i < tparams.Length; i++) {
2506 var targ = targs[i];
2507 if (!CheckConstraint (context, targ, tparams [i], loc))
2510 if (!recursive_checks)
2513 if (!Check (mc, targ, loc))
2520 bool CheckConstraint (MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, Location loc)
2523 // First, check the `class' and `struct' constraints.
2525 if (tparam.HasSpecialClass && !TypeSpec.IsReferenceType (atype)) {
2527 mc.Module.Compiler.Report.Error (452, loc,
2528 "The type `{0}' must be a reference type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
2529 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
2535 if (tparam.HasSpecialStruct && (!TypeSpec.IsValueType (atype) || atype.IsNullableType)) {
2537 mc.Module.Compiler.Report.Error (453, loc,
2538 "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}'",
2539 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
2548 // Check the class constraint
2550 if (tparam.HasTypeConstraint) {
2551 if (!CheckConversion (mc, context, atype, tparam, tparam.BaseType, loc)) {
2560 // Check the interfaces constraints
2562 if (tparam.InterfacesDefined != null) {
2563 foreach (TypeSpec iface in tparam.InterfacesDefined) {
2564 if (!CheckConversion (mc, context, atype, tparam, iface, loc)) {
2575 // Check the type parameter constraint
2577 if (tparam.TypeArguments != null) {
2578 foreach (var ta in tparam.TypeArguments) {
2579 if (!CheckConversion (mc, context, atype, tparam, ta, loc)) {
2590 // Finally, check the constructor constraint.
2592 if (!tparam.HasSpecialConstructor)
2595 if (!HasDefaultConstructor (atype)) {
2597 mc.Module.Compiler.Report.SymbolRelatedToPreviousError (atype);
2598 mc.Module.Compiler.Report.Error (310, loc,
2599 "The type `{0}' must have a public parameterless constructor in order to use it as parameter `{1}' in the generic type or method `{2}'",
2600 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
2608 static bool HasDynamicTypeArgument (TypeSpec[] targs)
2610 for (int i = 0; i < targs.Length; ++i) {
2611 var targ = targs [i];
2612 if (targ.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2615 if (HasDynamicTypeArgument (targ.TypeArguments))
2622 bool CheckConversion (IMemberContext mc, MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, TypeSpec ttype, Location loc)
2627 if (atype.IsGenericParameter) {
2628 var tps = (TypeParameterSpec) atype;
2629 if (tps.HasDependencyOn (ttype))
2632 if (Convert.ImplicitTypeParameterConversion (null, tps, ttype) != null)
2635 } else if (TypeSpec.IsValueType (atype)) {
2636 if (atype.IsNullableType) {
2638 // LAMESPEC: Only identity or base type ValueType or Object satisfy nullable type
2640 if (TypeSpec.IsBaseClass (atype, ttype, false))
2643 if (Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
2647 if (Convert.ImplicitReferenceConversionExists (atype, ttype) || Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
2652 mc.Module.Compiler.Report.SymbolRelatedToPreviousError (tparam);
2653 if (atype.IsGenericParameter) {
2654 mc.Module.Compiler.Report.Error (314, loc,
2655 "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}'",
2656 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2657 } else if (TypeSpec.IsValueType (atype)) {
2658 if (atype.IsNullableType) {
2659 if (ttype.IsInterface) {
2660 mc.Module.Compiler.Report.Error (313, loc,
2661 "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}'",
2662 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2664 mc.Module.Compiler.Report.Error (312, loc,
2665 "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}'",
2666 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2669 mc.Module.Compiler.Report.Error (315, loc,
2670 "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}'",
2671 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2674 mc.Module.Compiler.Report.Error (311, loc,
2675 "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}'",
2676 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2683 static bool HasDefaultConstructor (TypeSpec atype)
2685 var tp = atype as TypeParameterSpec;
2687 return tp.HasSpecialConstructor || tp.HasSpecialStruct;
2690 if (atype.IsStruct || atype.IsEnum)
2693 if (atype.IsAbstract)
2696 var tdef = atype.GetDefinition ();
2698 var found = MemberCache.FindMember (tdef,
2699 MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters),
2700 BindingRestriction.DeclaredOnly | BindingRestriction.InstanceOnly);
2702 return found != null && (found.Modifiers & Modifiers.PUBLIC) != 0;
2707 // Implements C# type inference
2712 // Tracks successful rate of type inference
2714 int score = int.MaxValue;
2715 readonly Arguments arguments;
2716 readonly int arg_count;
2718 public TypeInference (Arguments arguments)
2720 this.arguments = arguments;
2721 if (arguments != null)
2722 arg_count = arguments.Count;
2725 public int InferenceScore {
2731 public TypeSpec[] InferMethodArguments (ResolveContext ec, MethodSpec method)
2733 var method_generic_args = method.GenericDefinition.TypeParameters;
2734 TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2735 if (!context.UnfixedVariableExists)
2736 return TypeSpec.EmptyTypes;
2738 AParametersCollection pd = method.Parameters;
2739 if (!InferInPhases (ec, context, pd))
2742 return context.InferredTypeArguments;
2746 // Implements method type arguments inference
2748 bool InferInPhases (ResolveContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
2750 int params_arguments_start;
2751 if (methodParameters.HasParams) {
2752 params_arguments_start = methodParameters.Count - 1;
2754 params_arguments_start = arg_count;
2757 TypeSpec [] ptypes = methodParameters.Types;
2760 // The first inference phase
2762 TypeSpec method_parameter = null;
2763 for (int i = 0; i < arg_count; i++) {
2764 Argument a = arguments [i];
2768 if (i < params_arguments_start) {
2769 method_parameter = methodParameters.Types [i];
2770 } else if (i == params_arguments_start) {
2771 if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2772 method_parameter = methodParameters.Types [params_arguments_start];
2774 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2776 ptypes = (TypeSpec[]) ptypes.Clone ();
2777 ptypes [i] = method_parameter;
2781 // When a lambda expression, an anonymous method
2782 // is used an explicit argument type inference takes a place
2784 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2786 if (am.ExplicitTypeInference (tic, method_parameter))
2792 score -= tic.ExactInference (a.Type, method_parameter);
2796 if (a.Expr.Type == InternalType.NullLiteral)
2799 if (TypeSpec.IsValueType (method_parameter)) {
2800 score -= tic.LowerBoundInference (a.Type, method_parameter);
2805 // Otherwise an output type inference is made
2807 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2811 // Part of the second phase but because it happens only once
2812 // we don't need to call it in cycle
2814 bool fixed_any = false;
2815 if (!tic.FixIndependentTypeArguments (ec, ptypes, ref fixed_any))
2818 return DoSecondPhase (ec, tic, ptypes, !fixed_any);
2821 bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, TypeSpec[] methodParameters, bool fixDependent)
2823 bool fixed_any = false;
2824 if (fixDependent && !tic.FixDependentTypes (ec, ref fixed_any))
2827 // If no further unfixed type variables exist, type inference succeeds
2828 if (!tic.UnfixedVariableExists)
2831 if (!fixed_any && fixDependent)
2834 // For all arguments where the corresponding argument output types
2835 // contain unfixed type variables but the input types do not,
2836 // an output type inference is made
2837 for (int i = 0; i < arg_count; i++) {
2839 // Align params arguments
2840 TypeSpec t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
2842 if (!t_i.IsDelegate) {
2843 if (!t_i.IsExpressionTreeType)
2846 t_i = TypeManager.GetTypeArguments (t_i) [0];
2849 var mi = Delegate.GetInvokeMethod (t_i);
2850 TypeSpec rtype = mi.ReturnType;
2852 if (tic.IsReturnTypeNonDependent (mi, rtype)) {
2853 // It can be null for default arguments
2854 if (arguments[i] == null)
2857 score -= tic.OutputTypeInference (ec, arguments[i].Expr, t_i);
2862 return DoSecondPhase (ec, tic, methodParameters, true);
2866 public class TypeInferenceContext
2868 protected enum BoundKind
2875 struct BoundInfo : IEquatable<BoundInfo>
2877 public readonly TypeSpec Type;
2878 public readonly BoundKind Kind;
2880 public BoundInfo (TypeSpec type, BoundKind kind)
2886 public override int GetHashCode ()
2888 return Type.GetHashCode ();
2891 public Expression GetTypeExpression ()
2893 return new TypeExpression (Type, Location.Null);
2896 #region IEquatable<BoundInfo> Members
2898 public bool Equals (BoundInfo other)
2900 return Type == other.Type && Kind == other.Kind;
2906 readonly TypeSpec[] tp_args;
2907 readonly TypeSpec[] fixed_types;
2908 readonly List<BoundInfo>[] bounds;
2911 // TODO MemberCache: Could it be TypeParameterSpec[] ??
2912 public TypeInferenceContext (TypeSpec[] typeArguments)
2914 if (typeArguments.Length == 0)
2915 throw new ArgumentException ("Empty generic arguments");
2917 fixed_types = new TypeSpec [typeArguments.Length];
2918 for (int i = 0; i < typeArguments.Length; ++i) {
2919 if (typeArguments [i].IsGenericParameter) {
2920 if (bounds == null) {
2921 bounds = new List<BoundInfo> [typeArguments.Length];
2922 tp_args = new TypeSpec [typeArguments.Length];
2924 tp_args [i] = typeArguments [i];
2926 fixed_types [i] = typeArguments [i];
2932 // Used together with AddCommonTypeBound fo implement
2933 // 7.4.2.13 Finding the best common type of a set of expressions
2935 public TypeInferenceContext ()
2937 fixed_types = new TypeSpec [1];
2938 tp_args = new TypeSpec [1];
2939 tp_args[0] = InternalType.Arglist; // it can be any internal type
2940 bounds = new List<BoundInfo> [1];
2943 public TypeSpec[] InferredTypeArguments {
2949 public void AddCommonTypeBound (TypeSpec type)
2951 AddToBounds (new BoundInfo (type, BoundKind.Lower), 0, false);
2954 public void AddCommonTypeBoundAsync (TypeSpec type)
2956 AddToBounds (new BoundInfo (type, BoundKind.Lower), 0, true);
2959 void AddToBounds (BoundInfo bound, int index, bool voidAllowed)
2962 // Some types cannot be used as type arguments
2964 if ((bound.Type.Kind == MemberKind.Void && !voidAllowed) || bound.Type.IsPointer || bound.Type.IsSpecialRuntimeType ||
2965 bound.Type == InternalType.MethodGroup || bound.Type == InternalType.AnonymousMethod)
2968 var a = bounds [index];
2970 a = new List<BoundInfo> (2);
2976 if (a.Contains (bound))
2982 bool AllTypesAreFixed (TypeSpec[] types)
2984 foreach (TypeSpec t in types) {
2985 if (t.IsGenericParameter) {
2991 if (TypeManager.IsGenericType (t))
2992 return AllTypesAreFixed (TypeManager.GetTypeArguments (t));
2999 // 26.3.3.8 Exact Inference
3001 public int ExactInference (TypeSpec u, TypeSpec v)
3003 // If V is an array type
3008 var ac_u = (ArrayContainer) u;
3009 var ac_v = (ArrayContainer) v;
3010 if (ac_u.Rank != ac_v.Rank)
3013 return ExactInference (ac_u.Element, ac_v.Element);
3016 // If V is constructed type and U is constructed type
3017 if (TypeManager.IsGenericType (v)) {
3018 if (!TypeManager.IsGenericType (u) || v.MemberDefinition != u.MemberDefinition)
3021 TypeSpec [] ga_u = TypeManager.GetTypeArguments (u);
3022 TypeSpec [] ga_v = TypeManager.GetTypeArguments (v);
3023 if (ga_u.Length != ga_v.Length)
3027 for (int i = 0; i < ga_u.Length; ++i)
3028 score += ExactInference (ga_u [i], ga_v [i]);
3030 return System.Math.Min (1, score);
3033 // If V is one of the unfixed type arguments
3034 int pos = IsUnfixed (v);
3038 AddToBounds (new BoundInfo (u, BoundKind.Exact), pos, false);
3042 public bool FixAllTypes (ResolveContext ec)
3044 for (int i = 0; i < tp_args.Length; ++i) {
3045 if (!FixType (ec, i))
3052 // All unfixed type variables Xi are fixed for which all of the following hold:
3053 // a, There is at least one type variable Xj that depends on Xi
3054 // b, Xi has a non-empty set of bounds
3056 public bool FixDependentTypes (ResolveContext ec, ref bool fixed_any)
3058 for (int i = 0; i < tp_args.Length; ++i) {
3059 if (fixed_types[i] != null)
3062 if (bounds[i] == null)
3065 if (!FixType (ec, i))
3075 // All unfixed type variables Xi which depend on no Xj are fixed
3077 public bool FixIndependentTypeArguments (ResolveContext ec, TypeSpec[] methodParameters, ref bool fixed_any)
3079 var types_to_fix = new List<TypeSpec> (tp_args);
3080 for (int i = 0; i < methodParameters.Length; ++i) {
3081 TypeSpec t = methodParameters[i];
3083 if (!t.IsDelegate) {
3084 if (!t.IsExpressionTreeType)
3087 t = TypeManager.GetTypeArguments (t) [0];
3090 if (t.IsGenericParameter)
3093 var invoke = Delegate.GetInvokeMethod (t);
3094 TypeSpec rtype = invoke.ReturnType;
3095 while (rtype.IsArray)
3096 rtype = ((ArrayContainer) rtype).Element;
3098 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
3101 // Remove dependent types, they cannot be fixed yet
3102 RemoveDependentTypes (types_to_fix, rtype);
3105 foreach (TypeSpec t in types_to_fix) {
3109 int idx = IsUnfixed (t);
3110 if (idx >= 0 && !FixType (ec, idx)) {
3115 fixed_any = types_to_fix.Count > 0;
3122 public bool FixType (ResolveContext ec, int i)
3124 // It's already fixed
3125 if (fixed_types[i] != null)
3126 throw new InternalErrorException ("Type argument has been already fixed");
3131 var candidates = bounds [i];
3132 if (candidates == null)
3135 if (candidates.Count == 1) {
3136 TypeSpec t = candidates[0].Type;
3137 if (t == InternalType.NullLiteral)
3140 fixed_types [i] = t;
3145 // The set of candidate types Uj starts out as the set of
3146 // all types in the set of bounds for Xi
3148 var applicable = new bool [candidates.Count];
3149 for (int ci = 0; ci < applicable.Length; ++ci)
3150 applicable [ci] = true;
3152 for (int ci = 0; ci < applicable.Length; ++ci) {
3153 var bound = candidates [ci];
3156 switch (bound.Kind) {
3157 case BoundKind.Exact:
3158 for (; cii != applicable.Length; ++cii) {
3162 if (!applicable[cii])
3166 // For each exact bound U of Xi all types Uj which are not identical
3167 // to U are removed from the candidate set
3169 if (candidates [cii].Type != bound.Type)
3170 applicable[cii] = false;
3174 case BoundKind.Lower:
3175 for (; cii != applicable.Length; ++cii) {
3179 if (!applicable[cii])
3183 // For each lower bound U of Xi all types Uj to which there is not an implicit conversion
3184 // from U are removed from the candidate set
3186 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), candidates [cii].Type)) {
3187 applicable[cii] = false;
3193 case BoundKind.Upper:
3194 for (; cii != applicable.Length; ++cii) {
3198 if (!applicable[cii])
3202 // For each upper bound U of Xi all types Uj from which there is not an implicit conversion
3203 // to U are removed from the candidate set
3205 if (!Convert.ImplicitConversionExists (ec, candidates[cii].GetTypeExpression (), bound.Type))
3206 applicable[cii] = false;
3213 TypeSpec best_candidate = null;
3214 for (int ci = 0; ci < applicable.Length; ++ci) {
3215 if (!applicable[ci])
3218 var bound = candidates [ci];
3219 if (bound.Type == best_candidate)
3223 for (; cii < applicable.Length; ++cii) {
3227 if (!applicable[cii])
3230 if (!Convert.ImplicitConversionExists (ec, candidates[cii].GetTypeExpression (), bound.Type))
3234 if (cii != applicable.Length)
3238 // We already have the best candidate, break if it's different (non-unique)
3240 // Dynamic is never ambiguous as we prefer dynamic over other best candidate types
3242 if (best_candidate != null) {
3244 if (best_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3247 if (bound.Type.BuiltinType != BuiltinTypeSpec.Type.Dynamic && best_candidate != bound.Type)
3251 best_candidate = bound.Type;
3254 if (best_candidate == null)
3257 fixed_types[i] = best_candidate;
3261 public bool HasBounds (int pos)
3263 return bounds[pos] != null;
3267 // Uses inferred or partially infered types to inflate delegate type argument. Returns
3268 // null when type parameter has not been fixed
3270 public TypeSpec InflateGenericArgument (IModuleContext context, TypeSpec parameter)
3272 var tp = parameter as TypeParameterSpec;
3275 // Type inference works on generic arguments (MVAR) only
3277 if (!tp.IsMethodOwned)
3281 // Ensure the type parameter belongs to same container
3283 if (tp.DeclaredPosition < tp_args.Length && tp_args[tp.DeclaredPosition] == parameter)
3284 return fixed_types[tp.DeclaredPosition] ?? parameter;
3289 var gt = parameter as InflatedTypeSpec;
3291 var inflated_targs = new TypeSpec [gt.TypeArguments.Length];
3292 for (int ii = 0; ii < inflated_targs.Length; ++ii) {
3293 var inflated = InflateGenericArgument (context, gt.TypeArguments [ii]);
3294 if (inflated == null)
3297 inflated_targs[ii] = inflated;
3300 return gt.GetDefinition ().MakeGenericType (context, inflated_targs);
3303 var ac = parameter as ArrayContainer;
3305 var inflated = InflateGenericArgument (context, ac.Element);
3306 if (inflated != ac.Element)
3307 return ArrayContainer.MakeType (context.Module, inflated);
3314 // Tests whether all delegate input arguments are fixed and generic output type
3315 // requires output type inference
3317 public bool IsReturnTypeNonDependent (MethodSpec invoke, TypeSpec returnType)
3319 AParametersCollection d_parameters = invoke.Parameters;
3321 if (d_parameters.IsEmpty)
3324 while (returnType.IsArray)
3325 returnType = ((ArrayContainer) returnType).Element;
3327 if (returnType.IsGenericParameter) {
3328 if (IsFixed (returnType))
3330 } else if (TypeManager.IsGenericType (returnType)) {
3331 TypeSpec[] g_args = TypeManager.GetTypeArguments (returnType);
3333 // At least one unfixed return type has to exist
3334 if (AllTypesAreFixed (g_args))
3340 // All generic input arguments have to be fixed
3341 return AllTypesAreFixed (d_parameters.Types);
3344 bool IsFixed (TypeSpec type)
3346 return IsUnfixed (type) == -1;
3349 int IsUnfixed (TypeSpec type)
3351 if (!type.IsGenericParameter)
3354 for (int i = 0; i < tp_args.Length; ++i) {
3355 if (tp_args[i] == type) {
3356 if (fixed_types[i] != null)
3367 // 26.3.3.9 Lower-bound Inference
3369 public int LowerBoundInference (TypeSpec u, TypeSpec v)
3371 return LowerBoundInference (u, v, false);
3375 // Lower-bound (false) or Upper-bound (true) inference based on inversed argument
3377 int LowerBoundInference (TypeSpec u, TypeSpec v, bool inversed)
3379 // If V is one of the unfixed type arguments
3380 int pos = IsUnfixed (v);
3382 AddToBounds (new BoundInfo (u, inversed ? BoundKind.Upper : BoundKind.Lower), pos, false);
3386 // If U is an array type
3387 var u_ac = u as ArrayContainer;
3389 var v_ac = v as ArrayContainer;
3391 if (u_ac.Rank != v_ac.Rank)
3394 if (TypeSpec.IsValueType (u_ac.Element))
3395 return ExactInference (u_ac.Element, v_ac.Element);
3397 return LowerBoundInference (u_ac.Element, v_ac.Element, inversed);
3400 if (u_ac.Rank != 1 || !v.IsArrayGenericInterface)
3403 var v_i = TypeManager.GetTypeArguments (v) [0];
3404 if (TypeSpec.IsValueType (u_ac.Element))
3405 return ExactInference (u_ac.Element, v_i);
3407 return LowerBoundInference (u_ac.Element, v_i);
3410 if (v.IsGenericOrParentIsGeneric) {
3412 // if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
3413 // such that U is identical to, inherits from (directly or indirectly),
3414 // or implements (directly or indirectly) C<U1..Uk>
3416 var u_candidates = new List<TypeSpec> ();
3417 var open_v = v.MemberDefinition;
3419 for (TypeSpec t = u; t != null; t = t.BaseType) {
3420 if (open_v == t.MemberDefinition)
3421 u_candidates.Add (t);
3424 // Using this trick for dynamic type inference, the spec says the type arguments are "unknown" but
3425 // that would complicate the process a lot, instead I treat them as dynamic
3427 if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3428 u_candidates.Add (t);
3431 if (u.Interfaces != null) {
3432 foreach (var iface in u.Interfaces) {
3433 if (open_v == iface.MemberDefinition)
3434 u_candidates.Add (iface);
3438 TypeSpec[] unique_candidate_targs = null;
3439 var ga_v = TypeSpec.GetAllTypeArguments (v);
3440 foreach (TypeSpec u_candidate in u_candidates) {
3442 // The unique set of types U1..Uk means that if we have an interface I<T>,
3443 // class U : I<int>, I<long> then no type inference is made when inferring
3444 // type I<T> by applying type U because T could be int or long
3446 if (unique_candidate_targs != null) {
3447 TypeSpec[] second_unique_candidate_targs = TypeSpec.GetAllTypeArguments (u_candidate);
3448 if (TypeSpecComparer.Equals (unique_candidate_targs, second_unique_candidate_targs)) {
3449 unique_candidate_targs = second_unique_candidate_targs;
3454 // This should always cause type inference failure
3461 // A candidate is dynamic type expression, to simplify things use dynamic
3462 // for all type parameter of this type. For methods like this one
3464 // void M<T, U> (IList<T>, IList<U[]>)
3466 // dynamic becomes both T and U when the arguments are of dynamic type
3468 if (u_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
3469 unique_candidate_targs = new TypeSpec[ga_v.Length];
3470 for (int i = 0; i < unique_candidate_targs.Length; ++i)
3471 unique_candidate_targs[i] = u_candidate;
3473 unique_candidate_targs = TypeSpec.GetAllTypeArguments (u_candidate);
3477 if (unique_candidate_targs != null) {
3480 TypeParameterSpec[] tps = null;
3482 for (int i = 0; i < unique_candidate_targs.Length; ++i) {
3484 while (v.Arity == 0)
3485 v = v.DeclaringType;
3487 tps = v.MemberDefinition.TypeParameters;
3488 tp_index = tps.Length - 1;
3491 Variance variance = tps [tp_index--].Variance;
3493 TypeSpec u_i = unique_candidate_targs [i];
3494 if (variance == Variance.None || TypeSpec.IsValueType (u_i)) {
3495 if (ExactInference (u_i, ga_v [i]) == 0)
3498 bool upper_bound = (variance == Variance.Contravariant && !inversed) ||
3499 (variance == Variance.Covariant && inversed);
3501 if (LowerBoundInference (u_i, ga_v [i], upper_bound) == 0)
3514 // 26.3.3.6 Output Type Inference
3516 public int OutputTypeInference (ResolveContext ec, Expression e, TypeSpec t)
3518 // If e is a lambda or anonymous method with inferred return type
3519 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
3521 TypeSpec rt = ame.InferReturnType (ec, this, t);
3522 var invoke = Delegate.GetInvokeMethod (t);
3525 AParametersCollection pd = invoke.Parameters;
3526 return ame.Parameters.Count == pd.Count ? 1 : 0;
3529 TypeSpec rtype = invoke.ReturnType;
3530 return LowerBoundInference (rt, rtype) + 1;
3534 // if E is a method group and T is a delegate type or expression tree type
3535 // return type Tb with parameter types T1..Tk and return type Tb, and overload
3536 // resolution of E with the types T1..Tk yields a single method with return type U,
3537 // then a lower-bound inference is made from U for Tb.
3539 if (e is MethodGroupExpr) {
3540 if (!t.IsDelegate) {
3541 if (!t.IsExpressionTreeType)
3544 t = TypeManager.GetTypeArguments (t)[0];
3547 var invoke = Delegate.GetInvokeMethod (t);
3548 TypeSpec rtype = invoke.ReturnType;
3550 if (!IsReturnTypeNonDependent (invoke, rtype))
3553 // LAMESPEC: Standard does not specify that all methodgroup arguments
3554 // has to be fixed but it does not specify how to do recursive type inference
3555 // either. We choose the simple option and infer return type only
3556 // if all delegate generic arguments are fixed.
3557 TypeSpec[] param_types = new TypeSpec [invoke.Parameters.Count];
3558 for (int i = 0; i < param_types.Length; ++i) {
3559 var inflated = InflateGenericArgument (ec, invoke.Parameters.Types[i]);
3560 if (inflated == null)
3563 param_types[i] = inflated;
3566 MethodGroupExpr mg = (MethodGroupExpr) e;
3567 Arguments args = DelegateCreation.CreateDelegateMethodArguments (ec, invoke.Parameters, param_types, e.Location);
3568 mg = mg.OverloadResolve (ec, ref args, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
3572 return LowerBoundInference (mg.BestCandidateReturnType, rtype) + 1;
3576 // if e is an expression with type U, then
3577 // a lower-bound inference is made from U for T
3579 return LowerBoundInference (e.Type, t) * 2;
3582 void RemoveDependentTypes (List<TypeSpec> types, TypeSpec returnType)
3584 int idx = IsUnfixed (returnType);
3590 if (TypeManager.IsGenericType (returnType)) {
3591 foreach (TypeSpec t in TypeManager.GetTypeArguments (returnType)) {
3592 RemoveDependentTypes (types, t);
3597 public bool UnfixedVariableExists {
3599 foreach (TypeSpec ut in fixed_types) {