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 type.GetSignatureForError ());
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 readonly TypeParameterSpec spec;
363 public TypeParameter (int index, MemberName name, Constraints constraints, Attributes attrs, Variance variance)
364 : base (null, name, attrs)
366 this.constraints = constraints;
367 this.spec = new TypeParameterSpec (null, index, this, SpecialConstraint.None, variance, null);
373 public TypeParameter (MemberName name, Attributes attrs, Variance variance)
374 : base (null, name, attrs)
376 this.spec = new TypeParameterSpec (null, -1, this, SpecialConstraint.None, variance, null);
379 public TypeParameter (TypeParameterSpec spec, TypeSpec parentSpec, MemberName name, Attributes attrs)
380 : base (null, name, attrs)
382 this.spec = new TypeParameterSpec (parentSpec, spec.DeclaredPosition, spec.MemberDefinition, spec.SpecialConstraint, spec.Variance, null) {
383 BaseType = spec.BaseType,
384 InterfacesDefined = spec.InterfacesDefined,
385 TypeArguments = spec.TypeArguments
391 public override AttributeTargets AttributeTargets {
393 return AttributeTargets.GenericParameter;
397 public Constraints Constraints {
406 public IAssemblyDefinition DeclaringAssembly {
408 return Module.DeclaringAssembly;
412 public override string DocCommentHeader {
414 throw new InvalidOperationException (
415 "Unexpected attempt to get doc comment from " + this.GetType ());
419 bool ITypeDefinition.IsComImport {
425 bool ITypeDefinition.IsPartial {
431 public bool IsMethodTypeParameter {
433 return spec.IsMethodOwned;
437 bool ITypeDefinition.IsTypeForwarder {
445 return MemberName.Name;
449 public string Namespace {
455 public TypeParameterSpec Type {
461 public int TypeParametersCount {
467 public TypeParameterSpec[] TypeParameters {
473 public override string[] ValidAttributeTargets {
475 return attribute_target;
479 public Variance Variance {
481 return spec.Variance;
488 // This is called for each part of a partial generic type definition.
490 // If partial type parameters constraints are not null and we don't
491 // already have constraints they become our constraints. If we already
492 // have constraints, we must check that they're the same.
494 public bool AddPartialConstraints (TypeDefinition part, TypeParameter tp)
497 throw new InvalidOperationException ();
499 var new_constraints = tp.constraints;
500 if (new_constraints == null)
503 // TODO: could create spec only
504 //tp.Define (null, -1, part.Definition);
505 tp.spec.DeclaringType = part.Definition;
506 if (!tp.ResolveConstraints (part))
509 if (constraints != null)
510 return spec.HasSameConstraintsDefinition (tp.Type);
512 // Copy constraint from resolved part to partial container
513 spec.SpecialConstraint = tp.spec.SpecialConstraint;
514 spec.Interfaces = tp.spec.Interfaces;
515 spec.TypeArguments = tp.spec.TypeArguments;
516 spec.BaseType = tp.spec.BaseType;
521 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
523 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
526 public void CheckGenericConstraints (bool obsoleteCheck)
528 if (constraints != null)
529 constraints.CheckGenericConstraints (this, obsoleteCheck);
532 public TypeParameter CreateHoistedCopy (TypeSpec declaringSpec)
534 return new TypeParameter (spec, declaringSpec, MemberName, null);
537 public override bool Define ()
543 // This is the first method which is called during the resolving
544 // process; we're called immediately after creating the type parameters
545 // with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
548 public void Define (GenericTypeParameterBuilder type, TypeSpec declaringType, TypeContainer parent)
551 throw new InternalErrorException ();
553 // Needed to get compiler reference
554 this.Parent = parent;
556 spec.DeclaringType = declaringType;
557 spec.SetMetaInfo (type);
560 public void EmitConstraints (GenericTypeParameterBuilder builder)
562 var attr = GenericParameterAttributes.None;
563 if (spec.Variance == Variance.Contravariant)
564 attr |= GenericParameterAttributes.Contravariant;
565 else if (spec.Variance == Variance.Covariant)
566 attr |= GenericParameterAttributes.Covariant;
568 if (spec.HasSpecialClass)
569 attr |= GenericParameterAttributes.ReferenceTypeConstraint;
570 else if (spec.HasSpecialStruct)
571 attr |= GenericParameterAttributes.NotNullableValueTypeConstraint | GenericParameterAttributes.DefaultConstructorConstraint;
573 if (spec.HasSpecialConstructor)
574 attr |= GenericParameterAttributes.DefaultConstructorConstraint;
576 if (spec.BaseType.BuiltinType != BuiltinTypeSpec.Type.Object)
577 builder.SetBaseTypeConstraint (spec.BaseType.GetMetaInfo ());
579 if (spec.InterfacesDefined != null)
580 builder.SetInterfaceConstraints (spec.InterfacesDefined.Select (l => l.GetMetaInfo ()).ToArray ());
582 if (spec.TypeArguments != null)
583 builder.SetInterfaceConstraints (spec.TypeArguments.Select (l => l.GetMetaInfo ()).ToArray ());
585 builder.SetGenericParameterAttributes (attr);
588 public override void Emit ()
590 EmitConstraints (builder);
592 if (OptAttributes != null)
593 OptAttributes.Emit ();
598 public void ErrorInvalidVariance (IMemberContext mc, Variance expected)
600 Report.SymbolRelatedToPreviousError (mc.CurrentMemberDefinition);
601 string input_variance = Variance == Variance.Contravariant ? "contravariant" : "covariant";
602 string gtype_variance;
604 case Variance.Contravariant: gtype_variance = "contravariantly"; break;
605 case Variance.Covariant: gtype_variance = "covariantly"; break;
606 default: gtype_variance = "invariantly"; break;
609 Delegate d = mc as Delegate;
610 string parameters = d != null ? d.Parameters.GetSignatureForError () : "";
612 Report.Error (1961, Location,
613 "The {2} type parameter `{0}' must be {3} valid on `{1}{4}'",
614 GetSignatureForError (), mc.GetSignatureForError (), input_variance, gtype_variance, parameters);
617 public TypeSpec GetAttributeCoClass ()
622 public string GetAttributeDefaultMember ()
624 throw new NotSupportedException ();
627 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
629 throw new NotSupportedException ();
632 public override string GetSignatureForDocumentation ()
634 throw new NotImplementedException ();
637 public override string GetSignatureForError ()
639 return MemberName.Name;
642 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
644 return spec.MemberDefinition.DeclaringAssembly == assembly;
647 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
649 throw new NotSupportedException ("Not supported for compiled definition");
653 // Resolves all type parameter constraints
655 public bool ResolveConstraints (IMemberContext context)
657 if (constraints != null)
658 return constraints.Resolve (context, this);
660 if (spec.BaseType == null)
661 spec.BaseType = context.Module.Compiler.BuiltinTypes.Object;
666 public override bool IsClsComplianceRequired ()
671 public new void VerifyClsCompliance ()
673 if (constraints != null)
674 constraints.VerifyClsCompliance (Report);
677 public void WarningParentNameConflict (TypeParameter conflict)
679 conflict.Report.SymbolRelatedToPreviousError (conflict.Location, null);
680 conflict.Report.Warning (693, 3, Location,
681 "Type parameter `{0}' has the same name as the type parameter from outer type `{1}'",
682 GetSignatureForError (), conflict.CurrentType.GetSignatureForError ());
686 [System.Diagnostics.DebuggerDisplay ("{DisplayDebugInfo()}")]
687 public class TypeParameterSpec : TypeSpec
689 public static readonly new TypeParameterSpec[] EmptyTypes = new TypeParameterSpec[0];
692 SpecialConstraint spec;
695 TypeSpec[] ifaces_defined;
698 // Creates type owned type parameter
700 public TypeParameterSpec (TypeSpec declaringType, int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
701 : base (MemberKind.TypeParameter, declaringType, definition, info, Modifiers.PUBLIC)
703 this.variance = variance;
705 state &= ~StateFlags.Obsolete_Undetected;
710 // Creates method owned type parameter
712 public TypeParameterSpec (int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
713 : this (null, index, definition, spec, variance, info)
719 public int DeclaredPosition {
728 public bool HasSpecialConstructor {
730 return (spec & SpecialConstraint.Constructor) != 0;
734 public bool HasSpecialClass {
736 return (spec & SpecialConstraint.Class) != 0;
740 public bool HasSpecialStruct {
742 return (spec & SpecialConstraint.Struct) != 0;
746 public bool HasAnyTypeConstraint {
748 return (spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0 || ifaces != null || targs != null || HasTypeConstraint;
752 public bool HasTypeConstraint {
754 var bt = BaseType.BuiltinType;
755 return bt != BuiltinTypeSpec.Type.Object && bt != BuiltinTypeSpec.Type.ValueType;
759 public override IList<TypeSpec> Interfaces {
761 if ((state & StateFlags.InterfacesExpanded) == 0) {
762 if (ifaces != null) {
763 if (ifaces_defined == null)
764 ifaces_defined = ifaces.ToArray ();
766 for (int i = 0; i < ifaces_defined.Length; ++i ) {
767 var iface_type = ifaces_defined[i];
768 var td = iface_type.MemberDefinition as TypeDefinition;
770 td.DoExpandBaseInterfaces ();
772 if (iface_type.Interfaces != null) {
773 for (int ii = 0; ii < iface_type.Interfaces.Count; ++ii) {
774 var ii_iface_type = iface_type.Interfaces [ii];
775 AddInterface (ii_iface_type);
779 } else if (ifaces_defined == null) {
780 ifaces_defined = ifaces == null ? TypeSpec.EmptyTypes : ifaces.ToArray ();
784 // Include all base type interfaces too, see ImportTypeBase for details
786 if (BaseType != null) {
787 var td = BaseType.MemberDefinition as TypeDefinition;
789 td.DoExpandBaseInterfaces ();
791 if (BaseType.Interfaces != null) {
792 foreach (var iface in BaseType.Interfaces) {
793 AddInterface (iface);
798 state |= StateFlags.InterfacesExpanded;
806 // Unexpanded interfaces list
808 public TypeSpec[] InterfacesDefined {
810 if (ifaces_defined == null) {
814 ifaces_defined = ifaces.ToArray ();
817 return ifaces_defined.Length == 0 ? null : ifaces_defined;
820 ifaces_defined = value;
821 if (value != null && value.Length != 0)
822 ifaces = new List<TypeSpec> (value);
826 public bool IsConstrained {
828 return spec != SpecialConstraint.None || ifaces != null || targs != null || HasTypeConstraint;
833 // Returns whether the type parameter is known to be a reference type
835 public new bool IsReferenceType {
837 if ((spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0)
838 return (spec & SpecialConstraint.Class) != 0;
841 // Full check is needed (see IsValueType for details)
843 if (HasTypeConstraint && TypeSpec.IsReferenceType (BaseType))
847 foreach (var ta in targs) {
849 // Secondary special constraints are ignored (I am not sure why)
851 var tp = ta as TypeParameterSpec;
852 if (tp != null && (tp.spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0)
855 if (TypeSpec.IsReferenceType (ta))
865 // Returns whether the type parameter is known to be a value type
867 public new bool IsValueType {
870 // Even if structs/enums cannot be used directly as constraints
871 // they can apear as constraint type when inheriting base constraint
872 // which has dependant type parameter constraint which has been
873 // inflated using value type
875 // class A : B<int> { override void Foo<U> () {} }
876 // class B<T> { virtual void Foo<U> () where U : T {} }
878 if (HasSpecialStruct)
882 foreach (var ta in targs) {
883 if (TypeSpec.IsValueType (ta))
892 public override string Name {
894 return definition.Name;
898 public bool IsMethodOwned {
900 return DeclaringType == null;
904 public SpecialConstraint SpecialConstraint {
914 // Types used to inflate the generic type
916 public new TypeSpec[] TypeArguments {
925 public Variance Variance {
933 public string DisplayDebugInfo ()
935 var s = GetSignatureForError ();
936 return IsMethodOwned ? s + "!!" : s + "!";
940 // Finds effective base class. The effective base class is always a class-type
942 public TypeSpec GetEffectiveBase ()
944 if (HasSpecialStruct)
948 // If T has a class-type constraint C but no type-parameter constraints, its effective base class is C
950 if (BaseType != null && targs == null) {
952 // 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.
954 // LAMESPEC: Is System.ValueType always the most specific base type in this case?
956 // Note: This can never happen in an explicitly given constraint, but may occur when the constraints of a generic method
957 // are implicitly inherited by an overriding method declaration or an explicit implementation of an interface method.
959 return BaseType.IsStruct ? BaseType.BaseType : BaseType;
963 if (HasTypeConstraint) {
964 Array.Resize (ref types, types.Length + 1);
966 for (int i = 0; i < types.Length - 1; ++i) {
967 types[i] = types[i].BaseType;
970 types[types.Length - 1] = BaseType;
972 types = types.Select (l => l.BaseType).ToArray ();
976 return Convert.FindMostEncompassedType (types);
981 public override string GetSignatureForDocumentation ()
983 var prefix = IsMethodOwned ? "``" : "`";
984 return prefix + DeclaredPosition;
987 public override string GetSignatureForError ()
993 // Constraints have to match by definition but not position, used by
994 // partial classes or methods
996 public bool HasSameConstraintsDefinition (TypeParameterSpec other)
998 if (spec != other.spec)
1001 if (BaseType != other.BaseType)
1004 if (!TypeSpecComparer.Override.IsSame (InterfacesDefined, other.InterfacesDefined))
1007 if (!TypeSpecComparer.Override.IsSame (targs, other.targs))
1014 // Constraints have to match by using same set of types, used by
1015 // implicit interface implementation
1017 public bool HasSameConstraintsImplementation (TypeParameterSpec other)
1019 if (spec != other.spec)
1023 // It can be same base type or inflated type parameter
1025 // interface I<T> { void Foo<U> where U : T; }
1026 // class A : I<int> { void Foo<X> where X : int {} }
1029 if (!TypeSpecComparer.Override.IsEqual (BaseType, other.BaseType)) {
1030 if (other.targs == null)
1034 foreach (var otarg in other.targs) {
1035 if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
1045 // Check interfaces implementation -> definition
1046 if (InterfacesDefined != null) {
1048 // Iterate over inflated interfaces
1050 foreach (var iface in Interfaces) {
1052 if (other.InterfacesDefined != null) {
1053 foreach (var oiface in other.Interfaces) {
1054 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
1064 if (other.targs != null) {
1065 foreach (var otarg in other.targs) {
1066 if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
1078 // Check interfaces implementation <- definition
1079 if (other.InterfacesDefined != null) {
1080 if (InterfacesDefined == null)
1084 // Iterate over inflated interfaces
1086 foreach (var oiface in other.Interfaces) {
1088 foreach (var iface in Interfaces) {
1089 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
1100 // Check type parameters implementation -> definition
1101 if (targs != null) {
1102 if (other.targs == null)
1105 foreach (var targ in targs) {
1107 foreach (var otarg in other.targs) {
1108 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
1119 // Check type parameters implementation <- definition
1120 if (other.targs != null) {
1121 foreach (var otarg in other.targs) {
1122 // Ignore inflated type arguments, were checked above
1123 if (!otarg.IsGenericParameter)
1130 foreach (var targ in targs) {
1131 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
1145 public static TypeParameterSpec[] InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec[] tparams)
1147 return InflateConstraints (tparams, l => l, inflator);
1150 public static TypeParameterSpec[] InflateConstraints<T> (TypeParameterSpec[] tparams, Func<T, TypeParameterInflator> inflatorFactory, T arg)
1152 TypeParameterSpec[] constraints = null;
1153 TypeParameterInflator? inflator = null;
1155 for (int i = 0; i < tparams.Length; ++i) {
1156 var tp = tparams[i];
1157 if (tp.HasTypeConstraint || tp.InterfacesDefined != null || tp.TypeArguments != null) {
1158 if (constraints == null) {
1159 constraints = new TypeParameterSpec[tparams.Length];
1160 Array.Copy (tparams, constraints, constraints.Length);
1164 // Using a factory to avoid possibly expensive inflator build up
1166 if (inflator == null)
1167 inflator = inflatorFactory (arg);
1169 constraints[i] = (TypeParameterSpec) constraints[i].InflateMember (inflator.Value);
1173 if (constraints == null)
1174 constraints = tparams;
1179 public void InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec tps)
1181 tps.BaseType = inflator.Inflate (BaseType);
1183 var defined = InterfacesDefined;
1184 if (defined != null) {
1185 tps.ifaces_defined = new TypeSpec[defined.Length];
1186 for (int i = 0; i < defined.Length; ++i)
1187 tps.ifaces_defined [i] = inflator.Inflate (defined[i]);
1190 var ifaces = Interfaces;
1191 if (ifaces != null) {
1192 tps.ifaces = new List<TypeSpec> (ifaces.Count);
1193 for (int i = 0; i < ifaces.Count; ++i)
1194 tps.ifaces.Add (inflator.Inflate (ifaces[i]));
1197 if (targs != null) {
1198 tps.targs = new TypeSpec[targs.Length];
1199 for (int i = 0; i < targs.Length; ++i)
1200 tps.targs[i] = inflator.Inflate (targs[i]);
1204 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1206 var tps = (TypeParameterSpec) MemberwiseClone ();
1207 InflateConstraints (inflator, tps);
1212 // Populates type parameter members using type parameter constraints
1213 // The trick here is to be called late enough but not too late to
1214 // populate member cache with all members from other types
1216 protected override void InitializeMemberCache (bool onlyTypes)
1218 cache = new MemberCache ();
1221 // For a type parameter the membercache is the union of the sets of members of the types
1222 // specified as a primary constraint or secondary constraint
1224 if (BaseType.BuiltinType != BuiltinTypeSpec.Type.Object && BaseType.BuiltinType != BuiltinTypeSpec.Type.ValueType)
1225 cache.AddBaseType (BaseType);
1227 if (InterfacesDefined != null) {
1228 foreach (var iface_type in InterfacesDefined) {
1229 cache.AddInterface (iface_type);
1233 if (targs != null) {
1234 foreach (var ta in targs) {
1235 var b_type = ta.BaseType;
1236 if (b_type.BuiltinType != BuiltinTypeSpec.Type.Object && b_type.BuiltinType != BuiltinTypeSpec.Type.ValueType)
1237 cache.AddBaseType (b_type);
1239 var tps = ta as TypeParameterSpec;
1240 var ifaces = tps != null ? tps.InterfacesDefined : ta.Interfaces;
1242 if (ifaces != null) {
1243 foreach (var iface_type in ifaces) {
1244 cache.AddInterface (iface_type);
1251 public bool IsConvertibleToInterface (TypeSpec iface)
1253 if (Interfaces != null) {
1254 foreach (var t in Interfaces) {
1260 if (TypeArguments != null) {
1261 foreach (var t in TypeArguments) {
1262 if (((TypeParameterSpec) t).IsConvertibleToInterface (iface))
1270 public static bool HasAnyTypeParameterTypeConstrained (IGenericMethodDefinition md)
1272 var tps = md.TypeParameters;
1273 for (int i = 0; i < md.TypeParametersCount; ++i) {
1274 if (tps[i].HasAnyTypeConstraint) {
1282 public static bool HasAnyTypeParameterConstrained (IGenericMethodDefinition md)
1284 var tps = md.TypeParameters;
1285 for (int i = 0; i < md.TypeParametersCount; ++i) {
1286 if (tps[i].IsConstrained) {
1294 public bool HasDependencyOn (TypeSpec type)
1296 if (TypeArguments != null) {
1297 foreach (var targ in TypeArguments) {
1298 if (TypeSpecComparer.Override.IsEqual (targ, type))
1301 var tps = targ as TypeParameterSpec;
1302 if (tps != null && tps.HasDependencyOn (type))
1310 public override TypeSpec Mutate (TypeParameterMutator mutator)
1312 return mutator.Mutate (this);
1316 public struct TypeParameterInflator
1318 readonly TypeSpec type;
1319 readonly TypeParameterSpec[] tparams;
1320 readonly TypeSpec[] targs;
1321 readonly IModuleContext context;
1323 public TypeParameterInflator (TypeParameterInflator nested, TypeSpec type)
1324 : this (nested.context, type, nested.tparams, nested.targs)
1328 public TypeParameterInflator (IModuleContext context, TypeSpec type, TypeParameterSpec[] tparams, TypeSpec[] targs)
1330 if (tparams.Length != targs.Length)
1331 throw new ArgumentException ("Invalid arguments");
1333 this.context = context;
1334 this.tparams = tparams;
1341 public IModuleContext Context {
1347 public TypeSpec TypeInstance {
1354 // Type parameters to inflate
1356 public TypeParameterSpec[] TypeParameters {
1364 public TypeSpec Inflate (TypeSpec type)
1366 var tp = type as TypeParameterSpec;
1368 return Inflate (tp);
1370 var ac = type as ArrayContainer;
1372 var et = Inflate (ac.Element);
1373 if (et != ac.Element)
1374 return ArrayContainer.MakeType (context.Module, et, ac.Rank);
1380 // When inflating a nested type, inflate its parent first
1381 // in case it's using same type parameters (was inflated within the type)
1385 if (type.IsNested) {
1386 var parent = Inflate (type.DeclaringType);
1389 // Keep the inflated type arguments
1391 targs = type.TypeArguments;
1394 // When inflating imported nested type used inside same declaring type, we get TypeSpec
1395 // because the import cache helps us to catch it. However, that means we have to look at
1396 // type definition to get type argument (they are in fact type parameter in this case)
1398 if (targs.Length == 0 && type.Arity > 0)
1399 targs = type.MemberDefinition.TypeParameters;
1402 // Parent was inflated, find the same type on inflated type
1403 // to use same cache for nested types on same generic parent
1405 type = MemberCache.FindNestedType (parent, type.Name, type.Arity);
1408 // Handle the tricky case where parent shares local type arguments
1409 // which means inflating inflated type
1412 // public static Nested<T> Foo () { return null; }
1414 // public class Nested<U> {}
1417 // return type of Test<string>.Foo() has to be Test<string>.Nested<string>
1419 if (targs.Length > 0) {
1420 var inflated_targs = new TypeSpec[targs.Length];
1421 for (; i < targs.Length; ++i)
1422 inflated_targs[i] = Inflate (targs[i]);
1424 type = type.MakeGenericType (context, inflated_targs);
1430 // Nothing to do for non-generic type
1431 if (type.Arity == 0)
1434 targs = new TypeSpec[type.Arity];
1437 // Inflating using outside type arguments, var v = new Foo<int> (), class Foo<T> {}
1439 if (type is InflatedTypeSpec) {
1440 for (; i < targs.Length; ++i)
1441 targs[i] = Inflate (type.TypeArguments[i]);
1443 type = type.GetDefinition ();
1446 // Inflating parent using inside type arguments, class Foo<T> { ITest<T> foo; }
1448 var args = type.MemberDefinition.TypeParameters;
1449 foreach (var ds_tp in args)
1450 targs[i++] = Inflate (ds_tp);
1453 return type.MakeGenericType (context, targs);
1456 public TypeSpec Inflate (TypeParameterSpec tp)
1458 for (int i = 0; i < tparams.Length; ++i)
1459 if (tparams [i] == tp)
1462 // This can happen when inflating nested types
1463 // without type arguments specified
1469 // Before emitting any code we have to change all MVAR references to VAR
1470 // when the method is of generic type and has hoisted variables
1472 public class TypeParameterMutator
1474 readonly TypeParameters mvar;
1475 readonly TypeParameters var;
1476 readonly TypeParameterSpec[] src;
1477 Dictionary<TypeSpec, TypeSpec> mutated_typespec;
1479 public TypeParameterMutator (TypeParameters mvar, TypeParameters var)
1481 if (mvar.Count != var.Count)
1482 throw new ArgumentException ();
1488 public TypeParameterMutator (TypeParameterSpec[] srcVar, TypeParameters destVar)
1490 if (srcVar.Length != destVar.Count)
1491 throw new ArgumentException ();
1499 public TypeParameters MethodTypeParameters {
1507 public static TypeSpec GetMemberDeclaringType (TypeSpec type)
1509 if (type is InflatedTypeSpec) {
1510 if (type.DeclaringType == null)
1511 return type.GetDefinition ();
1513 var parent = GetMemberDeclaringType (type.DeclaringType);
1514 type = MemberCache.GetMember<TypeSpec> (parent, type);
1520 public TypeSpec Mutate (TypeSpec ts)
1523 if (mutated_typespec != null && mutated_typespec.TryGetValue (ts, out value))
1526 value = ts.Mutate (this);
1527 if (mutated_typespec == null)
1528 mutated_typespec = new Dictionary<TypeSpec, TypeSpec> ();
1530 mutated_typespec.Add (ts, value);
1534 public TypeParameterSpec Mutate (TypeParameterSpec tp)
1537 for (int i = 0; i < mvar.Count; ++i) {
1538 if (mvar[i].Type == tp)
1542 for (int i = 0; i < src.Length; ++i) {
1551 public TypeSpec[] Mutate (TypeSpec[] targs)
1553 TypeSpec[] mutated = new TypeSpec[targs.Length];
1554 bool changed = false;
1555 for (int i = 0; i < targs.Length; ++i) {
1556 mutated[i] = Mutate (targs[i]);
1557 changed |= targs[i] != mutated[i];
1560 return changed ? mutated : targs;
1565 /// A TypeExpr which already resolved to a type parameter.
1567 public class TypeParameterExpr : TypeExpression
1569 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1570 : base (type_parameter.Type, loc)
1572 this.eclass = ExprClass.TypeParameter;
1576 public class InflatedTypeSpec : TypeSpec
1579 TypeParameterSpec[] constraints;
1580 readonly TypeSpec open_type;
1581 readonly IModuleContext context;
1583 public InflatedTypeSpec (IModuleContext context, TypeSpec openType, TypeSpec declaringType, TypeSpec[] targs)
1584 : base (openType.Kind, declaringType, openType.MemberDefinition, null, openType.Modifiers)
1587 throw new ArgumentNullException ("targs");
1589 this.state &= ~SharedStateFlags;
1590 this.state |= (openType.state & SharedStateFlags);
1592 this.context = context;
1593 this.open_type = openType;
1596 foreach (var arg in targs) {
1597 if (arg.HasDynamicElement || arg.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1598 state |= StateFlags.HasDynamicElement;
1603 if (open_type.Kind == MemberKind.MissingType)
1604 MemberCache = MemberCache.Empty;
1606 if ((open_type.Modifiers & Modifiers.COMPILER_GENERATED) != 0)
1607 state |= StateFlags.ConstraintsChecked;
1612 public override TypeSpec BaseType {
1614 if (cache == null || (state & StateFlags.PendingBaseTypeInflate) != 0)
1615 InitializeMemberCache (true);
1617 return base.BaseType;
1622 // Inflated type parameters with constraints array, mapping with type arguments is based on index
1624 public TypeParameterSpec[] Constraints {
1626 if (constraints == null) {
1627 constraints = TypeParameterSpec.InflateConstraints (MemberDefinition.TypeParameters, l => l.CreateLocalInflator (context), this);
1635 // Used to cache expensive constraints validation on constructed types
1637 public bool HasConstraintsChecked {
1639 return (state & StateFlags.ConstraintsChecked) != 0;
1642 state = value ? state | StateFlags.ConstraintsChecked : state & ~StateFlags.ConstraintsChecked;
1646 public override IList<TypeSpec> Interfaces {
1649 InitializeMemberCache (true);
1651 return base.Interfaces;
1655 public override bool IsExpressionTreeType {
1657 return (open_type.state & StateFlags.InflatedExpressionType) != 0;
1661 public override bool IsGenericIterateInterface {
1663 return (open_type.state & StateFlags.GenericIterateInterface) != 0;
1667 public override bool IsGenericTask {
1669 return (open_type.state & StateFlags.GenericTask) != 0;
1673 public override bool IsNullableType {
1675 return (open_type.state & StateFlags.InflatedNullableType) != 0;
1680 // Types used to inflate the generic type
1682 public override TypeSpec[] TypeArguments {
1690 public override bool AddInterface (TypeSpec iface)
1692 var inflator = CreateLocalInflator (context);
1693 iface = inflator.Inflate (iface);
1697 return base.AddInterface (iface);
1700 public static bool ContainsTypeParameter (TypeSpec type)
1702 if (type.Kind == MemberKind.TypeParameter)
1705 var element_container = type as ElementTypeSpec;
1706 if (element_container != null)
1707 return ContainsTypeParameter (element_container.Element);
1709 foreach (var t in type.TypeArguments) {
1710 if (ContainsTypeParameter (t)) {
1718 TypeParameterInflator CreateLocalInflator (IModuleContext context)
1720 TypeParameterSpec[] tparams_full;
1721 TypeSpec[] targs_full = targs;
1724 // Special case is needed when we are inflating an open type (nested type definition)
1725 // on inflated parent. Consider following case
1727 // Foo<T>.Bar<U> => Foo<string>.Bar<U>
1729 // Any later inflation of Foo<string>.Bar<U> has to also inflate T if used inside Bar<U>
1731 List<TypeSpec> merged_targs = null;
1732 List<TypeParameterSpec> merged_tparams = null;
1734 var type = DeclaringType;
1737 if (type.TypeArguments.Length > 0) {
1738 if (merged_targs == null) {
1739 merged_targs = new List<TypeSpec> ();
1740 merged_tparams = new List<TypeParameterSpec> ();
1741 if (targs.Length > 0) {
1742 merged_targs.AddRange (targs);
1743 merged_tparams.AddRange (open_type.MemberDefinition.TypeParameters);
1746 merged_tparams.AddRange (type.MemberDefinition.TypeParameters);
1747 merged_targs.AddRange (type.TypeArguments);
1749 type = type.DeclaringType;
1750 } while (type != null);
1752 if (merged_targs != null) {
1753 // Type arguments are not in the right order but it should not matter in this case
1754 targs_full = merged_targs.ToArray ();
1755 tparams_full = merged_tparams.ToArray ();
1756 } else if (targs.Length == 0) {
1757 tparams_full = TypeParameterSpec.EmptyTypes;
1759 tparams_full = open_type.MemberDefinition.TypeParameters;
1761 } else if (targs.Length == 0) {
1762 tparams_full = TypeParameterSpec.EmptyTypes;
1764 tparams_full = open_type.MemberDefinition.TypeParameters;
1767 return new TypeParameterInflator (context, this, tparams_full, targs_full);
1770 MetaType CreateMetaInfo (TypeParameterMutator mutator)
1773 // Converts nested type arguments into right order
1774 // Foo<string, bool>.Bar<int> => string, bool, int
1776 var all = new List<MetaType> ();
1777 TypeSpec type = this;
1778 TypeSpec definition = type;
1780 if (type.GetDefinition().IsGeneric) {
1782 type.TypeArguments != TypeSpec.EmptyTypes ?
1783 type.TypeArguments.Select (l => l.GetMetaInfo ()) :
1784 type.MemberDefinition.TypeParameters.Select (l => l.GetMetaInfo ()));
1787 definition = definition.GetDefinition ();
1788 type = type.DeclaringType;
1789 } while (type != null);
1791 return definition.GetMetaInfo ().MakeGenericType (all.ToArray ());
1794 public override ObsoleteAttribute GetAttributeObsolete ()
1796 return open_type.GetAttributeObsolete ();
1799 protected override bool IsNotCLSCompliant (out bool attrValue)
1801 if (base.IsNotCLSCompliant (out attrValue))
1804 foreach (var ta in TypeArguments) {
1805 if (ta.MemberDefinition.CLSAttributeValue == false)
1812 public override TypeSpec GetDefinition ()
1817 public override MetaType GetMetaInfo ()
1820 info = CreateMetaInfo (null);
1825 public override string GetSignatureForError ()
1828 return targs[0].GetSignatureForError () + "?";
1830 return base.GetSignatureForError ();
1833 protected override string GetTypeNameSignature ()
1835 if (targs.Length == 0 || MemberDefinition is AnonymousTypeClass)
1838 return "<" + TypeManager.CSharpName (targs) + ">";
1841 public bool HasDynamicArgument ()
1843 for (int i = 0; i < targs.Length; ++i) {
1844 var item = targs[i];
1846 if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1849 if (item is InflatedTypeSpec) {
1850 if (((InflatedTypeSpec) item).HasDynamicArgument ())
1857 while (item.IsArray) {
1858 item = ((ArrayContainer) item).Element;
1861 if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1869 protected override void InitializeMemberCache (bool onlyTypes)
1871 if (cache == null) {
1872 var open_cache = onlyTypes ? open_type.MemberCacheTypes : open_type.MemberCache;
1874 // Surprisingly, calling MemberCache on open type could meantime create cache on this type
1875 // for imported type parameter constraints referencing nested type of this declaration
1877 cache = new MemberCache (open_cache);
1880 var inflator = CreateLocalInflator (context);
1883 // Two stage inflate due to possible nested types recursive
1893 // When resolving type of `b' members of `B' cannot be
1894 // inflated because are not yet available in membercache
1896 if ((state & StateFlags.PendingMemberCacheMembers) == 0) {
1897 open_type.MemberCacheTypes.InflateTypes (cache, inflator);
1900 // Inflate any implemented interfaces
1902 if (open_type.Interfaces != null) {
1903 ifaces = new List<TypeSpec> (open_type.Interfaces.Count);
1904 foreach (var iface in open_type.Interfaces) {
1905 var iface_inflated = inflator.Inflate (iface);
1906 if (iface_inflated == null)
1909 base.AddInterface (iface_inflated);
1914 // Handles the tricky case of recursive nested base generic type
1916 // class A<T> : Base<A<T>.Nested> {
1920 // When inflating A<T>. base type is not yet known, secondary
1921 // inflation is required (not common case) once base scope
1924 if (open_type.BaseType == null) {
1926 state |= StateFlags.PendingBaseTypeInflate;
1928 BaseType = inflator.Inflate (open_type.BaseType);
1930 } else if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1932 // It can happen when resolving base type without being defined
1933 // which is not allowed to happen and will always lead to an error
1935 // class B { class N {} }
1936 // class A<T> : A<B.N> {}
1938 if (open_type.BaseType == null)
1941 BaseType = inflator.Inflate (open_type.BaseType);
1942 state &= ~StateFlags.PendingBaseTypeInflate;
1946 state |= StateFlags.PendingMemberCacheMembers;
1950 var tc = open_type.MemberDefinition as TypeDefinition;
1951 if (tc != null && !tc.HasMembersDefined) {
1953 // Inflating MemberCache with undefined members
1958 if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1959 BaseType = inflator.Inflate (open_type.BaseType);
1960 state &= ~StateFlags.PendingBaseTypeInflate;
1963 state &= ~StateFlags.PendingMemberCacheMembers;
1964 open_type.MemberCache.InflateMembers (cache, open_type, inflator);
1967 public override TypeSpec Mutate (TypeParameterMutator mutator)
1969 var targs = TypeArguments;
1971 targs = mutator.Mutate (targs);
1973 var decl = DeclaringType;
1974 if (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
1975 decl = mutator.Mutate (decl);
1977 if (targs == TypeArguments && decl == DeclaringType)
1980 var mutated = (InflatedTypeSpec) MemberwiseClone ();
1981 if (decl != DeclaringType) {
1982 // Gets back MethodInfo in case of metaInfo was inflated
1983 //mutated.info = MemberCache.GetMember<TypeSpec> (DeclaringType.GetDefinition (), this).info;
1985 mutated.declaringType = decl;
1986 mutated.state |= StateFlags.PendingMetaInflate;
1989 if (targs != null) {
1990 mutated.targs = targs;
1991 mutated.info = null;
2000 // Tracks the type arguments when instantiating a generic type. It's used
2001 // by both type arguments and type parameters
2003 public class TypeArguments
2005 List<FullNamedExpression> args;
2008 public TypeArguments (params FullNamedExpression[] types)
2010 this.args = new List<FullNamedExpression> (types);
2013 public void Add (FullNamedExpression type)
2019 /// We may only be used after Resolve() is called and return the fully
2022 // TODO: Not needed, just return type from resolve
2023 public TypeSpec[] Arguments {
2038 public virtual bool IsEmpty {
2044 public List<FullNamedExpression> TypeExpressions {
2050 public string GetSignatureForError()
2052 StringBuilder sb = new StringBuilder ();
2053 for (int i = 0; i < Count; ++i) {
2056 sb.Append (expr.GetSignatureForError ());
2062 return sb.ToString ();
2066 /// Resolve the type arguments.
2068 public virtual bool Resolve (IMemberContext ec)
2071 return atypes.Length != 0;
2073 int count = args.Count;
2076 atypes = new TypeSpec [count];
2078 for (int i = 0; i < count; i++){
2079 var te = args[i].ResolveAsType (ec);
2088 ec.Module.Compiler.Report.Error (718, args[i].Location, "`{0}': static classes cannot be used as generic arguments",
2089 te.GetSignatureForError ());
2093 if (te.IsPointer || te.IsSpecialRuntimeType) {
2094 ec.Module.Compiler.Report.Error (306, args[i].Location,
2095 "The type `{0}' may not be used as a type argument",
2096 te.GetSignatureForError ());
2102 atypes = TypeSpec.EmptyTypes;
2107 public TypeArguments Clone ()
2109 TypeArguments copy = new TypeArguments ();
2110 foreach (var ta in args)
2117 public class UnboundTypeArguments : TypeArguments
2119 public UnboundTypeArguments (int arity)
2120 : base (new FullNamedExpression[arity])
2124 public override bool IsEmpty {
2130 public override bool Resolve (IMemberContext ec)
2132 // Nothing to be resolved
2137 public class TypeParameters
2139 List<TypeParameter> names;
2140 TypeParameterSpec[] types;
2142 public TypeParameters ()
2144 names = new List<TypeParameter> ();
2147 public TypeParameters (int count)
2149 names = new List<TypeParameter> (count);
2160 public TypeParameterSpec[] Types {
2168 public void Add (TypeParameter tparam)
2173 public void Add (TypeParameters tparams)
2175 names.AddRange (tparams.names);
2178 public void Define (GenericTypeParameterBuilder[] buiders, TypeSpec declaringType, int parentOffset, TypeContainer parent)
2180 types = new TypeParameterSpec[Count];
2181 for (int i = 0; i < types.Length; ++i) {
2184 tp.Define (buiders[i + parentOffset], declaringType, parent);
2186 types[i].DeclaredPosition = i + parentOffset;
2188 if (tp.Variance != Variance.None && !(declaringType != null && (declaringType.Kind == MemberKind.Interface || declaringType.Kind == MemberKind.Delegate))) {
2189 parent.Compiler.Report.Error (1960, tp.Location, "Variant type parameters can only be used with interfaces and delegates");
2194 public TypeParameter this[int index] {
2196 return names [index];
2199 names[index] = value;
2203 public TypeParameter Find (string name)
2205 foreach (var tp in names) {
2206 if (tp.Name == name)
2213 public string[] GetAllNames ()
2215 return names.Select (l => l.Name).ToArray ();
2218 public string GetSignatureForError ()
2220 StringBuilder sb = new StringBuilder ();
2221 for (int i = 0; i < Count; ++i) {
2225 var name = names[i];
2227 sb.Append (name.GetSignatureForError ());
2230 return sb.ToString ();
2233 public void VerifyClsCompliance ()
2235 foreach (var tp in names) {
2236 tp.VerifyClsCompliance ();
2242 // A type expression of generic type with type arguments
2244 class GenericTypeExpr : TypeExpr
2250 /// Instantiate the generic type `t' with the type arguments `args'.
2251 /// Use this constructor if you already know the fully resolved
2254 public GenericTypeExpr (TypeSpec open_type, TypeArguments args, Location l)
2256 this.open_type = open_type;
2261 public override string GetSignatureForError ()
2263 return type.GetSignatureForError ();
2266 public override TypeSpec ResolveAsType (IMemberContext mc)
2268 if (eclass != ExprClass.Unresolved)
2271 if (!args.Resolve (mc))
2274 TypeSpec[] atypes = args.Arguments;
2277 // Now bind the parameters
2279 var inflated = open_type.MakeGenericType (mc, atypes);
2281 eclass = ExprClass.Type;
2284 // The constraints can be checked only when full type hierarchy is known
2286 if (!inflated.HasConstraintsChecked && mc.Module.HasTypesFullyDefined) {
2287 var constraints = inflated.Constraints;
2288 if (constraints != null) {
2289 var cc = new ConstraintChecker (mc);
2290 if (cc.CheckAll (open_type, atypes, constraints, loc)) {
2291 inflated.HasConstraintsChecked = true;
2299 public override bool Equals (object obj)
2301 GenericTypeExpr cobj = obj as GenericTypeExpr;
2305 if ((type == null) || (cobj.type == null))
2308 return type == cobj.type;
2311 public override int GetHashCode ()
2313 return base.GetHashCode ();
2318 // Generic type with unbound type arguments, used for typeof (G<,,>)
2320 class GenericOpenTypeExpr : TypeExpression
2322 public GenericOpenTypeExpr (TypeSpec type, /*UnboundTypeArguments args,*/ Location loc)
2323 : base (type.GetDefinition (), loc)
2328 struct ConstraintChecker
2331 bool recursive_checks;
2333 public ConstraintChecker (IMemberContext ctx)
2336 recursive_checks = false;
2340 // Checks the constraints of open generic type against type
2341 // arguments. This version is used for types which could not be
2342 // checked immediatelly during construction because the type
2343 // hierarchy was not yet fully setup (before Emit phase)
2345 public static bool Check (IMemberContext mc, TypeSpec type, Location loc)
2348 // Check declaring type first if there is any
2350 if (type.DeclaringType != null && !Check (mc, type.DeclaringType, loc))
2353 while (type is ElementTypeSpec)
2354 type = ((ElementTypeSpec) type).Element;
2356 if (type.Arity == 0)
2359 var gtype = type as InflatedTypeSpec;
2363 var constraints = gtype.Constraints;
2364 if (constraints == null)
2367 if (gtype.HasConstraintsChecked)
2370 var cc = new ConstraintChecker (mc);
2371 cc.recursive_checks = true;
2373 if (cc.CheckAll (gtype.GetDefinition (), type.TypeArguments, constraints, loc)) {
2374 gtype.HasConstraintsChecked = true;
2382 // Checks all type arguments againts type parameters constraints
2383 // NOTE: It can run in probing mode when `this.mc' is null
2385 public bool CheckAll (MemberSpec context, TypeSpec[] targs, TypeParameterSpec[] tparams, Location loc)
2387 for (int i = 0; i < tparams.Length; i++) {
2388 var targ = targs[i];
2389 if (!CheckConstraint (context, targ, tparams [i], loc))
2392 if (!recursive_checks)
2395 if (!Check (mc, targ, loc))
2402 bool CheckConstraint (MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, Location loc)
2405 // First, check the `class' and `struct' constraints.
2407 if (tparam.HasSpecialClass && !TypeSpec.IsReferenceType (atype)) {
2409 mc.Module.Compiler.Report.Error (452, loc,
2410 "The type `{0}' must be a reference type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
2411 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
2417 if (tparam.HasSpecialStruct && (!TypeSpec.IsValueType (atype) || atype.IsNullableType)) {
2419 mc.Module.Compiler.Report.Error (453, loc,
2420 "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}'",
2421 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
2430 // Check the class constraint
2432 if (tparam.HasTypeConstraint) {
2433 if (!CheckConversion (mc, context, atype, tparam, tparam.BaseType, loc)) {
2442 // Check the interfaces constraints
2444 if (tparam.Interfaces != null) {
2445 foreach (TypeSpec iface in tparam.Interfaces) {
2446 if (!CheckConversion (mc, context, atype, tparam, iface, loc)) {
2457 // Check the type parameter constraint
2459 if (tparam.TypeArguments != null) {
2460 foreach (var ta in tparam.TypeArguments) {
2461 if (!CheckConversion (mc, context, atype, tparam, ta, loc)) {
2472 // Finally, check the constructor constraint.
2474 if (!tparam.HasSpecialConstructor)
2477 if (!HasDefaultConstructor (atype)) {
2479 mc.Module.Compiler.Report.SymbolRelatedToPreviousError (atype);
2480 mc.Module.Compiler.Report.Error (310, loc,
2481 "The type `{0}' must have a public parameterless constructor in order to use it as parameter `{1}' in the generic type or method `{2}'",
2482 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
2490 static bool HasDynamicTypeArgument (TypeSpec[] targs)
2492 for (int i = 0; i < targs.Length; ++i) {
2493 var targ = targs [i];
2494 if (targ.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2497 if (HasDynamicTypeArgument (targ.TypeArguments))
2504 bool CheckConversion (IMemberContext mc, MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, TypeSpec ttype, Location loc)
2509 if (atype.IsGenericParameter) {
2510 var tps = (TypeParameterSpec) atype;
2511 if (tps.HasDependencyOn (ttype))
2514 if (Convert.ImplicitTypeParameterConversion (null, tps, ttype) != null)
2517 } else if (TypeSpec.IsValueType (atype)) {
2518 if (atype.IsNullableType) {
2520 // LAMESPEC: Only identity or base type ValueType or Object satisfy nullable type
2522 if (TypeSpec.IsBaseClass (atype, ttype, false))
2525 if (Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
2529 if (Convert.ImplicitReferenceConversionExists (atype, ttype) || Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
2534 mc.Module.Compiler.Report.SymbolRelatedToPreviousError (tparam);
2535 if (atype.IsGenericParameter) {
2536 mc.Module.Compiler.Report.Error (314, loc,
2537 "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}'",
2538 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2539 } else if (TypeSpec.IsValueType (atype)) {
2540 if (atype.IsNullableType) {
2541 if (ttype.IsInterface) {
2542 mc.Module.Compiler.Report.Error (313, loc,
2543 "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}'",
2544 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2546 mc.Module.Compiler.Report.Error (312, loc,
2547 "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}'",
2548 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2551 mc.Module.Compiler.Report.Error (315, loc,
2552 "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}'",
2553 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2556 mc.Module.Compiler.Report.Error (311, loc,
2557 "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}'",
2558 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2565 static bool HasDefaultConstructor (TypeSpec atype)
2567 var tp = atype as TypeParameterSpec;
2569 return tp.HasSpecialConstructor || tp.HasSpecialStruct;
2572 if (atype.IsStruct || atype.IsEnum)
2575 if (atype.IsAbstract)
2578 var tdef = atype.GetDefinition ();
2580 var found = MemberCache.FindMember (tdef,
2581 MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters),
2582 BindingRestriction.DeclaredOnly | BindingRestriction.InstanceOnly);
2584 return found != null && (found.Modifiers & Modifiers.PUBLIC) != 0;
2588 public partial class TypeManager
2590 public static Variance CheckTypeVariance (TypeSpec t, Variance expected, IMemberContext member)
2592 var tp = t as TypeParameterSpec;
2594 Variance v = tp.Variance;
2595 if (expected == Variance.None && v != expected ||
2596 expected == Variance.Covariant && v == Variance.Contravariant ||
2597 expected == Variance.Contravariant && v == Variance.Covariant) {
2598 ((TypeParameter)tp.MemberDefinition).ErrorInvalidVariance (member, expected);
2604 if (t.TypeArguments.Length > 0) {
2605 var targs_definition = t.MemberDefinition.TypeParameters;
2606 TypeSpec[] targs = GetTypeArguments (t);
2607 for (int i = 0; i < targs.Length; ++i) {
2608 Variance v = targs_definition[i].Variance;
2609 CheckTypeVariance (targs[i], (Variance) ((int)v * (int)expected), member);
2616 return CheckTypeVariance (GetElementType (t), expected, member);
2618 return Variance.None;
2623 // Implements C# type inference
2628 // Tracks successful rate of type inference
2630 int score = int.MaxValue;
2631 readonly Arguments arguments;
2632 readonly int arg_count;
2634 public TypeInference (Arguments arguments)
2636 this.arguments = arguments;
2637 if (arguments != null)
2638 arg_count = arguments.Count;
2641 public int InferenceScore {
2647 public TypeSpec[] InferMethodArguments (ResolveContext ec, MethodSpec method)
2649 var method_generic_args = method.GenericDefinition.TypeParameters;
2650 TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2651 if (!context.UnfixedVariableExists)
2652 return TypeSpec.EmptyTypes;
2654 AParametersCollection pd = method.Parameters;
2655 if (!InferInPhases (ec, context, pd))
2658 return context.InferredTypeArguments;
2662 // Implements method type arguments inference
2664 bool InferInPhases (ResolveContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
2666 int params_arguments_start;
2667 if (methodParameters.HasParams) {
2668 params_arguments_start = methodParameters.Count - 1;
2670 params_arguments_start = arg_count;
2673 TypeSpec [] ptypes = methodParameters.Types;
2676 // The first inference phase
2678 TypeSpec method_parameter = null;
2679 for (int i = 0; i < arg_count; i++) {
2680 Argument a = arguments [i];
2684 if (i < params_arguments_start) {
2685 method_parameter = methodParameters.Types [i];
2686 } else if (i == params_arguments_start) {
2687 if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2688 method_parameter = methodParameters.Types [params_arguments_start];
2690 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2692 ptypes = (TypeSpec[]) ptypes.Clone ();
2693 ptypes [i] = method_parameter;
2697 // When a lambda expression, an anonymous method
2698 // is used an explicit argument type inference takes a place
2700 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2702 if (am.ExplicitTypeInference (ec, tic, method_parameter))
2708 score -= tic.ExactInference (a.Type, method_parameter);
2712 if (a.Expr.Type == InternalType.NullLiteral)
2715 if (TypeSpec.IsValueType (method_parameter)) {
2716 score -= tic.LowerBoundInference (a.Type, method_parameter);
2721 // Otherwise an output type inference is made
2723 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2727 // Part of the second phase but because it happens only once
2728 // we don't need to call it in cycle
2730 bool fixed_any = false;
2731 if (!tic.FixIndependentTypeArguments (ec, ptypes, ref fixed_any))
2734 return DoSecondPhase (ec, tic, ptypes, !fixed_any);
2737 bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, TypeSpec[] methodParameters, bool fixDependent)
2739 bool fixed_any = false;
2740 if (fixDependent && !tic.FixDependentTypes (ec, ref fixed_any))
2743 // If no further unfixed type variables exist, type inference succeeds
2744 if (!tic.UnfixedVariableExists)
2747 if (!fixed_any && fixDependent)
2750 // For all arguments where the corresponding argument output types
2751 // contain unfixed type variables but the input types do not,
2752 // an output type inference is made
2753 for (int i = 0; i < arg_count; i++) {
2755 // Align params arguments
2756 TypeSpec t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
2758 if (!t_i.IsDelegate) {
2759 if (!t_i.IsExpressionTreeType)
2762 t_i = TypeManager.GetTypeArguments (t_i) [0];
2765 var mi = Delegate.GetInvokeMethod (t_i);
2766 TypeSpec rtype = mi.ReturnType;
2768 if (tic.IsReturnTypeNonDependent (ec, mi, rtype)) {
2769 // It can be null for default arguments
2770 if (arguments[i] == null)
2773 score -= tic.OutputTypeInference (ec, arguments[i].Expr, t_i);
2778 return DoSecondPhase (ec, tic, methodParameters, true);
2782 public class TypeInferenceContext
2784 protected enum BoundKind
2791 struct BoundInfo : IEquatable<BoundInfo>
2793 public readonly TypeSpec Type;
2794 public readonly BoundKind Kind;
2796 public BoundInfo (TypeSpec type, BoundKind kind)
2802 public override int GetHashCode ()
2804 return Type.GetHashCode ();
2807 public Expression GetTypeExpression ()
2809 return new TypeExpression (Type, Location.Null);
2812 #region IEquatable<BoundInfo> Members
2814 public bool Equals (BoundInfo other)
2816 return Type == other.Type && Kind == other.Kind;
2822 readonly TypeSpec[] tp_args;
2823 readonly TypeSpec[] fixed_types;
2824 readonly List<BoundInfo>[] bounds;
2827 // TODO MemberCache: Could it be TypeParameterSpec[] ??
2828 public TypeInferenceContext (TypeSpec[] typeArguments)
2830 if (typeArguments.Length == 0)
2831 throw new ArgumentException ("Empty generic arguments");
2833 fixed_types = new TypeSpec [typeArguments.Length];
2834 for (int i = 0; i < typeArguments.Length; ++i) {
2835 if (typeArguments [i].IsGenericParameter) {
2836 if (bounds == null) {
2837 bounds = new List<BoundInfo> [typeArguments.Length];
2838 tp_args = new TypeSpec [typeArguments.Length];
2840 tp_args [i] = typeArguments [i];
2842 fixed_types [i] = typeArguments [i];
2848 // Used together with AddCommonTypeBound fo implement
2849 // 7.4.2.13 Finding the best common type of a set of expressions
2851 public TypeInferenceContext ()
2853 fixed_types = new TypeSpec [1];
2854 tp_args = new TypeSpec [1];
2855 tp_args[0] = InternalType.Arglist; // it can be any internal type
2856 bounds = new List<BoundInfo> [1];
2859 public TypeSpec[] InferredTypeArguments {
2865 public void AddCommonTypeBound (TypeSpec type)
2867 AddToBounds (new BoundInfo (type, BoundKind.Lower), 0);
2870 void AddToBounds (BoundInfo bound, int index)
2873 // Some types cannot be used as type arguments
2875 if (bound.Type.Kind == MemberKind.Void || bound.Type.IsPointer || bound.Type.IsSpecialRuntimeType ||
2876 bound.Type == InternalType.MethodGroup || bound.Type == InternalType.AnonymousMethod)
2879 var a = bounds [index];
2881 a = new List<BoundInfo> (2);
2887 if (a.Contains (bound))
2893 bool AllTypesAreFixed (TypeSpec[] types)
2895 foreach (TypeSpec t in types) {
2896 if (t.IsGenericParameter) {
2902 if (TypeManager.IsGenericType (t))
2903 return AllTypesAreFixed (TypeManager.GetTypeArguments (t));
2910 // 26.3.3.8 Exact Inference
2912 public int ExactInference (TypeSpec u, TypeSpec v)
2914 // If V is an array type
2919 var ac_u = (ArrayContainer) u;
2920 var ac_v = (ArrayContainer) v;
2921 if (ac_u.Rank != ac_v.Rank)
2924 return ExactInference (ac_u.Element, ac_v.Element);
2927 // If V is constructed type and U is constructed type
2928 if (TypeManager.IsGenericType (v)) {
2929 if (!TypeManager.IsGenericType (u) || v.MemberDefinition != u.MemberDefinition)
2932 TypeSpec [] ga_u = TypeManager.GetTypeArguments (u);
2933 TypeSpec [] ga_v = TypeManager.GetTypeArguments (v);
2934 if (ga_u.Length != ga_v.Length)
2938 for (int i = 0; i < ga_u.Length; ++i)
2939 score += ExactInference (ga_u [i], ga_v [i]);
2941 return System.Math.Min (1, score);
2944 // If V is one of the unfixed type arguments
2945 int pos = IsUnfixed (v);
2949 AddToBounds (new BoundInfo (u, BoundKind.Exact), pos);
2953 public bool FixAllTypes (ResolveContext ec)
2955 for (int i = 0; i < tp_args.Length; ++i) {
2956 if (!FixType (ec, i))
2963 // All unfixed type variables Xi are fixed for which all of the following hold:
2964 // a, There is at least one type variable Xj that depends on Xi
2965 // b, Xi has a non-empty set of bounds
2967 public bool FixDependentTypes (ResolveContext ec, ref bool fixed_any)
2969 for (int i = 0; i < tp_args.Length; ++i) {
2970 if (fixed_types[i] != null)
2973 if (bounds[i] == null)
2976 if (!FixType (ec, i))
2986 // All unfixed type variables Xi which depend on no Xj are fixed
2988 public bool FixIndependentTypeArguments (ResolveContext ec, TypeSpec[] methodParameters, ref bool fixed_any)
2990 var types_to_fix = new List<TypeSpec> (tp_args);
2991 for (int i = 0; i < methodParameters.Length; ++i) {
2992 TypeSpec t = methodParameters[i];
2994 if (!t.IsDelegate) {
2995 if (!t.IsExpressionTreeType)
2998 t = TypeManager.GetTypeArguments (t) [0];
3001 if (t.IsGenericParameter)
3004 var invoke = Delegate.GetInvokeMethod (t);
3005 TypeSpec rtype = invoke.ReturnType;
3006 while (rtype.IsArray)
3007 rtype = ((ArrayContainer) rtype).Element;
3009 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
3012 // Remove dependent types, they cannot be fixed yet
3013 RemoveDependentTypes (types_to_fix, rtype);
3016 foreach (TypeSpec t in types_to_fix) {
3020 int idx = IsUnfixed (t);
3021 if (idx >= 0 && !FixType (ec, idx)) {
3026 fixed_any = types_to_fix.Count > 0;
3033 public bool FixType (ResolveContext ec, int i)
3035 // It's already fixed
3036 if (fixed_types[i] != null)
3037 throw new InternalErrorException ("Type argument has been already fixed");
3042 var candidates = bounds [i];
3043 if (candidates == null)
3046 if (candidates.Count == 1) {
3047 TypeSpec t = candidates[0].Type;
3048 if (t == InternalType.NullLiteral)
3051 fixed_types [i] = t;
3056 // Determines a unique type from which there is
3057 // a standard implicit conversion to all the other
3060 TypeSpec best_candidate = null;
3062 int candidates_count = candidates.Count;
3063 for (int ci = 0; ci < candidates_count; ++ci) {
3064 BoundInfo bound = candidates [ci];
3065 for (cii = 0; cii < candidates_count; ++cii) {
3069 BoundInfo cbound = candidates[cii];
3071 // Same type parameters with different bounds
3072 if (cbound.Type == bound.Type) {
3073 if (bound.Kind != BoundKind.Exact)
3079 if (bound.Kind == BoundKind.Exact || cbound.Kind == BoundKind.Exact) {
3080 if (cbound.Kind == BoundKind.Lower) {
3081 if (!Convert.ImplicitConversionExists (ec, cbound.GetTypeExpression (), bound.Type)) {
3087 if (cbound.Kind == BoundKind.Upper) {
3088 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
3095 if (bound.Kind != BoundKind.Exact) {
3096 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
3107 if (bound.Kind == BoundKind.Lower) {
3108 if (cbound.Kind == BoundKind.Lower) {
3109 if (!Convert.ImplicitConversionExists (ec, cbound.GetTypeExpression (), bound.Type)) {
3113 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
3123 if (bound.Kind == BoundKind.Upper) {
3124 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
3128 throw new NotImplementedException ("variance conversion");
3132 if (cii != candidates_count)
3136 // We already have the best candidate, break if thet are different
3138 // Dynamic is never ambiguous as we prefer dynamic over other best candidate types
3140 if (best_candidate != null) {
3142 if (best_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3145 if (bound.Type.BuiltinType != BuiltinTypeSpec.Type.Dynamic && best_candidate != bound.Type)
3149 best_candidate = bound.Type;
3152 if (best_candidate == null)
3155 fixed_types[i] = best_candidate;
3159 public bool HasBounds (int pos)
3161 return bounds[pos] != null;
3165 // Uses inferred or partially infered types to inflate delegate type argument. Returns
3166 // null when type parameter has not been fixed
3168 public TypeSpec InflateGenericArgument (IModuleContext context, TypeSpec parameter)
3170 var tp = parameter as TypeParameterSpec;
3173 // Type inference works on generic arguments (MVAR) only
3175 if (!tp.IsMethodOwned)
3179 // Ensure the type parameter belongs to same container
3181 if (tp.DeclaredPosition < tp_args.Length && tp_args[tp.DeclaredPosition] == parameter)
3182 return fixed_types[tp.DeclaredPosition] ?? parameter;
3187 var gt = parameter as InflatedTypeSpec;
3189 var inflated_targs = new TypeSpec [gt.TypeArguments.Length];
3190 for (int ii = 0; ii < inflated_targs.Length; ++ii) {
3191 var inflated = InflateGenericArgument (context, gt.TypeArguments [ii]);
3192 if (inflated == null)
3195 inflated_targs[ii] = inflated;
3198 return gt.GetDefinition ().MakeGenericType (context, inflated_targs);
3201 var ac = parameter as ArrayContainer;
3203 var inflated = InflateGenericArgument (context, ac.Element);
3204 if (inflated != ac.Element)
3205 return ArrayContainer.MakeType (context.Module, inflated);
3212 // Tests whether all delegate input arguments are fixed and generic output type
3213 // requires output type inference
3215 public bool IsReturnTypeNonDependent (ResolveContext ec, MethodSpec invoke, TypeSpec returnType)
3217 while (returnType.IsArray)
3218 returnType = ((ArrayContainer) returnType).Element;
3220 if (returnType.IsGenericParameter) {
3221 if (IsFixed (returnType))
3223 } else if (TypeManager.IsGenericType (returnType)) {
3224 if (returnType.IsDelegate) {
3225 invoke = Delegate.GetInvokeMethod (returnType);
3226 return IsReturnTypeNonDependent (ec, invoke, invoke.ReturnType);
3229 TypeSpec[] g_args = TypeManager.GetTypeArguments (returnType);
3231 // At least one unfixed return type has to exist
3232 if (AllTypesAreFixed (g_args))
3238 // All generic input arguments have to be fixed
3239 AParametersCollection d_parameters = invoke.Parameters;
3240 return AllTypesAreFixed (d_parameters.Types);
3243 bool IsFixed (TypeSpec type)
3245 return IsUnfixed (type) == -1;
3248 int IsUnfixed (TypeSpec type)
3250 if (!type.IsGenericParameter)
3253 for (int i = 0; i < tp_args.Length; ++i) {
3254 if (tp_args[i] == type) {
3255 if (fixed_types[i] != null)
3266 // 26.3.3.9 Lower-bound Inference
3268 public int LowerBoundInference (TypeSpec u, TypeSpec v)
3270 return LowerBoundInference (u, v, false);
3274 // Lower-bound (false) or Upper-bound (true) inference based on inversed argument
3276 int LowerBoundInference (TypeSpec u, TypeSpec v, bool inversed)
3278 // If V is one of the unfixed type arguments
3279 int pos = IsUnfixed (v);
3281 AddToBounds (new BoundInfo (u, inversed ? BoundKind.Upper : BoundKind.Lower), pos);
3285 // If U is an array type
3286 var u_ac = u as ArrayContainer;
3288 var v_ac = v as ArrayContainer;
3290 if (u_ac.Rank != v_ac.Rank)
3293 if (TypeSpec.IsValueType (u_ac.Element))
3294 return ExactInference (u_ac.Element, v_ac.Element);
3296 return LowerBoundInference (u_ac.Element, v_ac.Element, inversed);
3299 if (u_ac.Rank != 1 || !v.IsGenericIterateInterface)
3302 var v_i = TypeManager.GetTypeArguments (v) [0];
3303 if (TypeSpec.IsValueType (u_ac.Element))
3304 return ExactInference (u_ac.Element, v_i);
3306 return LowerBoundInference (u_ac.Element, v_i);
3309 if (v.IsGenericOrParentIsGeneric) {
3311 // if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
3312 // such that U is identical to, inherits from (directly or indirectly),
3313 // or implements (directly or indirectly) C<U1..Uk>
3315 var u_candidates = new List<TypeSpec> ();
3316 var open_v = v.MemberDefinition;
3318 for (TypeSpec t = u; t != null; t = t.BaseType) {
3319 if (open_v == t.MemberDefinition)
3320 u_candidates.Add (t);
3323 // Using this trick for dynamic type inference, the spec says the type arguments are "unknown" but
3324 // that would complicate the process a lot, instead I treat them as dynamic
3326 if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3327 u_candidates.Add (t);
3330 if (u.Interfaces != null) {
3331 foreach (var iface in u.Interfaces) {
3332 if (open_v == iface.MemberDefinition)
3333 u_candidates.Add (iface);
3337 TypeSpec[] unique_candidate_targs = null;
3338 var ga_v = TypeSpec.GetAllTypeArguments (v);
3339 foreach (TypeSpec u_candidate in u_candidates) {
3341 // The unique set of types U1..Uk means that if we have an interface I<T>,
3342 // class U : I<int>, I<long> then no type inference is made when inferring
3343 // type I<T> by applying type U because T could be int or long
3345 if (unique_candidate_targs != null) {
3346 TypeSpec[] second_unique_candidate_targs = TypeSpec.GetAllTypeArguments (u_candidate);
3347 if (TypeSpecComparer.Equals (unique_candidate_targs, second_unique_candidate_targs)) {
3348 unique_candidate_targs = second_unique_candidate_targs;
3353 // This should always cause type inference failure
3360 // A candidate is dynamic type expression, to simplify things use dynamic
3361 // for all type parameter of this type. For methods like this one
3363 // void M<T, U> (IList<T>, IList<U[]>)
3365 // dynamic becomes both T and U when the arguments are of dynamic type
3367 if (u_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
3368 unique_candidate_targs = new TypeSpec[ga_v.Length];
3369 for (int i = 0; i < unique_candidate_targs.Length; ++i)
3370 unique_candidate_targs[i] = u_candidate;
3372 unique_candidate_targs = TypeSpec.GetAllTypeArguments (u_candidate);
3376 if (unique_candidate_targs != null) {
3379 TypeParameterSpec[] tps = null;
3381 for (int i = 0; i < unique_candidate_targs.Length; ++i) {
3383 while (v.Arity == 0)
3384 v = v.DeclaringType;
3386 tps = v.MemberDefinition.TypeParameters;
3387 tp_index = tps.Length - 1;
3390 Variance variance = tps [tp_index--].Variance;
3392 TypeSpec u_i = unique_candidate_targs [i];
3393 if (variance == Variance.None || TypeSpec.IsValueType (u_i)) {
3394 if (ExactInference (u_i, ga_v [i]) == 0)
3397 bool upper_bound = (variance == Variance.Contravariant && !inversed) ||
3398 (variance == Variance.Covariant && inversed);
3400 if (LowerBoundInference (u_i, ga_v [i], upper_bound) == 0)
3413 // 26.3.3.6 Output Type Inference
3415 public int OutputTypeInference (ResolveContext ec, Expression e, TypeSpec t)
3417 // If e is a lambda or anonymous method with inferred return type
3418 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
3420 TypeSpec rt = ame.InferReturnType (ec, this, t);
3421 var invoke = Delegate.GetInvokeMethod (t);
3424 AParametersCollection pd = invoke.Parameters;
3425 return ame.Parameters.Count == pd.Count ? 1 : 0;
3428 TypeSpec rtype = invoke.ReturnType;
3429 return LowerBoundInference (rt, rtype) + 1;
3433 // if E is a method group and T is a delegate type or expression tree type
3434 // return type Tb with parameter types T1..Tk and return type Tb, and overload
3435 // resolution of E with the types T1..Tk yields a single method with return type U,
3436 // then a lower-bound inference is made from U for Tb.
3438 if (e is MethodGroupExpr) {
3439 if (!t.IsDelegate) {
3440 if (!t.IsExpressionTreeType)
3443 t = TypeManager.GetTypeArguments (t)[0];
3446 var invoke = Delegate.GetInvokeMethod (t);
3447 TypeSpec rtype = invoke.ReturnType;
3449 if (!IsReturnTypeNonDependent (ec, invoke, rtype))
3452 // LAMESPEC: Standard does not specify that all methodgroup arguments
3453 // has to be fixed but it does not specify how to do recursive type inference
3454 // either. We choose the simple option and infer return type only
3455 // if all delegate generic arguments are fixed.
3456 TypeSpec[] param_types = new TypeSpec [invoke.Parameters.Count];
3457 for (int i = 0; i < param_types.Length; ++i) {
3458 var inflated = InflateGenericArgument (ec, invoke.Parameters.Types[i]);
3459 if (inflated == null)
3462 param_types[i] = inflated;
3465 MethodGroupExpr mg = (MethodGroupExpr) e;
3466 Arguments args = DelegateCreation.CreateDelegateMethodArguments (ec, invoke.Parameters, param_types, e.Location);
3467 mg = mg.OverloadResolve (ec, ref args, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
3471 return LowerBoundInference (mg.BestCandidateReturnType, rtype) + 1;
3475 // if e is an expression with type U, then
3476 // a lower-bound inference is made from U for T
3478 return LowerBoundInference (e.Type, t) * 2;
3481 void RemoveDependentTypes (List<TypeSpec> types, TypeSpec returnType)
3483 int idx = IsUnfixed (returnType);
3489 if (TypeManager.IsGenericType (returnType)) {
3490 foreach (TypeSpec t in TypeManager.GetTypeArguments (returnType)) {
3491 RemoveDependentTypes (types, t);
3496 public bool UnfixedVariableExists {
3498 foreach (TypeSpec ut in fixed_types) {